max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
dss/storage/bundles.py
DataBiosphere/data-store
3
6630451
import io from functools import lru_cache import json import typing import time import re from collections import OrderedDict import cachetools from cloud_blobstore import BlobNotFoundError, BlobStore from dss import Config, Replica from dss.api.search import PerPageBounds from dss.storage.identifiers import (DSS_BUNDLE_KEY_REGEX, TOMBSTONE_SUFFIX, BUNDLE_PREFIX, BundleTombstoneID, DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, BundleFQID, UUID_PATTERN, DSS_UNVERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, VERSION_PATTERN,) from dss.storage.blobstore import test_object_exists, idempotent_save from dss.util import multipart_parallel_upload _cache_key_template = "{replica}{fqid}" _bundle_manifest_cache = cachetools.LRUCache(maxsize=4) def get_bundle_manifest( uuid: str, replica: Replica, version: typing.Optional[str], *, bucket: typing.Optional[str] = None) -> typing.Optional[dict]: cache_key = _cache_key_template.format(replica=replica.name, fqid=BundleFQID(uuid, version).to_key()) if cache_key in _bundle_manifest_cache: return _bundle_manifest_cache[cache_key] else: bundle = _get_bundle_manifest(uuid, replica, version, bucket=bucket) if bundle is not None: _bundle_manifest_cache[cache_key] = bundle return bundle def _get_bundle_manifest( uuid: str, replica: Replica, version: typing.Optional[str], *, bucket: typing.Optional[str] = None) -> typing.Optional[dict]: """ Return the contents of the bundle manifest file from cloud storage, subject to the rules of tombstoning. If version is None, return the latest version, once again, subject to the rules of tombstoning. If the bundle cannot be found, return None """ uuid = uuid.lower() handle = Config.get_blobstore_handle(replica) default_bucket = replica.bucket # need the ability to use fixture bucket for testing bucket = default_bucket if bucket is None else bucket def tombstone_exists(uuid: str, version: typing.Optional[str]): return test_object_exists(handle, bucket, BundleTombstoneID(uuid=uuid, version=version).to_key()) # handle the following deletion cases # 1. the whole bundle is deleted # 2. the specific version of the bundle is deleted if tombstone_exists(uuid, None) or (version and tombstone_exists(uuid, version)): return None # handle the following deletion case # 3. no version is specified, we want the latest _non-deleted_ version if version is None: # list the files and find the one that is the most recent. prefix = f"bundles/{uuid}." object_names = handle.list(bucket, prefix) version = _latest_version_from_object_names(object_names) if version is None: # no matches! return None bundle_fqid = BundleFQID(uuid=uuid, version=version) # retrieve the bundle metadata. try: bundle_manifest_blob = handle.get(bucket, bundle_fqid.to_key()).decode("utf-8") return json.loads(bundle_manifest_blob) except BlobNotFoundError: return None def save_bundle_manifest(replica: Replica, uuid: str, version: str, bundle: dict) -> typing.Tuple[bool, bool]: handle = Config.get_blobstore_handle(replica) data = json.dumps(bundle).encode("utf-8") fqid = BundleFQID(uuid, version).to_key() created, idempotent = idempotent_save(handle, replica.bucket, fqid, data) if created and idempotent: cache_key = _cache_key_template.format(replica=replica.name, fqid=fqid) _bundle_manifest_cache[cache_key] = bundle return created, idempotent def _latest_version_from_object_names(object_names: typing.Iterator[str]) -> str: dead_versions = set() # type: typing.Set[str] all_versions = set() # type: typing.Set[str] set_checks = [ (DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, dead_versions), (DSS_BUNDLE_KEY_REGEX, all_versions), ] for object_name in object_names: for regex, version_set in set_checks: match = regex.match(object_name) if match: _, version = match.groups() version_set.add(version) break version = None for current_version in (all_versions - dead_versions): if version is None or current_version > version: version = current_version return version def enumerate_available_bundles(replica: str = None, prefix: typing.Optional[str] = None, per_page: int = PerPageBounds.per_page_max, search_after: typing.Optional[str] = None, token: typing.Optional[str] = None): """ :returns: dictionary with bundles that are available, provides context of cloud providers internal pagination mechanism. :rtype: dictionary """ kwargs = dict(bucket=Replica[replica].bucket, prefix=prefix, k_page_max=per_page) if search_after: kwargs['start_after_key'] = search_after if token: kwargs['token'] = token storage_handler = Config.get_blobstore_handle(Replica[replica]) prefix_iterator = Living(storage_handler.list_v2(**kwargs)) # note dont wrap this in enumerate; it looses the token uuid_list = list() for fqid in prefix_iterator: uuid_list.append(dict(uuid=fqid.uuid, version=fqid.version)) if len(uuid_list) >= per_page: break return dict(search_after=prefix_iterator.start_after_key, bundles=uuid_list, token=prefix_iterator.token, page_count=len(uuid_list)) class Living(): """ This utility class takes advantage of lexicographical ordering on object storage to list non-tombstoned bundles. """ def __init__(self, paged_iter): self.paged_iter = paged_iter self._init_bundle_info() self.start_after_key = None self.token = None def _init_bundle_info(self, fqid=None): self.bundle_info = dict(contains_unversioned_tombstone=False, uuid=None, fqids=OrderedDict()) if fqid: self.bundle_info['uuid'] = fqid.uuid self.bundle_info['fqids'][fqid] = False def _living_fqids_in_bundle_info(self): if not self.bundle_info['contains_unversioned_tombstone']: for fqid, is_dead in self.bundle_info['fqids'].items(): if not is_dead: yield fqid def _keys(self): for key, _ in self.paged_iter: yield key self.start_after_key = key self.token = getattr(self.paged_iter, "token", None) def __iter__(self): for key in self._keys(): fqid = BundleFQID.from_key(key) if fqid.uuid != self.bundle_info['uuid']: for bundle_fqid in self._living_fqids_in_bundle_info(): yield bundle_fqid self._init_bundle_info(fqid) else: if not fqid.is_fully_qualified(): self.bundle_info['contains_unversioned_tombstone'] = True else: self.bundle_info['fqids'][fqid] = isinstance(fqid, BundleTombstoneID) for bundle_fqid in self._living_fqids_in_bundle_info(): yield bundle_fqid def get_tombstoned_bundles(replica: Replica, tombstone_key: str) -> typing.Iterator[str]: """ Return the bundle fqid(s) associated with a versioned or unversioned tombstone, as verified on object storage. Note that an unversioned tombstone returns keys associated with bundles not previously, as show in the example below. bundles/uuid.version1 bundles/uuid.version2 bundles/uuid.version2.dead bundles/uuid.version3 bundles/uuid.version3.dead bundles/uuid.dead For the above listing: `get_tombstoned_bundles(replica, bundles/uuid.version2.dead)` -> `[bundles/uuid.version2]` `get_tombstoned_bundles(replica, bundles/uuid.dead)` -> `[bundles/uuid.version1]` """ handle = Config.get_blobstore_handle(replica) if DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX.match(tombstone_key): pfx = tombstone_key.split(f".{TOMBSTONE_SUFFIX}")[0] prev_key = "" for key in handle.list(replica.bucket, pfx): if key == f"{prev_key}.{TOMBSTONE_SUFFIX}": yield prev_key prev_key = key elif DSS_UNVERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX.match(tombstone_key): pfx = tombstone_key.split(f".{TOMBSTONE_SUFFIX}")[0] prev_key = "" for key in handle.list(replica.bucket, pfx): if key != f"{prev_key}.{TOMBSTONE_SUFFIX}" and not prev_key.endswith(TOMBSTONE_SUFFIX): if prev_key: yield prev_key prev_key = key else: raise ValueError(f"{tombstone_key} is not a tombstone key")
import io from functools import lru_cache import json import typing import time import re from collections import OrderedDict import cachetools from cloud_blobstore import BlobNotFoundError, BlobStore from dss import Config, Replica from dss.api.search import PerPageBounds from dss.storage.identifiers import (DSS_BUNDLE_KEY_REGEX, TOMBSTONE_SUFFIX, BUNDLE_PREFIX, BundleTombstoneID, DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, BundleFQID, UUID_PATTERN, DSS_UNVERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, VERSION_PATTERN,) from dss.storage.blobstore import test_object_exists, idempotent_save from dss.util import multipart_parallel_upload _cache_key_template = "{replica}{fqid}" _bundle_manifest_cache = cachetools.LRUCache(maxsize=4) def get_bundle_manifest( uuid: str, replica: Replica, version: typing.Optional[str], *, bucket: typing.Optional[str] = None) -> typing.Optional[dict]: cache_key = _cache_key_template.format(replica=replica.name, fqid=BundleFQID(uuid, version).to_key()) if cache_key in _bundle_manifest_cache: return _bundle_manifest_cache[cache_key] else: bundle = _get_bundle_manifest(uuid, replica, version, bucket=bucket) if bundle is not None: _bundle_manifest_cache[cache_key] = bundle return bundle def _get_bundle_manifest( uuid: str, replica: Replica, version: typing.Optional[str], *, bucket: typing.Optional[str] = None) -> typing.Optional[dict]: """ Return the contents of the bundle manifest file from cloud storage, subject to the rules of tombstoning. If version is None, return the latest version, once again, subject to the rules of tombstoning. If the bundle cannot be found, return None """ uuid = uuid.lower() handle = Config.get_blobstore_handle(replica) default_bucket = replica.bucket # need the ability to use fixture bucket for testing bucket = default_bucket if bucket is None else bucket def tombstone_exists(uuid: str, version: typing.Optional[str]): return test_object_exists(handle, bucket, BundleTombstoneID(uuid=uuid, version=version).to_key()) # handle the following deletion cases # 1. the whole bundle is deleted # 2. the specific version of the bundle is deleted if tombstone_exists(uuid, None) or (version and tombstone_exists(uuid, version)): return None # handle the following deletion case # 3. no version is specified, we want the latest _non-deleted_ version if version is None: # list the files and find the one that is the most recent. prefix = f"bundles/{uuid}." object_names = handle.list(bucket, prefix) version = _latest_version_from_object_names(object_names) if version is None: # no matches! return None bundle_fqid = BundleFQID(uuid=uuid, version=version) # retrieve the bundle metadata. try: bundle_manifest_blob = handle.get(bucket, bundle_fqid.to_key()).decode("utf-8") return json.loads(bundle_manifest_blob) except BlobNotFoundError: return None def save_bundle_manifest(replica: Replica, uuid: str, version: str, bundle: dict) -> typing.Tuple[bool, bool]: handle = Config.get_blobstore_handle(replica) data = json.dumps(bundle).encode("utf-8") fqid = BundleFQID(uuid, version).to_key() created, idempotent = idempotent_save(handle, replica.bucket, fqid, data) if created and idempotent: cache_key = _cache_key_template.format(replica=replica.name, fqid=fqid) _bundle_manifest_cache[cache_key] = bundle return created, idempotent def _latest_version_from_object_names(object_names: typing.Iterator[str]) -> str: dead_versions = set() # type: typing.Set[str] all_versions = set() # type: typing.Set[str] set_checks = [ (DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX, dead_versions), (DSS_BUNDLE_KEY_REGEX, all_versions), ] for object_name in object_names: for regex, version_set in set_checks: match = regex.match(object_name) if match: _, version = match.groups() version_set.add(version) break version = None for current_version in (all_versions - dead_versions): if version is None or current_version > version: version = current_version return version def enumerate_available_bundles(replica: str = None, prefix: typing.Optional[str] = None, per_page: int = PerPageBounds.per_page_max, search_after: typing.Optional[str] = None, token: typing.Optional[str] = None): """ :returns: dictionary with bundles that are available, provides context of cloud providers internal pagination mechanism. :rtype: dictionary """ kwargs = dict(bucket=Replica[replica].bucket, prefix=prefix, k_page_max=per_page) if search_after: kwargs['start_after_key'] = search_after if token: kwargs['token'] = token storage_handler = Config.get_blobstore_handle(Replica[replica]) prefix_iterator = Living(storage_handler.list_v2(**kwargs)) # note dont wrap this in enumerate; it looses the token uuid_list = list() for fqid in prefix_iterator: uuid_list.append(dict(uuid=fqid.uuid, version=fqid.version)) if len(uuid_list) >= per_page: break return dict(search_after=prefix_iterator.start_after_key, bundles=uuid_list, token=prefix_iterator.token, page_count=len(uuid_list)) class Living(): """ This utility class takes advantage of lexicographical ordering on object storage to list non-tombstoned bundles. """ def __init__(self, paged_iter): self.paged_iter = paged_iter self._init_bundle_info() self.start_after_key = None self.token = None def _init_bundle_info(self, fqid=None): self.bundle_info = dict(contains_unversioned_tombstone=False, uuid=None, fqids=OrderedDict()) if fqid: self.bundle_info['uuid'] = fqid.uuid self.bundle_info['fqids'][fqid] = False def _living_fqids_in_bundle_info(self): if not self.bundle_info['contains_unversioned_tombstone']: for fqid, is_dead in self.bundle_info['fqids'].items(): if not is_dead: yield fqid def _keys(self): for key, _ in self.paged_iter: yield key self.start_after_key = key self.token = getattr(self.paged_iter, "token", None) def __iter__(self): for key in self._keys(): fqid = BundleFQID.from_key(key) if fqid.uuid != self.bundle_info['uuid']: for bundle_fqid in self._living_fqids_in_bundle_info(): yield bundle_fqid self._init_bundle_info(fqid) else: if not fqid.is_fully_qualified(): self.bundle_info['contains_unversioned_tombstone'] = True else: self.bundle_info['fqids'][fqid] = isinstance(fqid, BundleTombstoneID) for bundle_fqid in self._living_fqids_in_bundle_info(): yield bundle_fqid def get_tombstoned_bundles(replica: Replica, tombstone_key: str) -> typing.Iterator[str]: """ Return the bundle fqid(s) associated with a versioned or unversioned tombstone, as verified on object storage. Note that an unversioned tombstone returns keys associated with bundles not previously, as show in the example below. bundles/uuid.version1 bundles/uuid.version2 bundles/uuid.version2.dead bundles/uuid.version3 bundles/uuid.version3.dead bundles/uuid.dead For the above listing: `get_tombstoned_bundles(replica, bundles/uuid.version2.dead)` -> `[bundles/uuid.version2]` `get_tombstoned_bundles(replica, bundles/uuid.dead)` -> `[bundles/uuid.version1]` """ handle = Config.get_blobstore_handle(replica) if DSS_VERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX.match(tombstone_key): pfx = tombstone_key.split(f".{TOMBSTONE_SUFFIX}")[0] prev_key = "" for key in handle.list(replica.bucket, pfx): if key == f"{prev_key}.{TOMBSTONE_SUFFIX}": yield prev_key prev_key = key elif DSS_UNVERSIONED_BUNDLE_TOMBSTONE_KEY_REGEX.match(tombstone_key): pfx = tombstone_key.split(f".{TOMBSTONE_SUFFIX}")[0] prev_key = "" for key in handle.list(replica.bucket, pfx): if key != f"{prev_key}.{TOMBSTONE_SUFFIX}" and not prev_key.endswith(TOMBSTONE_SUFFIX): if prev_key: yield prev_key prev_key = key else: raise ValueError(f"{tombstone_key} is not a tombstone key")
en
0.753998
Return the contents of the bundle manifest file from cloud storage, subject to the rules of tombstoning. If version is None, return the latest version, once again, subject to the rules of tombstoning. If the bundle cannot be found, return None # need the ability to use fixture bucket for testing # handle the following deletion cases # 1. the whole bundle is deleted # 2. the specific version of the bundle is deleted # handle the following deletion case # 3. no version is specified, we want the latest _non-deleted_ version # list the files and find the one that is the most recent. # no matches! # retrieve the bundle metadata. # type: typing.Set[str] # type: typing.Set[str] :returns: dictionary with bundles that are available, provides context of cloud providers internal pagination mechanism. :rtype: dictionary # note dont wrap this in enumerate; it looses the token This utility class takes advantage of lexicographical ordering on object storage to list non-tombstoned bundles. Return the bundle fqid(s) associated with a versioned or unversioned tombstone, as verified on object storage. Note that an unversioned tombstone returns keys associated with bundles not previously, as show in the example below. bundles/uuid.version1 bundles/uuid.version2 bundles/uuid.version2.dead bundles/uuid.version3 bundles/uuid.version3.dead bundles/uuid.dead For the above listing: `get_tombstoned_bundles(replica, bundles/uuid.version2.dead)` -> `[bundles/uuid.version2]` `get_tombstoned_bundles(replica, bundles/uuid.dead)` -> `[bundles/uuid.version1]`
2.076172
2
tests/test_ezbee.py
ffreemt/ezbee
0
6630452
<gh_stars>0 """Test ezbee.""" # pylint: disable=broad-except from ezbee import __version__ from ezbee import ezbee from ezbee.loadtext import loadtext def test_version(): """Test version.""" assert __version__[:3] == "0.1" def test_sanity(): """Sanity check.""" try: assert not ezbee([""], [""]) except Exception: assert True def test_data_en_zh(): """Test data/test-en/zh.txt. pytest tests\test_ezbee.py -k en_zh poetry remove holoviews plotly seaborn holoviews 1.14.8 plotly 5.6.0 seaborn 0.11.2 du -sh . # 452M poetry add -E holoviews plotly seaborn """ text_en = loadtext("data/test-en.txt") text_zh = loadtext("data/test-zh.txt") list1 = [elm.strip() for elm in text_en.splitlines() if elm.strip()] list2 = [elm.strip() for elm in text_zh.splitlines() if elm.strip()] # (len(list1), len(list2)) == (33, 36) res = ezbee(list1, list2) assert len(res) == 36 assert res[-1] == (35, 32, 0.5) assert res[15] == (15, 14, 0.31) assert [elm[0] for elm in res if not isinstance(elm[0], str)] == [*range(36)] [elm[1] for elm in res if not isinstance(elm[1], str)] == [*range(33)]
"""Test ezbee.""" # pylint: disable=broad-except from ezbee import __version__ from ezbee import ezbee from ezbee.loadtext import loadtext def test_version(): """Test version.""" assert __version__[:3] == "0.1" def test_sanity(): """Sanity check.""" try: assert not ezbee([""], [""]) except Exception: assert True def test_data_en_zh(): """Test data/test-en/zh.txt. pytest tests\test_ezbee.py -k en_zh poetry remove holoviews plotly seaborn holoviews 1.14.8 plotly 5.6.0 seaborn 0.11.2 du -sh . # 452M poetry add -E holoviews plotly seaborn """ text_en = loadtext("data/test-en.txt") text_zh = loadtext("data/test-zh.txt") list1 = [elm.strip() for elm in text_en.splitlines() if elm.strip()] list2 = [elm.strip() for elm in text_zh.splitlines() if elm.strip()] # (len(list1), len(list2)) == (33, 36) res = ezbee(list1, list2) assert len(res) == 36 assert res[-1] == (35, 32, 0.5) assert res[15] == (15, 14, 0.31) assert [elm[0] for elm in res if not isinstance(elm[0], str)] == [*range(36)] [elm[1] for elm in res if not isinstance(elm[1], str)] == [*range(33)]
en
0.302364
Test ezbee. # pylint: disable=broad-except Test version. Sanity check. Test data/test-en/zh.txt. pytest tests\test_ezbee.py -k en_zh poetry remove holoviews plotly seaborn holoviews 1.14.8 plotly 5.6.0 seaborn 0.11.2 du -sh . # 452M poetry add -E holoviews plotly seaborn # (len(list1), len(list2)) == (33, 36)
2.221175
2
inputs/trace_to_flow.py
flaviovdf/playlist-analysis
0
6630453
import pandas as pd df = pd.read_csv('./transitions-mood-sound-gender-collaps.csv') df = df[['playlist_id', 'source', 'tags', 'mood_source', 'mood_target', 'sound_source', 'sound_target', 'playlist_name', 'genre_source', 'genre_target']] for i in range(len(df)): row = df.ix[i] try: if isinstance(row['tags'], str): tags = row['tags'] else: tags = 'NT' if isinstance(row['playlist_name'], str): name = row['playlist_name'] else: name = 'NN' t = str(row['playlist_id']) + '/' + tags + '/' + name + '/' + \ row['source'] print(0, end='\t') print(t, end='\t') print(row['mood_source'], end='/') print(row['sound_source'], end='/') print(row['genre_source'], end='\t') print(row['mood_target'], end='/') print(row['sound_target'], end='/') print(row['genre_target']) except: pass
import pandas as pd df = pd.read_csv('./transitions-mood-sound-gender-collaps.csv') df = df[['playlist_id', 'source', 'tags', 'mood_source', 'mood_target', 'sound_source', 'sound_target', 'playlist_name', 'genre_source', 'genre_target']] for i in range(len(df)): row = df.ix[i] try: if isinstance(row['tags'], str): tags = row['tags'] else: tags = 'NT' if isinstance(row['playlist_name'], str): name = row['playlist_name'] else: name = 'NN' t = str(row['playlist_id']) + '/' + tags + '/' + name + '/' + \ row['source'] print(0, end='\t') print(t, end='\t') print(row['mood_source'], end='/') print(row['sound_source'], end='/') print(row['genre_source'], end='\t') print(row['mood_target'], end='/') print(row['sound_target'], end='/') print(row['genre_target']) except: pass
none
1
2.920804
3
station/__init__.py
mrbenjones/coffeetalk-python
1
6630454
<gh_stars>1-10 from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS app = Flask(__name__) app.config.from_object(Config) #cors = CORS(app, resources={r"/get_calls/*": {"origins": "*"}}) cors = CORS(app) db = SQLAlchemy(app) migrate = Migrate(app,db) from station import primary,models
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS app = Flask(__name__) app.config.from_object(Config) #cors = CORS(app, resources={r"/get_calls/*": {"origins": "*"}}) cors = CORS(app) db = SQLAlchemy(app) migrate = Migrate(app,db) from station import primary,models
en
0.241252
#cors = CORS(app, resources={r"/get_calls/*": {"origins": "*"}})
1.970525
2
HelpDesk/UpdateGEPrefix.py
flopezag/fiware-scrum-reports
0
6630455
<gh_stars>0 __author__ = '<NAME>' import re from jira.client import JIRA from kernel.Settings import settings server = settings.server['JIRA'] options = {'server': 'https://{}'.format(server.domain), 'verify': False} # jira = JIRA(options, basic_auth=(server.username, server.password)) users = ('aalonsog', 'fermin', 'frb', 'aarranz', 'amagan', 'fdelavega', 'meth', 'henar', 'knagin', 'tali', 'ckan-fiware-okfn', 'llopez', 'artusio', 'ralli', 'gessler', 'telsaleh', 'cdangerville', 'olivier.bettan', 'ariokkon', 'cvetan', 'jhyvarinen', 'sami_jylkk', 'jonne.vaisanen', 'loorni', 'tospie', 'glikson', 'jesus.movilla', 'jesus.perezgonzalez') user = 'sergg' chapter = 'Data' keyword = 'CKAN' query = 'project = HELP and status in (Closed, Done, Dismissed) AND component = FIWARE-TECH-HELP and assignee = {}'\ .format(user) issues = jira.search_issues(query, maxResults=False) issues = [issue for issue in issues if not re.match(r'FIWARE\.(Request|Question)\.Tech\.Data', issue.fields.summary)] for n, issue in enumerate(issues): print(n, issue, issue.fields.summary) # exit() for n, issue in enumerate(issues): if re.match(r'FIWARE\.(Question|Request)\.Tech\.{}\.{}'.format(chapter, keyword), issue.fields.summary): # print('->right', n, issue.fields.summary) continue if re.match(r'FIWARE\.(Question|Request)\.{}'.format('Tech'), issue.fields.summary): if re.match(r'FIWARE\.(Question|Request)\.Tech\.FIWARE\.(Question|Request)\.Tech', issue.fields.summary): summary = re.sub(r'FIWARE\.(Question|Request)\.Tech\.FIWARE\.', 'FIWARE.', issue.fields.summary) issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) else: summary = issue.fields.summary.strip().split('.') prefix = '.'.join(summary[0:3]) issuename = '.'.join(summary[3:]).strip() summary = prefix + '.{}.{}.'.format(chapter, keyword) + issuename issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) continue if re.match(r'FIWARE\.(Question|Request)\.Lab', issue.fields.summary.strip()): # print(n, issue, issue.fields.summary) summary = re.sub(r'\.Lab\.', '.Tech.', issue.fields.summary.strip()) issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) continue # print(n, issue, issue.fields.issuetype, issue.fields.summary) summary = re.sub(r'\[[^\]]+?\]', '', issue.fields.summary) if issue.fields.issuetype.name == 'Monitor': summary = 'FIWARE.Question.Tech.{}'.format(summary.strip()) if issue.fields.issuetype.name == 'extRequest': summary = 'FIWARE.Request.Tech.{}'.format(summary.strip()) issue.update(fields={'summary': summary}) print('updated->', issue, summary)
__author__ = '<NAME>' import re from jira.client import JIRA from kernel.Settings import settings server = settings.server['JIRA'] options = {'server': 'https://{}'.format(server.domain), 'verify': False} # jira = JIRA(options, basic_auth=(server.username, server.password)) users = ('aalonsog', 'fermin', 'frb', 'aarranz', 'amagan', 'fdelavega', 'meth', 'henar', 'knagin', 'tali', 'ckan-fiware-okfn', 'llopez', 'artusio', 'ralli', 'gessler', 'telsaleh', 'cdangerville', 'olivier.bettan', 'ariokkon', 'cvetan', 'jhyvarinen', 'sami_jylkk', 'jonne.vaisanen', 'loorni', 'tospie', 'glikson', 'jesus.movilla', 'jesus.perezgonzalez') user = 'sergg' chapter = 'Data' keyword = 'CKAN' query = 'project = HELP and status in (Closed, Done, Dismissed) AND component = FIWARE-TECH-HELP and assignee = {}'\ .format(user) issues = jira.search_issues(query, maxResults=False) issues = [issue for issue in issues if not re.match(r'FIWARE\.(Request|Question)\.Tech\.Data', issue.fields.summary)] for n, issue in enumerate(issues): print(n, issue, issue.fields.summary) # exit() for n, issue in enumerate(issues): if re.match(r'FIWARE\.(Question|Request)\.Tech\.{}\.{}'.format(chapter, keyword), issue.fields.summary): # print('->right', n, issue.fields.summary) continue if re.match(r'FIWARE\.(Question|Request)\.{}'.format('Tech'), issue.fields.summary): if re.match(r'FIWARE\.(Question|Request)\.Tech\.FIWARE\.(Question|Request)\.Tech', issue.fields.summary): summary = re.sub(r'FIWARE\.(Question|Request)\.Tech\.FIWARE\.', 'FIWARE.', issue.fields.summary) issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) else: summary = issue.fields.summary.strip().split('.') prefix = '.'.join(summary[0:3]) issuename = '.'.join(summary[3:]).strip() summary = prefix + '.{}.{}.'.format(chapter, keyword) + issuename issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) continue if re.match(r'FIWARE\.(Question|Request)\.Lab', issue.fields.summary.strip()): # print(n, issue, issue.fields.summary) summary = re.sub(r'\.Lab\.', '.Tech.', issue.fields.summary.strip()) issue.update(fields={'summary': summary}) print('updated ->', issue, issue.fields.summary) continue # print(n, issue, issue.fields.issuetype, issue.fields.summary) summary = re.sub(r'\[[^\]]+?\]', '', issue.fields.summary) if issue.fields.issuetype.name == 'Monitor': summary = 'FIWARE.Question.Tech.{}'.format(summary.strip()) if issue.fields.issuetype.name == 'extRequest': summary = 'FIWARE.Request.Tech.{}'.format(summary.strip()) issue.update(fields={'summary': summary}) print('updated->', issue, summary)
en
0.604633
# jira = JIRA(options, basic_auth=(server.username, server.password)) # exit() # print('->right', n, issue.fields.summary) # print(n, issue, issue.fields.summary) # print(n, issue, issue.fields.issuetype, issue.fields.summary)
2.271983
2
Errors/RequestFailedException.py
pjpmosteiro/DiscordGPT-3
49
6630456
<filename>Errors/RequestFailedException.py from string import Template from Errors import * from Errors.OpenAIError import OpenAIError from Errors.TokenExhaustedError import TokenExhaustedError from Errors.TokenInvalidError import TokenInvalidError class RequestFailedException(Error): def __init__(self, status_code: int): self.status_code = status_code self.try_handle() def __str__(self): return repr(self.status_code) def try_handle(self): if self.status_code == 429: raise TokenExhaustedError elif self.status_code == 400: raise TokenInvalidError elif self.status_code == 500: raise OpenAIError raise NotImplementedError( Template("$input status code has no exception handler.").substitute(input=self.status_code))
<filename>Errors/RequestFailedException.py from string import Template from Errors import * from Errors.OpenAIError import OpenAIError from Errors.TokenExhaustedError import TokenExhaustedError from Errors.TokenInvalidError import TokenInvalidError class RequestFailedException(Error): def __init__(self, status_code: int): self.status_code = status_code self.try_handle() def __str__(self): return repr(self.status_code) def try_handle(self): if self.status_code == 429: raise TokenExhaustedError elif self.status_code == 400: raise TokenInvalidError elif self.status_code == 500: raise OpenAIError raise NotImplementedError( Template("$input status code has no exception handler.").substitute(input=self.status_code))
none
1
2.786871
3
qubekit/torsions/fitting/forcebalance_wrapper.py
qubekit/QUBEK
45
6630457
""" Classes that help with parameter fitting using ForceBalance. """ import abc import copy import os import subprocess from typing import Any, Dict, List, Tuple from pydantic import BaseModel, Field, PositiveFloat, PositiveInt from qcelemental.util import which_import from typing_extensions import Literal from qubekit.molecules import Ligand, TorsionDriveData from qubekit.torsions.utils import forcebalance_setup from qubekit.utils.datastructures import StageBase from qubekit.utils.exceptions import ForceBalanceError, MissingReferenceData from qubekit.utils.file_handling import get_data, make_and_change_into from qubekit.utils.helpers import export_torsiondrive_data class Priors(BaseModel): """ A class which controls the forcebalance force field prior values. """ Proper_k: float = Field( 6.0, description="The initial prior for the proper torsion k values." ) def format_priors(self) -> Dict[str, Any]: """ Returns: A formatted dict version of the prior that can be consumed by forcebalance. """ data = {} for prior, value in self.__dict__.items(): prior = prior.split("_") prior = "/".join(prior) data[prior] = value return data class TargetBase(BaseModel, abc.ABC): """ A base class which each forcebalnce target should overwrite. This should control the run time settings used during fitting and implement a file setup method which is called before fitting. """ target_name: str description: str writelevel: PositiveInt = 2 keywords: Dict[str, Any] = {} openmm_platform: Literal["Reference"] = "Reference" class Config: validate_assignment = True fields = { "target_name": { "description": "The name of the forcebalance target to be fit" }, "entries": {"description": "a list of target entries to be optimised."}, "writelevel": { "description": "The write level controls the types of intermedate information which is saved from an optimisation." }, "keywords": { "description": "Any keyword information which should be passed to forcebalance as a run time setting." }, "openmm_platform": { "description": "The openmm platform that should be used in the fitting." }, } @abc.abstractmethod def prep_for_fitting(self, molecule: Ligand) -> None: """ The target will need to convert the input reference data to some format ready for fitting, this method should be implimented to take each molecule and assume it has the correct reference data. """ ... def fb_options(self) -> Dict[str, Any]: """ Format the target class run time options into a dict that can be consumed by forcebalance. """ data = self.dict(exclude={"target_name", "description", "keywords"}) data.update(self.keywords) return data class TorsionProfile(TargetBase): """ This helps set up the files required to perform the torsion profile fitting target in forcebalance. For each ligand passed the input files are prepared for each target torsion, the optimize in file is also updated with the target info. """ target_name: Literal["TorsionProfile_OpenMM"] = "TorsionProfile_OpenMM" description = "Relaxed energy and RMSD fitting for torsion drives only." energy_denom: PositiveFloat = Field( 1.0, description="The energy denominator used by forcebalance to weight the energies contribution to the objective function.", ) energy_upper: PositiveFloat = Field( 10.0, description="The upper limit for energy differences in kcal/mol which are included in fitting. Relative energies above this value do not contribute to the objective.", ) attenuate: bool = Field( False, description="If the weights should be attenuated as a function of the energy above the minimum.", ) restrain_k: float = Field( 1.0, description="The strength of the harmonic restraint in kcal/mol used in the mm relaxation on all non-torsion atoms.", ) keywords: Dict[str, Any] = {"pdb": "molecule.pdb", "coords": "scan.xyz"} def prep_for_fitting(self, molecule: Ligand) -> List[str]: """ For the given ligand prep the input files ready for torsion profile fitting. Args: molecule: The molecule object that we need to prep for fitting, this should have qm reference data stored in molecule.qm_scans. Note: We assume we are already in the targets folder. Returns: A list of target folder names made by this target. Raises: MissingReferenceData: If the molecule does not have any torsion drive reference data saved in molecule.qm_scans. """ # make sure we have data if not molecule.qm_scans: raise MissingReferenceData( f"Can not prepare a forcebalance fitting target for {molecule.name} as the reference data is missing!" ) # write out the qdata and other input files for each scan target_folders = [] # keep track of where we start base_folder = os.getcwd() # loop over each scanned bond and make a target folder for scan in molecule.qm_scans: task_name = ( f"{self.target_name}_{scan.central_bond[0]}_{scan.central_bond[1]}" ) target_folders.append(task_name) make_and_change_into(name=task_name) # make the pdb topology file if molecule.has_ub_terms(): molecule._to_ub_pdb(file_name="molecule") else: molecule.to_file(file_name="molecule.pdb") # write the qdata file export_torsiondrive_data(molecule=molecule, tdrive_data=scan) # make the metadata self.make_metadata(torsiondrive_data=scan) # now move back to the base os.chdir(base_folder) return target_folders @staticmethod def make_metadata(torsiondrive_data: TorsionDriveData) -> None: """ Create the metadata.json required to run a torsion profile target, this details the constrained optimisations to be done. Args: torsiondrive_data: Create the torsion metadata file which describes the angle to be scanned and the dihedral grid points. """ import json json_data = { "dihedrals": [ torsiondrive_data.dihedral, ], "grid_spacing": [ torsiondrive_data.grid_spacing, ], "dihedral_ranges": [ torsiondrive_data.torsion_drive_range, ], "torsion_grid_ids": [ [ data.angle, ] for data in torsiondrive_data.reference_data.values() ], } # now dump to file with open("metadata.json", "w") as meta: meta.write(json.dumps(json_data, indent=2)) class ForceBalanceFitting(StageBase): """ This class interfaces with forcebalance <https://github.com/leeping/forcebalance> and allows users to fit multiple force field parameters to multiple different targets such as optimised geometries vibration frequencies and relaxed torsion profiles. Note: We only support relaxed torsion profile fitting so far. All targets are fitted using OpenMM. """ class Config: validate_assignment = True arbitrary_types_allowed = True type: Literal["ForceBalanceFitting"] = "ForceBalanceFitting" penalty_type: Literal["L1", "L2"] = "L1" job_type: str = "optimize" max_iterations: PositiveInt = 10 convergence_step_criteria: PositiveFloat = 0.01 convergence_objective_criteria: PositiveFloat = 0.01 convergence_gradient_criteria: PositiveFloat = 0.01 n_criteria: PositiveInt = 1 eig_lowerbound: PositiveFloat = 0.01 finite_difference_h: PositiveFloat = 0.01 penalty_additive: PositiveFloat = 0.1 constrain_charge: bool = False initial_trust_radius: float = -0.25 minimum_trust_radius: float = 0.05 error_tolerance: PositiveFloat = 1.0 adaptive_factor: PositiveFloat = 0.2 adaptive_damping: PositiveFloat = 1.0 normalize_weights: bool = False extras: Dict[str, Any] = {} priors: Priors = Priors() targets: Dict[str, TorsionProfile] = {"TorsionProfile_OpenMM": TorsionProfile()} def start_message(self, **kwargs) -> str: return "Performing torsion optimisations using ForceBalance." def finish_message(self, **kwargs) -> str: return "Torsion optimisation complete." @classmethod def is_available(cls) -> bool: """Make sure forcebalance can be imported.""" fb = which_import( "forcebalance", return_bool=True, raise_error=True, raise_msg="Please install via `conda install forcebalance -c conda-forge`.", ) openmm = which_import( ".openmm", return_bool=True, raise_error=True, package="simtk", raise_msg="Please install via `conda install openmm -c conda-forge`.", ) return fb and openmm def run(self, molecule: "Ligand", **kwargs) -> "Ligand": """ The main run method of the ForceBalance torsion optimisation stage. Args: molecule: The molecule that should be optimised with its QM reference data. Important: We work on a copy of the molecule as we have to change some parameters. """ # check we have targets to fit if not self.targets: raise ForceBalanceError( "No fitting targets have been set for forcebalance, please set at least one target." ) # now we have validated the data run the optimiser return self._optimise(molecule=molecule) def add_target(self, target: TargetBase) -> None: """ Try and add the given target class to the forcebalance optimiser to be executed when optimise is called. Args: target: The ForceBalance optimisation target that should be added. """ if issubclass(type(target), TargetBase): self.targets[target.target_name] = target def _optimise(self, molecule: Ligand) -> Ligand: """ For the given input molecule run the forcebalance fitting for the list of targets and run time settings. Note: The list of optimisation targets should be set before running. """ # set up the master fitting folder with forcebalance_setup(folder_name="ForceBalance"): fitting_folder = os.getcwd() fitting_targets = {} # prep the target folders os.chdir("targets") for target in self.targets.values(): target_folders = target.prep_for_fitting(molecule=molecule) fitting_targets[target.target_name] = target_folders # back to fitting folder os.chdir(fitting_folder) # now we can make the optimize in file self.generate_optimise_in(target_data=fitting_targets) # now make the forcefield file self.generate_forcefield(molecule=molecule) # now execute forcebalance with open("log.txt", "w") as log: subprocess.run( "ForceBalance optimize.in", shell=True, stdout=log, stderr=log ) result_ligand = self.collect_results(molecule=molecule) return result_ligand def generate_forcefield(self, molecule: Ligand) -> None: """ For the given molecule generate the fitting forcefield with the target torsion terms tagged with the parameterize keyword. Args: molecule: The molecule whose torsion parameters should be optimised. Note: We currently hard code to only fit dihedrals that pass through the targeted rotatable bond. Important: We work with a copy of the molecule here as we add attributes to the forcefield and change default values. """ copy_mol = copy.deepcopy(molecule) # now we need to find all of the dihedrals for a central bond which should be optimised for torsiondrive_data in copy_mol.qm_scans: central_bond = torsiondrive_data.central_bond # now we can get all dihedrals for this bond try: dihedrals = copy_mol.dihedrals[central_bond] except KeyError: dihedrals = copy_mol.dihedrals[tuple(reversed(central_bond))] dihedral_groups = self.group_by_symmetry( molecule=copy_mol, dihedrals=dihedrals ) for dihedral_group in dihedral_groups: # add parametrise flags for forcebalance to one dihedral in the group # the rest get parameter eval tags referenced to this master dihedral master_dihedral = dihedral_group[0] master_parameter = copy_mol.TorsionForce[master_dihedral] # use the parameter atom order to be consistent dihedral_string = ".".join(str(i) for i in master_parameter.atoms) eval_tags = [ f"k{i}=PARM['Proper/k{i}/{dihedral_string}']" for i in range(1, 5) ] # we need to make sure all parameters are bigger than 0 to be loaded into an OpenMM system parameter_data = {"attributes": {"k1", "k2", "k3", "k4"}} for k in ["k1", "k2", "k3", "k4"]: if getattr(master_parameter, k) == 0: parameter_data[k] = 1e-6 master_parameter.update(**parameter_data) # now add parameter evals for dihedral in dihedral_group[1:]: parameter = copy_mol.TorsionForce[dihedral] parameter.parameter_eval = eval_tags # now we have all of the dihedrals build the force field copy_mol.write_parameters(file_name=os.path.join("forcefield", "bespoke.xml")) def group_by_symmetry( self, molecule: Ligand, dihedrals: List[Tuple[int, int, int, int]] ) -> List[List[Tuple[int, int, int, int]]]: """ For a list of target dihedrals to be optimised group them by symmetry type. Note: Dihedrals not in the target bond but in the same symmetry group are also included. """ dihedral_types = molecule.dihedral_types atom_types = molecule.atom_types dihedral_groups = {} for dihedral in dihedrals: # get the dihedral type dihedral_type = "-".join(atom_types[i] for i in dihedral) # now get all dihedrals of this type if ( dihedral_type not in dihedral_groups and dihedral_type[::-1] not in dihedral_groups ): try: dihedral_groups[dihedral_type] = dihedral_types[dihedral_type] except KeyError: dihedral_groups[dihedral_type[::-1]] = dihedral_types[ dihedral_type[::-1] ] return list(dihedral_groups.values()) def generate_optimise_in(self, target_data: Dict[str, List[str]]) -> None: """ For the given list of targets and entries produce an optimize.in file which contains all of the run time settings to be used in the optimization. this uses jinja templates to generate the required file from the template distributed with qubekit. Args: target_data: A dictionary mapping the target name to the target folders that have been created. """ from jinja2 import Template template_file = get_data(os.path.join("templates", "optimize.txt")) with open(template_file) as file: template = Template(file.read()) data = self.dict(exclude={"targets", "priors"}) data["priors"] = self.priors.format_priors() data["fitting_targets"] = target_data target_options = {} for target in self.targets.values(): target_options[target.target_name] = target.fb_options() data["target_options"] = target_options rendered_template = template.render(**data) with open("optimize.in", "w") as opt_in: opt_in.write(rendered_template) @staticmethod def check_converged() -> bool: """ Read the output from a forcebalance run to determine the exit status of the optimisation. Returns: `True` if the optimisation has converged else `False` """ converged = False with open("optimize.out") as log: for line in log.readlines(): if "optimization converged" in line.lower(): converged = True break elif "convergence failure" in line.lower(): converged = False break return converged def collect_results(self, molecule: Ligand) -> Ligand: """ Collect the results of an optimisation by checking the exit status and then transferring the optimised parameters from the final xml forcefield back into the ligand. Args: molecule: The molecule that was optimised and where the parameters should be stored. Returns: The input molecule with the optimised parameters saved. Raises: ForceBalanceError: If the optimisation did not converge or exit properly. """ # first check the exit status status = self.check_converged() if not status: raise ForceBalanceError( f"The optimisation for molecule {molecule.name} did not converge so the parameters could not be updated." ) else: from qubekit.parametrisation import XML # load the new parameters into the ligand # xml needs a pdb file xml = XML() xml.run( molecule=molecule, input_files=[os.path.join("result", self.job_type, "bespoke.xml")], ) return molecule
""" Classes that help with parameter fitting using ForceBalance. """ import abc import copy import os import subprocess from typing import Any, Dict, List, Tuple from pydantic import BaseModel, Field, PositiveFloat, PositiveInt from qcelemental.util import which_import from typing_extensions import Literal from qubekit.molecules import Ligand, TorsionDriveData from qubekit.torsions.utils import forcebalance_setup from qubekit.utils.datastructures import StageBase from qubekit.utils.exceptions import ForceBalanceError, MissingReferenceData from qubekit.utils.file_handling import get_data, make_and_change_into from qubekit.utils.helpers import export_torsiondrive_data class Priors(BaseModel): """ A class which controls the forcebalance force field prior values. """ Proper_k: float = Field( 6.0, description="The initial prior for the proper torsion k values." ) def format_priors(self) -> Dict[str, Any]: """ Returns: A formatted dict version of the prior that can be consumed by forcebalance. """ data = {} for prior, value in self.__dict__.items(): prior = prior.split("_") prior = "/".join(prior) data[prior] = value return data class TargetBase(BaseModel, abc.ABC): """ A base class which each forcebalnce target should overwrite. This should control the run time settings used during fitting and implement a file setup method which is called before fitting. """ target_name: str description: str writelevel: PositiveInt = 2 keywords: Dict[str, Any] = {} openmm_platform: Literal["Reference"] = "Reference" class Config: validate_assignment = True fields = { "target_name": { "description": "The name of the forcebalance target to be fit" }, "entries": {"description": "a list of target entries to be optimised."}, "writelevel": { "description": "The write level controls the types of intermedate information which is saved from an optimisation." }, "keywords": { "description": "Any keyword information which should be passed to forcebalance as a run time setting." }, "openmm_platform": { "description": "The openmm platform that should be used in the fitting." }, } @abc.abstractmethod def prep_for_fitting(self, molecule: Ligand) -> None: """ The target will need to convert the input reference data to some format ready for fitting, this method should be implimented to take each molecule and assume it has the correct reference data. """ ... def fb_options(self) -> Dict[str, Any]: """ Format the target class run time options into a dict that can be consumed by forcebalance. """ data = self.dict(exclude={"target_name", "description", "keywords"}) data.update(self.keywords) return data class TorsionProfile(TargetBase): """ This helps set up the files required to perform the torsion profile fitting target in forcebalance. For each ligand passed the input files are prepared for each target torsion, the optimize in file is also updated with the target info. """ target_name: Literal["TorsionProfile_OpenMM"] = "TorsionProfile_OpenMM" description = "Relaxed energy and RMSD fitting for torsion drives only." energy_denom: PositiveFloat = Field( 1.0, description="The energy denominator used by forcebalance to weight the energies contribution to the objective function.", ) energy_upper: PositiveFloat = Field( 10.0, description="The upper limit for energy differences in kcal/mol which are included in fitting. Relative energies above this value do not contribute to the objective.", ) attenuate: bool = Field( False, description="If the weights should be attenuated as a function of the energy above the minimum.", ) restrain_k: float = Field( 1.0, description="The strength of the harmonic restraint in kcal/mol used in the mm relaxation on all non-torsion atoms.", ) keywords: Dict[str, Any] = {"pdb": "molecule.pdb", "coords": "scan.xyz"} def prep_for_fitting(self, molecule: Ligand) -> List[str]: """ For the given ligand prep the input files ready for torsion profile fitting. Args: molecule: The molecule object that we need to prep for fitting, this should have qm reference data stored in molecule.qm_scans. Note: We assume we are already in the targets folder. Returns: A list of target folder names made by this target. Raises: MissingReferenceData: If the molecule does not have any torsion drive reference data saved in molecule.qm_scans. """ # make sure we have data if not molecule.qm_scans: raise MissingReferenceData( f"Can not prepare a forcebalance fitting target for {molecule.name} as the reference data is missing!" ) # write out the qdata and other input files for each scan target_folders = [] # keep track of where we start base_folder = os.getcwd() # loop over each scanned bond and make a target folder for scan in molecule.qm_scans: task_name = ( f"{self.target_name}_{scan.central_bond[0]}_{scan.central_bond[1]}" ) target_folders.append(task_name) make_and_change_into(name=task_name) # make the pdb topology file if molecule.has_ub_terms(): molecule._to_ub_pdb(file_name="molecule") else: molecule.to_file(file_name="molecule.pdb") # write the qdata file export_torsiondrive_data(molecule=molecule, tdrive_data=scan) # make the metadata self.make_metadata(torsiondrive_data=scan) # now move back to the base os.chdir(base_folder) return target_folders @staticmethod def make_metadata(torsiondrive_data: TorsionDriveData) -> None: """ Create the metadata.json required to run a torsion profile target, this details the constrained optimisations to be done. Args: torsiondrive_data: Create the torsion metadata file which describes the angle to be scanned and the dihedral grid points. """ import json json_data = { "dihedrals": [ torsiondrive_data.dihedral, ], "grid_spacing": [ torsiondrive_data.grid_spacing, ], "dihedral_ranges": [ torsiondrive_data.torsion_drive_range, ], "torsion_grid_ids": [ [ data.angle, ] for data in torsiondrive_data.reference_data.values() ], } # now dump to file with open("metadata.json", "w") as meta: meta.write(json.dumps(json_data, indent=2)) class ForceBalanceFitting(StageBase): """ This class interfaces with forcebalance <https://github.com/leeping/forcebalance> and allows users to fit multiple force field parameters to multiple different targets such as optimised geometries vibration frequencies and relaxed torsion profiles. Note: We only support relaxed torsion profile fitting so far. All targets are fitted using OpenMM. """ class Config: validate_assignment = True arbitrary_types_allowed = True type: Literal["ForceBalanceFitting"] = "ForceBalanceFitting" penalty_type: Literal["L1", "L2"] = "L1" job_type: str = "optimize" max_iterations: PositiveInt = 10 convergence_step_criteria: PositiveFloat = 0.01 convergence_objective_criteria: PositiveFloat = 0.01 convergence_gradient_criteria: PositiveFloat = 0.01 n_criteria: PositiveInt = 1 eig_lowerbound: PositiveFloat = 0.01 finite_difference_h: PositiveFloat = 0.01 penalty_additive: PositiveFloat = 0.1 constrain_charge: bool = False initial_trust_radius: float = -0.25 minimum_trust_radius: float = 0.05 error_tolerance: PositiveFloat = 1.0 adaptive_factor: PositiveFloat = 0.2 adaptive_damping: PositiveFloat = 1.0 normalize_weights: bool = False extras: Dict[str, Any] = {} priors: Priors = Priors() targets: Dict[str, TorsionProfile] = {"TorsionProfile_OpenMM": TorsionProfile()} def start_message(self, **kwargs) -> str: return "Performing torsion optimisations using ForceBalance." def finish_message(self, **kwargs) -> str: return "Torsion optimisation complete." @classmethod def is_available(cls) -> bool: """Make sure forcebalance can be imported.""" fb = which_import( "forcebalance", return_bool=True, raise_error=True, raise_msg="Please install via `conda install forcebalance -c conda-forge`.", ) openmm = which_import( ".openmm", return_bool=True, raise_error=True, package="simtk", raise_msg="Please install via `conda install openmm -c conda-forge`.", ) return fb and openmm def run(self, molecule: "Ligand", **kwargs) -> "Ligand": """ The main run method of the ForceBalance torsion optimisation stage. Args: molecule: The molecule that should be optimised with its QM reference data. Important: We work on a copy of the molecule as we have to change some parameters. """ # check we have targets to fit if not self.targets: raise ForceBalanceError( "No fitting targets have been set for forcebalance, please set at least one target." ) # now we have validated the data run the optimiser return self._optimise(molecule=molecule) def add_target(self, target: TargetBase) -> None: """ Try and add the given target class to the forcebalance optimiser to be executed when optimise is called. Args: target: The ForceBalance optimisation target that should be added. """ if issubclass(type(target), TargetBase): self.targets[target.target_name] = target def _optimise(self, molecule: Ligand) -> Ligand: """ For the given input molecule run the forcebalance fitting for the list of targets and run time settings. Note: The list of optimisation targets should be set before running. """ # set up the master fitting folder with forcebalance_setup(folder_name="ForceBalance"): fitting_folder = os.getcwd() fitting_targets = {} # prep the target folders os.chdir("targets") for target in self.targets.values(): target_folders = target.prep_for_fitting(molecule=molecule) fitting_targets[target.target_name] = target_folders # back to fitting folder os.chdir(fitting_folder) # now we can make the optimize in file self.generate_optimise_in(target_data=fitting_targets) # now make the forcefield file self.generate_forcefield(molecule=molecule) # now execute forcebalance with open("log.txt", "w") as log: subprocess.run( "ForceBalance optimize.in", shell=True, stdout=log, stderr=log ) result_ligand = self.collect_results(molecule=molecule) return result_ligand def generate_forcefield(self, molecule: Ligand) -> None: """ For the given molecule generate the fitting forcefield with the target torsion terms tagged with the parameterize keyword. Args: molecule: The molecule whose torsion parameters should be optimised. Note: We currently hard code to only fit dihedrals that pass through the targeted rotatable bond. Important: We work with a copy of the molecule here as we add attributes to the forcefield and change default values. """ copy_mol = copy.deepcopy(molecule) # now we need to find all of the dihedrals for a central bond which should be optimised for torsiondrive_data in copy_mol.qm_scans: central_bond = torsiondrive_data.central_bond # now we can get all dihedrals for this bond try: dihedrals = copy_mol.dihedrals[central_bond] except KeyError: dihedrals = copy_mol.dihedrals[tuple(reversed(central_bond))] dihedral_groups = self.group_by_symmetry( molecule=copy_mol, dihedrals=dihedrals ) for dihedral_group in dihedral_groups: # add parametrise flags for forcebalance to one dihedral in the group # the rest get parameter eval tags referenced to this master dihedral master_dihedral = dihedral_group[0] master_parameter = copy_mol.TorsionForce[master_dihedral] # use the parameter atom order to be consistent dihedral_string = ".".join(str(i) for i in master_parameter.atoms) eval_tags = [ f"k{i}=PARM['Proper/k{i}/{dihedral_string}']" for i in range(1, 5) ] # we need to make sure all parameters are bigger than 0 to be loaded into an OpenMM system parameter_data = {"attributes": {"k1", "k2", "k3", "k4"}} for k in ["k1", "k2", "k3", "k4"]: if getattr(master_parameter, k) == 0: parameter_data[k] = 1e-6 master_parameter.update(**parameter_data) # now add parameter evals for dihedral in dihedral_group[1:]: parameter = copy_mol.TorsionForce[dihedral] parameter.parameter_eval = eval_tags # now we have all of the dihedrals build the force field copy_mol.write_parameters(file_name=os.path.join("forcefield", "bespoke.xml")) def group_by_symmetry( self, molecule: Ligand, dihedrals: List[Tuple[int, int, int, int]] ) -> List[List[Tuple[int, int, int, int]]]: """ For a list of target dihedrals to be optimised group them by symmetry type. Note: Dihedrals not in the target bond but in the same symmetry group are also included. """ dihedral_types = molecule.dihedral_types atom_types = molecule.atom_types dihedral_groups = {} for dihedral in dihedrals: # get the dihedral type dihedral_type = "-".join(atom_types[i] for i in dihedral) # now get all dihedrals of this type if ( dihedral_type not in dihedral_groups and dihedral_type[::-1] not in dihedral_groups ): try: dihedral_groups[dihedral_type] = dihedral_types[dihedral_type] except KeyError: dihedral_groups[dihedral_type[::-1]] = dihedral_types[ dihedral_type[::-1] ] return list(dihedral_groups.values()) def generate_optimise_in(self, target_data: Dict[str, List[str]]) -> None: """ For the given list of targets and entries produce an optimize.in file which contains all of the run time settings to be used in the optimization. this uses jinja templates to generate the required file from the template distributed with qubekit. Args: target_data: A dictionary mapping the target name to the target folders that have been created. """ from jinja2 import Template template_file = get_data(os.path.join("templates", "optimize.txt")) with open(template_file) as file: template = Template(file.read()) data = self.dict(exclude={"targets", "priors"}) data["priors"] = self.priors.format_priors() data["fitting_targets"] = target_data target_options = {} for target in self.targets.values(): target_options[target.target_name] = target.fb_options() data["target_options"] = target_options rendered_template = template.render(**data) with open("optimize.in", "w") as opt_in: opt_in.write(rendered_template) @staticmethod def check_converged() -> bool: """ Read the output from a forcebalance run to determine the exit status of the optimisation. Returns: `True` if the optimisation has converged else `False` """ converged = False with open("optimize.out") as log: for line in log.readlines(): if "optimization converged" in line.lower(): converged = True break elif "convergence failure" in line.lower(): converged = False break return converged def collect_results(self, molecule: Ligand) -> Ligand: """ Collect the results of an optimisation by checking the exit status and then transferring the optimised parameters from the final xml forcefield back into the ligand. Args: molecule: The molecule that was optimised and where the parameters should be stored. Returns: The input molecule with the optimised parameters saved. Raises: ForceBalanceError: If the optimisation did not converge or exit properly. """ # first check the exit status status = self.check_converged() if not status: raise ForceBalanceError( f"The optimisation for molecule {molecule.name} did not converge so the parameters could not be updated." ) else: from qubekit.parametrisation import XML # load the new parameters into the ligand # xml needs a pdb file xml = XML() xml.run( molecule=molecule, input_files=[os.path.join("result", self.job_type, "bespoke.xml")], ) return molecule
en
0.817635
Classes that help with parameter fitting using ForceBalance. A class which controls the forcebalance force field prior values. Returns: A formatted dict version of the prior that can be consumed by forcebalance. A base class which each forcebalnce target should overwrite. This should control the run time settings used during fitting and implement a file setup method which is called before fitting. The target will need to convert the input reference data to some format ready for fitting, this method should be implimented to take each molecule and assume it has the correct reference data. Format the target class run time options into a dict that can be consumed by forcebalance. This helps set up the files required to perform the torsion profile fitting target in forcebalance. For each ligand passed the input files are prepared for each target torsion, the optimize in file is also updated with the target info. For the given ligand prep the input files ready for torsion profile fitting. Args: molecule: The molecule object that we need to prep for fitting, this should have qm reference data stored in molecule.qm_scans. Note: We assume we are already in the targets folder. Returns: A list of target folder names made by this target. Raises: MissingReferenceData: If the molecule does not have any torsion drive reference data saved in molecule.qm_scans. # make sure we have data # write out the qdata and other input files for each scan # keep track of where we start # loop over each scanned bond and make a target folder # make the pdb topology file # write the qdata file # make the metadata # now move back to the base Create the metadata.json required to run a torsion profile target, this details the constrained optimisations to be done. Args: torsiondrive_data: Create the torsion metadata file which describes the angle to be scanned and the dihedral grid points. # now dump to file This class interfaces with forcebalance <https://github.com/leeping/forcebalance> and allows users to fit multiple force field parameters to multiple different targets such as optimised geometries vibration frequencies and relaxed torsion profiles. Note: We only support relaxed torsion profile fitting so far. All targets are fitted using OpenMM. Make sure forcebalance can be imported. The main run method of the ForceBalance torsion optimisation stage. Args: molecule: The molecule that should be optimised with its QM reference data. Important: We work on a copy of the molecule as we have to change some parameters. # check we have targets to fit # now we have validated the data run the optimiser Try and add the given target class to the forcebalance optimiser to be executed when optimise is called. Args: target: The ForceBalance optimisation target that should be added. For the given input molecule run the forcebalance fitting for the list of targets and run time settings. Note: The list of optimisation targets should be set before running. # set up the master fitting folder # prep the target folders # back to fitting folder # now we can make the optimize in file # now make the forcefield file # now execute forcebalance For the given molecule generate the fitting forcefield with the target torsion terms tagged with the parameterize keyword. Args: molecule: The molecule whose torsion parameters should be optimised. Note: We currently hard code to only fit dihedrals that pass through the targeted rotatable bond. Important: We work with a copy of the molecule here as we add attributes to the forcefield and change default values. # now we need to find all of the dihedrals for a central bond which should be optimised # now we can get all dihedrals for this bond # add parametrise flags for forcebalance to one dihedral in the group # the rest get parameter eval tags referenced to this master dihedral # use the parameter atom order to be consistent # we need to make sure all parameters are bigger than 0 to be loaded into an OpenMM system # now add parameter evals # now we have all of the dihedrals build the force field For a list of target dihedrals to be optimised group them by symmetry type. Note: Dihedrals not in the target bond but in the same symmetry group are also included. # get the dihedral type # now get all dihedrals of this type For the given list of targets and entries produce an optimize.in file which contains all of the run time settings to be used in the optimization. this uses jinja templates to generate the required file from the template distributed with qubekit. Args: target_data: A dictionary mapping the target name to the target folders that have been created. Read the output from a forcebalance run to determine the exit status of the optimisation. Returns: `True` if the optimisation has converged else `False` Collect the results of an optimisation by checking the exit status and then transferring the optimised parameters from the final xml forcefield back into the ligand. Args: molecule: The molecule that was optimised and where the parameters should be stored. Returns: The input molecule with the optimised parameters saved. Raises: ForceBalanceError: If the optimisation did not converge or exit properly. # first check the exit status # load the new parameters into the ligand # xml needs a pdb file
2.788165
3
modules/remoteprocessing/remotescript/pydas/__init__.py
jcfr/Midas
20
6630458
<reponame>jcfr/Midas import json import urllib from communicator import Communicator
import json import urllib from communicator import Communicator
none
1
1.156469
1
GeneralClassesFunctions/simulation_functions.py
EAOgroup/FEAST
6
6630459
""" All functions that are required in the simulations and independent of input data and detection method are stored here. """ import numpy as np import random import os import pickle def sample_wr(data, n_samples=1): """ Create a list of data by random sampling from a data set with replacement Inputs: data List of data n_samples number of samples to draw Return: sample list of samples drawn """ sample = [] for ind in range(0, n_samples): sample.append(random.choice(data)) return sample def new_leak_count(time, gas_field): """ Calculate the number of new leaks to generate Inputs: time a Time object gas_field a GasField object Return: Number of new leaks """ return np.random.poisson(gas_field.leak_production_rate * time.delta_t * gas_field.component_count) def save_results(dir_out, results): """ Save results to a file Inputs: dir_out Name of output file to save results A results object """ if not os.path.exists(dir_out): os.makedirs(dir_out) n_realization = len(os.listdir(dir_out)) file_out = dir_out + '/realization' + str(n_realization) + '.p' pickle.dump(results, open(file_out, 'wb')) def set_kwargs_attrs(obj_in, kwargs, only_existing=True): """ Function for overwriting parameters with key word arguments Inputs: obj_in Object with parameters to be updated kwargs Dict containing new parameter values only_existing Determines with new parameters can be created with kwargs """ for key in kwargs.keys(): # If only_existing is true, only set attributes that already exist if only_existing: if not hasattr(obj_in, key): raise ValueError("Tried to set invalid attribute. Class: ", type(obj_in), 'attempted attribute:', key) setattr(obj_in, key, kwargs[key]) # Calculate the concentration of methane at arbitrary points downwind of a leak source. def gauss_leak_model(x, y, z, leak, atm, current_time, index=None): """ Returns the concentration of methane at a position downwind of the leak Inputs: x, y, z array of points at which to calculate the concentration [m] x is measured parallel to the wind, z is vertical distance above the ground and y completes a right hand coordinate system leak Leak object containing numpy arrays of leak data atm Atmosphere object containing atmosphere data index index of leak to be analyzed from within 'leak.' Outputs: phi array storing the concentration of methane at the desired coordinates [g/m^3] """ # Definitions: # sigmay is the standard deviation of the concentration in the y direction. # sigmaz is the standard deviation of the concentration in the z direction. # sigmay and sigmaz are calculated as a function of x based on the Pasquill # stability category. They are linear fits to the 100 meter data on the # Pasquill Gifford curves. n_loc = len(x) # If an index (or list of indexes) is passed in, only consider those leaks. Otherwise, compute phi for all leaks if index is None: rng = np.array(range(0, leak.n_leaks)) phi = np.zeros([n_loc, leak.n_leaks]) elif type(index) is not np.ndarray: try: len(index) rng = np.array(index) except TypeError: rng = np.array([index]) phi = np.zeros([n_loc, len(rng)]) else: rng = index phi = np.zeros([n_loc, len(rng)]) # Iterate through each location for loc in range(0, n_loc): if z[loc] < 0: continue normx = x[loc]-leak.x[rng] # poslocations limits the calculation to points downwind of the leak and above ground. poslocations = np.where(normx > 0) normx = normx[poslocations] temp_rng = rng[poslocations] # sigmay and sigmaz are arrays of dimension normx sigmaz = atm.l[current_time]*normx/(1+normx/atm.a[current_time])**atm.q[current_time] sigmay = atm.k[current_time]*normx/(1+normx/atm.a[current_time])**atm.p[current_time] # a and b are variables used in later calculations to account for # the buoyancy of the plume. b = -leak.z[temp_rng]-1.6 * leak.f_one_third[temp_rng] * normx**(2/3)/atm.wind_speed[current_time] a = z[loc]+b # Concentration Calculation fy = np.exp(-(y[loc]-leak.y[temp_rng])**2 / (2*sigmay**2)) fz = np.exp(-a**2./(2*sigmaz**2)) fg = np.exp(-(a-2*b)**2./(2*sigmaz**2)) phi[loc, poslocations] = leak.flux[temp_rng]/(atm.wind_speed[current_time] * 2*np.pi*sigmaz*sigmay)*fy*(fz+fg) # g/m^3 return phi
""" All functions that are required in the simulations and independent of input data and detection method are stored here. """ import numpy as np import random import os import pickle def sample_wr(data, n_samples=1): """ Create a list of data by random sampling from a data set with replacement Inputs: data List of data n_samples number of samples to draw Return: sample list of samples drawn """ sample = [] for ind in range(0, n_samples): sample.append(random.choice(data)) return sample def new_leak_count(time, gas_field): """ Calculate the number of new leaks to generate Inputs: time a Time object gas_field a GasField object Return: Number of new leaks """ return np.random.poisson(gas_field.leak_production_rate * time.delta_t * gas_field.component_count) def save_results(dir_out, results): """ Save results to a file Inputs: dir_out Name of output file to save results A results object """ if not os.path.exists(dir_out): os.makedirs(dir_out) n_realization = len(os.listdir(dir_out)) file_out = dir_out + '/realization' + str(n_realization) + '.p' pickle.dump(results, open(file_out, 'wb')) def set_kwargs_attrs(obj_in, kwargs, only_existing=True): """ Function for overwriting parameters with key word arguments Inputs: obj_in Object with parameters to be updated kwargs Dict containing new parameter values only_existing Determines with new parameters can be created with kwargs """ for key in kwargs.keys(): # If only_existing is true, only set attributes that already exist if only_existing: if not hasattr(obj_in, key): raise ValueError("Tried to set invalid attribute. Class: ", type(obj_in), 'attempted attribute:', key) setattr(obj_in, key, kwargs[key]) # Calculate the concentration of methane at arbitrary points downwind of a leak source. def gauss_leak_model(x, y, z, leak, atm, current_time, index=None): """ Returns the concentration of methane at a position downwind of the leak Inputs: x, y, z array of points at which to calculate the concentration [m] x is measured parallel to the wind, z is vertical distance above the ground and y completes a right hand coordinate system leak Leak object containing numpy arrays of leak data atm Atmosphere object containing atmosphere data index index of leak to be analyzed from within 'leak.' Outputs: phi array storing the concentration of methane at the desired coordinates [g/m^3] """ # Definitions: # sigmay is the standard deviation of the concentration in the y direction. # sigmaz is the standard deviation of the concentration in the z direction. # sigmay and sigmaz are calculated as a function of x based on the Pasquill # stability category. They are linear fits to the 100 meter data on the # Pasquill Gifford curves. n_loc = len(x) # If an index (or list of indexes) is passed in, only consider those leaks. Otherwise, compute phi for all leaks if index is None: rng = np.array(range(0, leak.n_leaks)) phi = np.zeros([n_loc, leak.n_leaks]) elif type(index) is not np.ndarray: try: len(index) rng = np.array(index) except TypeError: rng = np.array([index]) phi = np.zeros([n_loc, len(rng)]) else: rng = index phi = np.zeros([n_loc, len(rng)]) # Iterate through each location for loc in range(0, n_loc): if z[loc] < 0: continue normx = x[loc]-leak.x[rng] # poslocations limits the calculation to points downwind of the leak and above ground. poslocations = np.where(normx > 0) normx = normx[poslocations] temp_rng = rng[poslocations] # sigmay and sigmaz are arrays of dimension normx sigmaz = atm.l[current_time]*normx/(1+normx/atm.a[current_time])**atm.q[current_time] sigmay = atm.k[current_time]*normx/(1+normx/atm.a[current_time])**atm.p[current_time] # a and b are variables used in later calculations to account for # the buoyancy of the plume. b = -leak.z[temp_rng]-1.6 * leak.f_one_third[temp_rng] * normx**(2/3)/atm.wind_speed[current_time] a = z[loc]+b # Concentration Calculation fy = np.exp(-(y[loc]-leak.y[temp_rng])**2 / (2*sigmay**2)) fz = np.exp(-a**2./(2*sigmaz**2)) fg = np.exp(-(a-2*b)**2./(2*sigmaz**2)) phi[loc, poslocations] = leak.flux[temp_rng]/(atm.wind_speed[current_time] * 2*np.pi*sigmaz*sigmay)*fy*(fz+fg) # g/m^3 return phi
en
0.816776
All functions that are required in the simulations and independent of input data and detection method are stored here. Create a list of data by random sampling from a data set with replacement Inputs: data List of data n_samples number of samples to draw Return: sample list of samples drawn Calculate the number of new leaks to generate Inputs: time a Time object gas_field a GasField object Return: Number of new leaks Save results to a file Inputs: dir_out Name of output file to save results A results object Function for overwriting parameters with key word arguments Inputs: obj_in Object with parameters to be updated kwargs Dict containing new parameter values only_existing Determines with new parameters can be created with kwargs # If only_existing is true, only set attributes that already exist # Calculate the concentration of methane at arbitrary points downwind of a leak source. Returns the concentration of methane at a position downwind of the leak Inputs: x, y, z array of points at which to calculate the concentration [m] x is measured parallel to the wind, z is vertical distance above the ground and y completes a right hand coordinate system leak Leak object containing numpy arrays of leak data atm Atmosphere object containing atmosphere data index index of leak to be analyzed from within 'leak.' Outputs: phi array storing the concentration of methane at the desired coordinates [g/m^3] # Definitions: # sigmay is the standard deviation of the concentration in the y direction. # sigmaz is the standard deviation of the concentration in the z direction. # sigmay and sigmaz are calculated as a function of x based on the Pasquill # stability category. They are linear fits to the 100 meter data on the # Pasquill Gifford curves. # If an index (or list of indexes) is passed in, only consider those leaks. Otherwise, compute phi for all leaks # Iterate through each location # poslocations limits the calculation to points downwind of the leak and above ground. # sigmay and sigmaz are arrays of dimension normx # a and b are variables used in later calculations to account for # the buoyancy of the plume. # Concentration Calculation # g/m^3
2.989686
3
test/test_mpc.py
JJusti/CrypTen
0
6630460
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import math import unittest import crypten import crypten.communicator as comm import torch import torch.nn.functional as F from crypten.common.functions.pooling import _pool2d_reshape from crypten.common.rng import generate_kbit_random_tensor, generate_random_ring_element from crypten.common.tensor_types import is_float_tensor from crypten.config import cfg from crypten.mpc import MPCTensor, ptype as Ptype from crypten.mpc.primitives import ArithmeticSharedTensor, BinarySharedTensor from test.multiprocess_test_case import MultiProcessTestCase, get_random_test_tensor class TestMPC(object): """ This class tests all functions of MPCTensor. """ def _get_random_test_tensor(self, *args, **kwargs): return get_random_test_tensor(device=self.device, *args, **kwargs) def _check(self, encrypted_tensor, reference, msg, dst=None, tolerance=None): if tolerance is None: tolerance = getattr(self, "default_tolerance", 0.05) tensor = encrypted_tensor.get_plain_text(dst=dst) if dst is not None and dst != self.rank: self.assertIsNone(tensor) return # Check sizes match self.assertTrue(tensor.size() == reference.size(), msg) self.assertTrue(is_float_tensor(reference), "reference must be a float") if tensor.device != reference.device: tensor = tensor.cpu() reference = reference.cpu() diff = (tensor - reference).abs_() norm_diff = diff.div(tensor.abs() + reference.abs()).abs_() test_passed = norm_diff.le(tolerance) + diff.le(tolerance * 0.1) test_passed = test_passed.gt(0).all().item() == 1 if not test_passed: logging.info(msg) logging.info("Result %s" % tensor) logging.info("Reference %s" % reference) logging.info("Result - Reference = %s" % (tensor - reference)) self.assertTrue(test_passed, msg=msg) def _check_tuple(self, encrypted_tuple, reference, msg, tolerance=None): self.assertTrue(isinstance(encrypted_tuple, tuple)) self.assertEqual(len(encrypted_tuple), len(reference)) for i in range(len(reference)): self._check(encrypted_tuple[i], reference[i], msg, tolerance=tolerance) def test_repr(self): a = self._get_random_test_tensor(size=(1,)) arithmetic = MPCTensor(a, ptype=Ptype.arithmetic) binary = MPCTensor(a, ptype=Ptype.binary) # Make sure these don't crash print(arithmetic) repr(arithmetic) print(binary) repr(binary) def test_from_shares(self): """Tests MPCTensor.from_shares() functionality.""" # settings for test: num_parties = int(self.world_size) size = (5, 4) def _generate_tensor(ptype): reference = self._get_random_test_tensor(size=size, is_float=False) # generate arithmetic sharing of reference tensor: if ptype == Ptype.arithmetic: zero_shares = generate_random_ring_element( (num_parties, *size), device=self.device ) zero_shares = zero_shares - zero_shares.roll(1, dims=0) shares = list(zero_shares.unbind(0)) shares[0] += reference # generate binary sharing of reference tensor: else: zero_shares = generate_kbit_random_tensor( (num_parties, *size), device=self.device ) zero_shares = zero_shares ^ zero_shares.roll(1, dims=0) shares = list(zero_shares.unbind(0)) shares[0] ^= reference # return shares and reference: return shares, reference # test both types: for ptype in [Ptype.arithmetic, Ptype.binary]: # generate shares, sync them between parties, and create tensor: shares, reference = _generate_tensor(ptype) share = comm.get().scatter(shares, 0) encrypted_tensor = MPCTensor.from_shares(share, ptype=ptype) # check resulting tensor: self.assertIsInstance(encrypted_tensor, MPCTensor) self.assertEqual(encrypted_tensor.ptype, ptype) self.assertIsInstance(encrypted_tensor._tensor, ptype.to_tensor()) decrypted_tensor = encrypted_tensor.reveal() self.assertTrue(torch.all(decrypted_tensor.eq(reference)).item()) def test_share_attr(self): """Tests share attribute getter and setter""" for is_float in (True, False): reference = self._get_random_test_tensor(is_float=is_float) encrypted_tensor = MPCTensor(reference) underlying_tensor = encrypted_tensor.share self.assertTrue( torch.equal(encrypted_tensor.share, underlying_tensor), "share getter failed", ) new_share = self._get_random_test_tensor(is_float=False) encrypted_tensor.share = new_share self.assertTrue( torch.equal(encrypted_tensor.share, new_share), "share setter failed" ) def test_encrypt_decrypt(self): """ Tests tensor encryption and decryption for both positive and negative values. """ sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 3, 32, 32), (5, 3, 32, 32), ] for size in sizes: # encryption and decryption without source: reference = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(reference) self._check(encrypted_tensor, reference, "en/decryption failed") for dst in range(self.world_size): self._check( encrypted_tensor, reference, "en/decryption failed", dst=dst ) # test creation via new() function: encrypted_tensor2 = encrypted_tensor.new(reference) self.assertIsInstance( encrypted_tensor2, MPCTensor, "new() returns incorrect type" ) self._check(encrypted_tensor2, reference, "en/decryption failed") # TODO: Implement broadcast_size on GPU if self.device.type == "cuda": continue # encryption and decryption with source: for src in range(self.world_size): input_tensor = reference if src == self.rank else [] encrypted_tensor = MPCTensor(input_tensor, src=src, broadcast_size=True) for dst in range(self.world_size): self._check( encrypted_tensor, reference, "en/decryption with broadcast_size failed", dst=dst, ) # MPCTensors cannot be initialized with None: with self.assertRaises(ValueError): _ = MPCTensor(None) def test_arithmetic(self): """Tests arithmetic functions on encrypted tensor.""" arithmetic_functions = ["add", "add_", "sub", "sub_", "mul", "mul_"] for func in arithmetic_functions: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted, func)(encrypted2) self._check( encrypted_out, reference, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) if "_" in func: # Check in-place op worked self._check( encrypted, reference, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) # Check encrypted vector with encrypted scalar works. tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True, size=(1,)) encrypted1 = MPCTensor(tensor1) encrypted2 = MPCTensor(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted1, func)(encrypted2) self._check(encrypted_out, reference, "private %s failed" % func) tensor = self._get_random_test_tensor(is_float=True) reference = tensor * tensor encrypted = MPCTensor(tensor) encrypted_out = encrypted.square() self._check(encrypted_out, reference, "square failed") # Test radd, rsub, and rmul reference = 2 + tensor1 encrypted = MPCTensor(tensor1) encrypted_out = 2 + encrypted self._check(encrypted_out, reference, "right add failed") reference = 2 - tensor1 encrypted_out = 2 - encrypted self._check(encrypted_out, reference, "right sub failed") reference = 2 * tensor1 encrypted_out = 2 * encrypted self._check(encrypted_out, reference, "right mul failed") def test_sum(self): """Tests sum reduction on encrypted tensor.""" tensor = self._get_random_test_tensor(size=(100, 100), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.sum(), tensor.sum(), "sum failed") for dim in [0, 1]: reference = tensor.sum(dim) encrypted_out = encrypted.sum(dim) self._check(encrypted_out, reference, "sum failed") def test_prod(self): """Tests prod reduction on encrypted tensor.""" tensor = self._get_random_test_tensor(size=(3, 3), max_value=3, is_float=False) encrypted = MPCTensor(tensor) self._check(encrypted.prod(), tensor.prod().float(), "prod failed") tensor = self._get_random_test_tensor( size=(5, 5, 5), max_value=3, is_float=False ) encrypted = MPCTensor(tensor) for dim in [0, 1, 2]: reference = tensor.prod(dim).float() encrypted_out = encrypted.prod(dim) self._check(encrypted_out, reference, "prod failed") def test_ptype(self): """Test that ptype attribute creates the correct type of encrypted tensor""" ptype_values = [crypten.mpc.arithmetic, crypten.mpc.binary] tensor_types = [ArithmeticSharedTensor, BinarySharedTensor] for i, curr_ptype in enumerate(ptype_values): tensor = self._get_random_test_tensor(is_float=False) encr_tensor = crypten.cryptensor(tensor, ptype=curr_ptype) assert isinstance(encr_tensor._tensor, tensor_types[i]), "ptype test failed" def test_div(self): """Tests division of encrypted tensor by scalar and tensor.""" for function in ["div", "div_"]: for scalar in [2, 2.0]: tensor = self._get_random_test_tensor(is_float=True) reference = tensor.float().div(scalar) encrypted_tensor = MPCTensor(tensor) encrypted_tensor = getattr(encrypted_tensor, function)(scalar) self._check(encrypted_tensor, reference, "scalar division failed") # multiply denominator by 10 to avoid dividing by small num divisor = self._get_random_test_tensor(is_float=True, ex_zero=True) * 10 reference = tensor.div(divisor) encrypted_tensor = MPCTensor(tensor) encrypted_tensor = getattr(encrypted_tensor, function)(divisor) self._check(encrypted_tensor, reference, "tensor division failed") def test_mean(self): """Tests computing means of encrypted tensors.""" tensor = self._get_random_test_tensor(size=(5, 10, 15), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.mean(), tensor.mean(), "mean failed") for dim in [0, 1, 2]: reference = tensor.mean(dim) encrypted_out = encrypted.mean(dim) self._check(encrypted_out, reference, "mean failed") def test_var(self): """Tests computing variances of encrypted tensors.""" tensor = self._get_random_test_tensor(size=(5, 10, 15), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.var(), tensor.var(), "var failed") for dim in [0, 1, 2]: reference = tensor.var(dim) encrypted_out = encrypted.var(dim) self._check(encrypted_out, reference, "var failed") def test_matmul(self): """Test matrix multiplication.""" for tensor_type in [lambda x: x, MPCTensor]: tensor = self._get_random_test_tensor(max_value=7, is_float=True) for width in range(2, tensor.nelement()): matrix_size = (tensor.nelement(), width) matrix = self._get_random_test_tensor( max_value=7, size=matrix_size, is_float=True ) reference = tensor.matmul(matrix) encrypted_tensor = MPCTensor(tensor) matrix = tensor_type(matrix) encrypted_tensor = encrypted_tensor.matmul(matrix) self._check( encrypted_tensor, reference, "Private-%s matrix multiplication failed" % ("private" if tensor_type == MPCTensor else "public"), ) def test_dot_ger(self): """Test dot product of vector and encrypted tensor.""" for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True).squeeze() tensor2 = self._get_random_test_tensor(is_float=True).squeeze() dot_reference = tensor1.dot(tensor2) ger_reference = torch.ger(tensor1, tensor2) tensor2 = tensor_type(tensor2) # dot encrypted_tensor = MPCTensor(tensor1) encrypted_out = encrypted_tensor.dot(tensor2) self._check( encrypted_out, dot_reference, "%s dot product failed" % "private" if tensor_type == MPCTensor else "public", ) # ger encrypted_tensor = MPCTensor(tensor1) encrypted_out = encrypted_tensor.ger(tensor2) self._check( encrypted_out, ger_reference, "%s outer product failed" % "private" if tensor_type == MPCTensor else "public", ) def test_squeeze(self): tensor = self._get_random_test_tensor(is_float=True) for dim in [0, 1, 2]: # Test unsqueeze reference = tensor.unsqueeze(dim) encrypted = MPCTensor(tensor) encrypted_out = encrypted.unsqueeze(dim) self._check(encrypted_out, reference, "unsqueeze failed") # Test squeeze encrypted = MPCTensor(tensor.unsqueeze(0)) encrypted_out = encrypted.squeeze() self._check(encrypted_out, reference.squeeze(), "squeeze failed") # Check that the encrypted_out and encrypted point to the same # thing. encrypted_out[0:2] = torch.tensor( [0, 1], dtype=torch.float, device=self.device ) ref = encrypted.squeeze().get_plain_text() self._check(encrypted_out, ref, "squeeze failed") def test_transpose(self): sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 3, 32, 32), (5, 3, 32, 32), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) if len(size) == 2: # t() asserts dim == 2 reference = tensor.t() encrypted_out = encrypted_tensor.t() self._check(encrypted_out, reference, "t() failed") for dim0 in range(len(size)): for dim1 in range(len(size)): reference = tensor.transpose(dim0, dim1) encrypted_out = encrypted_tensor.transpose(dim0, dim1) self._check(encrypted_out, reference, "transpose failed") def test_conv1d_smaller_signal_one_channel(self): self._conv1d(5, 1) def test_conv1d_smaller_signal_many_channels(self): self._conv1d(5, 5) def test_conv1d_larger_signal_one_channel(self): self._conv1d(16, 1) def test_conv1d_larger_signal_many_channels(self): self._conv1d(16, 5) def _conv1d(self, signal_size, in_channels): """Test convolution of encrypted tensor with public/private tensors.""" nbatches = [1, 3] kernel_sizes = [1, 2, 3] ochannels = [1, 3, 6] paddings = [0, 1] strides = [1, 2] dilations = [1, 2] groupings = [1, 2] for func_name in ["conv1d", "conv_transpose1d"]: for kernel_type in [lambda x: x, MPCTensor]: for ( batches, kernel_size, out_channels, padding, stride, dilation, groups, ) in itertools.product( nbatches, kernel_sizes, ochannels, paddings, strides, dilations, groupings, ): # group convolution is not supported on GPU if self.device.type == "cuda" and groups > 1: continue input_size = (batches, in_channels * groups, signal_size) signal = self._get_random_test_tensor( size=input_size, is_float=True ) if func_name == "conv1d": k_size = (out_channels * groups, in_channels, kernel_size) else: k_size = (in_channels * groups, out_channels, kernel_size) kernel = self._get_random_test_tensor(size=k_size, is_float=True) reference = getattr(F, func_name)( signal, kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) encrypted_signal = MPCTensor(signal) encrypted_kernel = kernel_type(kernel) encrypted_conv = getattr(encrypted_signal, func_name)( encrypted_kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) self._check(encrypted_conv, reference, f"{func_name} failed") def test_conv2d_square_image_one_channel(self): self._conv2d((5, 5), 1, "conv2d") def test_conv_transpose2d_square_image_one_channel(self): self._conv2d((5, 5), 1, "conv_transpose2d") def test_conv2d_square_image_many_channels(self): self._conv2d((5, 5), 5, "conv2d") def test_conv_transpose2d_square_image_many_channels(self): self._conv2d((5, 5), 5, "conv_transpose2d") def test_conv2d_rectangular_image_one_channel(self): self._conv2d((16, 7), 1, "conv2d") def test_conv_transpose2d_rectangular_image_one_channel(self): self._conv2d((16, 7), 1, "conv_transpose2d") def test_conv2d_rectangular_image_many_channels(self): self._conv2d((16, 7), 5, "conv2d") def test_conv_transpose2d_rectangular_image_many_channels(self): self._conv2d((16, 7), 5, "conv_transpose2d") def _conv2d(self, image_size, in_channels, func_name): """Test convolution of encrypted tensor with public/private tensors.""" nbatches = [1, 3] kernel_sizes = [(1, 1), (2, 2), (2, 3)] ochannels = [1, 3] paddings = [0, 1, (0, 1)] strides = [1, 2, (1, 2)] dilations = [1, 2] groupings = [1, 2] assert func_name in [ "conv2d", "conv_transpose2d", ], f"Invalid func_name: {func_name}" for kernel_type in [lambda x: x, MPCTensor]: for ( batches, kernel_size, out_channels, padding, stride, dilation, groups, ) in itertools.product( nbatches, kernel_sizes, ochannels, paddings, strides, dilations, groupings, ): # group convolution is not supported on GPU if self.device.type == "cuda" and groups > 1: continue # sample input: input_size = (batches, in_channels * groups, *image_size) input = self._get_random_test_tensor(size=input_size, is_float=True) # sample filtering kernel: if func_name == "conv2d": k_size = (out_channels * groups, in_channels, *kernel_size) else: k_size = (in_channels * groups, out_channels, *kernel_size) kernel = self._get_random_test_tensor(size=k_size, is_float=True) # perform filtering: encr_matrix = MPCTensor(input) encr_kernel = kernel_type(kernel) encr_conv = getattr(encr_matrix, func_name)( encr_kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) # check that result is correct: reference = getattr(F, func_name)( input, kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) self._check(encr_conv, reference, "%s failed" % func_name) def test_max_pooling(self): """Test max_pool of encrypted tensor.""" def _assert_index_match( indices, encrypted_indices, matrix_size, kernel_size, **kwargs, ): # Assert each kernel is one-hot self.assertTrue( encrypted_indices.get_plain_text() .sum(-1) .sum(-1) .eq(torch.ones_like(indices)) .all(), "Encrypted indices are not one-hot", ) # Populate tensor with kernel indices arange_size = matrix_size[-2:] index_values = torch.arange(arange_size.numel(), device=indices.device) index_values = index_values.view(arange_size) index_values = index_values.expand(matrix_size) # Ensure encrypted indices are correct index_mask, size = _pool2d_reshape(index_values, kernel_size, **kwargs) index_mask = index_mask.view(*size, kernel_size, kernel_size) crypten_indices = encrypted_indices.mul(index_mask).sum(-1).sum(-1) self._check( crypten_indices, indices.float(), "max_pool2d indexing is incorrect" ) dilations = [1, 2] for width in range(2, 5): for kernel_size in range(1, width): matrix_size = (1, 4, 5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) strides = list(range(1, kernel_size + 1)) + [(1, kernel_size)] paddings = range(kernel_size // 2 + 1) for ( stride, padding, dilation, ceil_mode, return_indices, ) in itertools.product( strides, paddings, dilations, [False, True], [False, True], ): kwargs = { "stride": stride, "padding": padding, "dilation": dilation, "ceil_mode": ceil_mode, "return_indices": return_indices, } # Skip kernels that lead to 0-size outputs if (kernel_size - 1) * dilation > width - 1: continue reference = F.max_pool2d(matrix, kernel_size, **kwargs) encrypted_matrix = MPCTensor(matrix) encrypted_pool = encrypted_matrix.max_pool2d(kernel_size, **kwargs) if return_indices: indices = reference[1] encrypted_indices = encrypted_pool[1] kwargs.pop("return_indices") _assert_index_match( indices, encrypted_indices, matrix.size(), kernel_size, **kwargs, ) encrypted_pool = encrypted_pool[0] reference = reference[0] self._check(encrypted_pool, reference, "max_pool2d failed") def test_avg_pooling(self): """Test avg_pool of encrypted tensor.""" for width in range(2, 5): for kernel_size in range(1, width): matrix_size = (1, 4, 5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) strides = list(range(1, kernel_size + 1)) + [(1, kernel_size)] paddings = range(kernel_size // 2 + 1) for stride, padding in itertools.product(strides, paddings): kwargs = {"stride": stride, "padding": padding} reference = F.avg_pool2d(matrix, kernel_size, **kwargs) encrypted_matrix = MPCTensor(matrix) encrypted_pool = encrypted_matrix.avg_pool2d(kernel_size, **kwargs) self._check(encrypted_pool, reference, "avg_pool2d failed") def test_adaptive_pooling(self): """test adaptive_avg_pool2d and adaptive_max_pool2d""" for in_size in range(1, 11): for out_size in list(range(1, in_size + 1)) + [None]: input_size = (1, in_size, in_size) output_size = (out_size, out_size) tensor = self._get_random_test_tensor( size=input_size, is_float=True ).unsqueeze(0) encrypted = MPCTensor(tensor) # Test adaptive_avg_pool2d reference = F.adaptive_avg_pool2d(tensor, output_size) encrypted_out = encrypted.adaptive_avg_pool2d(output_size) self._check(encrypted_out, reference, "adaptive_avg_pool2d failed") # Test adapvite_max_pool2d for return_indices in [False, True]: reference = F.adaptive_max_pool2d( tensor, output_size, return_indices=return_indices ) encrypted_out = encrypted.adaptive_max_pool2d( output_size, return_indices=return_indices ) if return_indices: encrypted_out = encrypted_out[0] reference = reference[0] self._check(encrypted_out, reference, "adaptive_max_pool2d failed") def test_take(self): """Tests take function on encrypted tensor""" tensor_size = [5, 5, 5, 5] index = torch.tensor( [[[1, 2], [3, 4]], [[4, 2], [1, 3]]], dtype=torch.long, device=self.device ) tensor = self._get_random_test_tensor(size=tensor_size, is_float=True) # Test when dimension!=None for dimension in range(0, 4): ndarray = tensor.cpu().numpy() reference = torch.from_numpy(ndarray.take(index.cpu(), dimension)) encrypted_tensor = MPCTensor(tensor) encrypted_out = encrypted_tensor.take(index, dimension) self._check(encrypted_out, reference, "take function failed: dimension set") # Test when dimension is default (i.e. None) sizes = [(15,), (5, 10), (15, 10, 5)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) take_indices = [[0], [10], [0, 5, 10]] for indices in take_indices: indices = torch.tensor(indices, device=self.device) self._check( encrypted_tensor.take(indices), tensor.take(indices), f"take failed with indices {indices}", ) def test_neg(self): """Test negative on encrypted tensor.""" for width in range(2, 5): matrix_size = (5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) encrypted_matrix = MPCTensor(matrix) self._check(-encrypted_matrix, -matrix, "__neg__ failed") for func_name in ["neg", "neg_"]: reference = getattr(matrix, func_name)() encrypted_output = getattr(encrypted_matrix, func_name)() self._check(encrypted_output, reference, "%s failed" % func_name) def test_relu(self): """Test relu on encrypted tensor.""" for width in range(2, 5): matrix_size = (5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) # Generate some negative values matrix2 = self._get_random_test_tensor(size=matrix_size, is_float=True) matrix = matrix - matrix2 encrypted_matrix = MPCTensor(matrix) reference = F.relu_(matrix) encrypted_matrix = encrypted_matrix.relu() self._check(encrypted_matrix, reference, "relu failed") def test_comparators(self): """Test comparators (>, >=, <, <=, ==, !=)""" for comp in ["gt", "ge", "lt", "le", "eq", "ne"]: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = tensor_type(tensor2) reference = getattr(tensor1, comp)(tensor2).float() encrypted_out = getattr(encrypted_tensor1, comp)(encrypted_tensor2) self._check(encrypted_out, reference, "%s comparator failed" % comp) # Check deterministic example to guarantee all combinations tensor1 = torch.tensor([2.0, 3.0, 1.0, 2.0, 2.0]) tensor2 = torch.tensor([2.0, 2.0, 2.0, 3.0, 1.0]) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = tensor_type(tensor2) reference = getattr(tensor1, comp)(tensor2).float() encrypted_out = getattr(encrypted_tensor1, comp)(encrypted_tensor2) self._check(encrypted_out, reference, "%s comparator failed" % comp) def test_max_min_pairwise(self): """Tests max and min for the deterministic constant (n^2) algorithm""" self._max_min("pairwise") def test_max_min_log_reduction(self): """Tests max and min for log reduction algorithm""" self._max_min("log_reduction") def test_max_min_double_log_reduction(self): """Tests max and min for double log reduction algorithm""" self._max_min("double_log_reduction") def test_max_min_accelerated_cascade(self): """Tests max and min for accelerated cascading algorithm""" self._max_min("accelerated_cascade") def _max_min(self, method): """Test max and min for the specified algorithm""" sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] test_cases = [ torch.tensor( [[1, 1, 2, 1, 4, 1, 3, 4]], dtype=torch.float, device=self.device ) ] + [self._get_random_test_tensor(size=size, is_float=False) for size in sizes] for tensor in test_cases: tensor = tensor.float() encrypted_tensor = MPCTensor(tensor) for comp in ["max", "min"]: reference = getattr(tensor, comp)() with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)() self._check(encrypted_out, reference, "%s reduction failed" % comp) for dim in range(tensor.dim()): for keepdim in [False, True]: reference = getattr(tensor, comp)(dim, keepdim=keepdim) # Test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=False ) # Check max / min values are correct self._check( encrypted_out[0], reference[0], "%s reduction failed" % comp ) # Test argmax / argmin values are correct out_encr = encrypted_out[1] out_decr = out_encr.get_plain_text().long() argmax_ref = reference[1] # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. if not keepdim: out_decr = out_decr.unsqueeze(dim) argmax_ref = argmax_ref.unsqueeze(dim) mpc_result = tensor.gather(dim, out_decr) torch_result = tensor.gather(dim, argmax_ref) self.assertTrue( (mpc_result == torch_result).all().item(), "%s reduction failed" % comp, ) # Test indices with one_hot = True with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=True ) # Check argmax results val_ref = reference[0] out_encr = encrypted_out[1] out_decr = out_encr.get_plain_text() self.assertTrue((out_decr.sum(dim) == 1).all()) self.assertTrue( ( out_decr.mul(tensor).sum(dim, keepdim=keepdim) == val_ref ).all() ) def test_argmax_argmin_pairwise(self): """Tests argmax and argmin for the deterministic constant (n^2) algorithm""" self._argmax_argmin("pairwise") def test_argmax_argmin_log_reduction(self): """Tests argmax and argmin for log reduction algorithm""" self._argmax_argmin("log_reduction") def test_argmax_argmin_double_log_reduction(self): """Tests argmax and argmin for double log reduction algorithm""" self._argmax_argmin("double_log_reduction") def test_argmax_argmin_accelerated_cascade(self): """Tests max and min for accelerated cascading algorithm""" self._max_min("accelerated_cascade") def _argmax_argmin(self, method): """Test argmax and argmin for specified algorithm""" sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] test_cases = [ torch.tensor( [[1, 1, 2, 1, 4, 1, 3, 4]], dtype=torch.float, device=self.device ) ] + [self._get_random_test_tensor(size=size, is_float=False) for size in sizes] for tensor in test_cases: tensor = tensor.float() encrypted_tensor = MPCTensor(tensor) for comp in ["argmax", "argmin"]: cmp = comp[3:] value = getattr(tensor, cmp)() # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)(one_hot=False) # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. decrypted_out = encrypted_out.get_plain_text() if tensor.dim() == 0: # if input is 0-d, argmax should be 0 self.assertEqual(decrypted_out, 0) else: decrypted_val = tensor.flatten()[decrypted_out.long()] self.assertTrue(decrypted_val.eq(value).all().item()) # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)(one_hot=True) one_hot_indices = (tensor == value).float() decrypted_out = encrypted_out.get_plain_text() self.assertTrue(decrypted_out.sum() == 1) self.assertTrue(decrypted_out.mul(one_hot_indices).sum() == 1) for dim in range(tensor.dim()): for keepdim in [False, True]: # Compute one-hot argmax/min reference in plaintext values, indices = getattr(tensor, cmp)(dim, keepdim=keepdim) # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=False ) # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value.abs decrypted_out = encrypted_out.get_plain_text() if not keepdim: decrypted_out = decrypted_out.unsqueeze(dim) indices = indices.unsqueeze(dim) decrypted_val = tensor.gather(dim, decrypted_out.long()) reference = tensor.gather(dim, indices) self.assertTrue(decrypted_val.eq(reference).all().item()) # test with one_hot = True with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=True ) decrypted_out = encrypted_out.get_plain_text() if not keepdim: values = values.unsqueeze(dim) one_hot_indices = tensor.eq(values).float() self.assertTrue(decrypted_out.sum(dim).eq(1).all()) self.assertTrue( decrypted_out.mul(one_hot_indices).sum(dim).eq(1).all() ) def test_abs_sign(self): """Test absolute value function""" for op in ["abs", "sign"]: tensor = self._get_random_test_tensor(is_float=True) if op == "sign": # do not test on 0 since torch.tensor([0]).sign() = 0 tensor = tensor + (tensor == 0).float() encrypted_tensor = MPCTensor(tensor) reference = getattr(tensor, op)() encrypted_out = getattr(encrypted_tensor, op)() self._check(encrypted_out, reference, "%s failed" % op) def test_approximations(self): """Test appoximate functions (exp, log, sqrt, reciprocal, pos_pow)""" def test_with_inputs(func, input): encrypted_tensor = MPCTensor(input) reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) # Test on [-10, 10] range full_range_cases = ["exp"] tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) for func in full_range_cases: test_with_inputs(func, tensor) # Test on [0, 10] range tensor[tensor == 0] = 1.0 non_zero_cases = ["reciprocal"] for func in non_zero_cases: test_with_inputs(func, tensor) # Test on [0, 10] range tensor = tensor[1001:] pos_cases = ["log", "sqrt"] for func in pos_cases: test_with_inputs(func, tensor) # Test pos_pow with several exponents encrypted_tensor = MPCTensor(tensor) # Reduced the max_value so approximations have less absolute error tensor_exponent = self._get_random_test_tensor( max_value=2, size=tensor.size(), is_float=True ) exponents = [-3, -2, -1, 0, 1, 2, 3, tensor_exponent] exponents += [MPCTensor(tensor_exponent)] for p in exponents: if isinstance(p, MPCTensor): reference = tensor.pow(p.get_plain_text()) else: reference = tensor.pow(p) encrypted_out = encrypted_tensor.pos_pow(p) self._check(encrypted_out, reference, f"pos_pow failed with power {p}") def test_norm(self): """Tests p-norm""" for p in [1, 1.5, 2, 3, float("inf"), "fro"]: for dim in [None, 0, 1, 2]: tensor = self._get_random_test_tensor(size=(3, 3, 3), is_float=True) / 5 if dim is None: reference = tensor.norm(p=p) else: reference = tensor.norm(p=p, dim=dim) encrypted = MPCTensor(tensor) encrypted_out = encrypted.norm(p=p, dim=dim) self._check(encrypted_out, reference, f"{p}-norm failed", tolerance=0.5) def test_logistic(self): """Tests logistic functions (sigmoid, tanh)""" tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) encrypted_tensor = MPCTensor(tensor) cases = ["sigmoid", "tanh"] for func in cases: reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) def test_hardtanh(self): tensor = torch.arange(-10, 10, dtype=torch.float32) encrypted = MPCTensor(tensor) for minval in range(-10, 10): for maxval in range(minval, 11): reference = torch.nn.functional.hardtanh(tensor, minval, maxval) encrypted_out = encrypted.hardtanh(minval, maxval) self._check(encrypted_out, reference, "hardtanh failed") def test_inplace_warning(self): """Tests that a warning is thrown that indicates that the `inplace` kwarg is ignored when a function is called with `inplace=True` """ tensor = get_random_test_tensor(is_float=True) encrypted = MPCTensor(tensor) functions = ["dropout", "_feature_dropout"] for func in functions: warning_str = ( f"CrypTen {func} does not support inplace computation during training." ) with self.assertLogs(logger=logging.getLogger(), level="WARNING") as cm: getattr(encrypted, func)(inplace=True) self.assertTrue(f"WARNING:root:{warning_str}" in cm.output) def test_cos_sin(self): """Tests trigonometric functions (cos, sin)""" tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) encrypted_tensor = MPCTensor(tensor) cases = ["cos", "sin"] for func in cases: reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) def test_softmax(self): """Test softmax and log_softmax function""" for softmax_fn in ["softmax", "log_softmax"]: # Test 0-dim tensor: tensor = self._get_random_test_tensor(size=(), is_float=True) reference = getattr(tensor, softmax_fn)(0) encrypted_tensor = MPCTensor(tensor) encrypted_out = getattr(encrypted_tensor, softmax_fn)(0) self._check(encrypted_out, reference, "0-dim tensor %s failed" % softmax_fn) # Test all other sizes sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 5, 5, 5), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) / 5 encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): reference = getattr(tensor, softmax_fn)(dim) encrypted_out = getattr(encrypted_tensor, softmax_fn)(dim) self._check(encrypted_out, reference, "%s failed" % softmax_fn) def test_get_set(self): """Tests element setting and getting by index""" for tensor_type in [lambda x: x, MPCTensor]: for size in range(1, 5): # Test __getitem__ tensor = self._get_random_test_tensor(size=(size, size), is_float=True) reference = tensor[:, 0] encrypted_tensor = MPCTensor(tensor) encrypted_out = encrypted_tensor[:, 0] self._check(encrypted_out, reference, "getitem failed") reference = tensor[0, :] encrypted_out = encrypted_tensor[0, :] self._check(encrypted_out, reference, "getitem failed") # Test __setitem__ tensor2 = self._get_random_test_tensor(size=(size,), is_float=True) reference = tensor.clone() reference[:, 0] = tensor2 encrypted_out = MPCTensor(tensor) encrypted2 = tensor_type(tensor2) encrypted_out[:, 0] = encrypted2 self._check( encrypted_out, reference, "%s setitem failed" % type(encrypted2) ) reference = tensor.clone() reference[0, :] = tensor2 encrypted_out = MPCTensor(tensor) encrypted2 = tensor_type(tensor2) encrypted_out[0, :] = encrypted2 self._check( encrypted_out, reference, "%s setitem failed" % type(encrypted2) ) def test_pad(self): """Tests padding""" sizes = [(1,), (5,), (1, 1), (5, 5), (5, 5, 5), (5, 3, 32, 32)] pads = [ (0, 0, 0, 0), (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1), (1, 1, 1, 1), (2, 2, 1, 1), (2, 2, 2, 2), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for pad in pads: for value in [0, 1, 10]: if tensor.dim() < 2: pad = pad[:2] reference = torch.nn.functional.pad(tensor, pad, value=value) encrypted_value = MPCTensor(value, device=self.device) encrypted_out = encrypted_tensor.pad(pad, value=encrypted_value) encrypted_out2 = encrypted_tensor.pad(pad, value=value) self._check(encrypted_out, reference, "pad failed") self._check(encrypted_out2, reference, "pad failed") def test_index_add(self): """Test index_add function of encrypted tensor""" index_add_functions = ["index_add", "index_add_"] tensor_size1 = [5, 5, 5, 5] index = torch.tensor( [1, 2, 3, 4, 4, 2, 1, 3], dtype=torch.long, device=self.device ) for dimension in range(0, 4): tensor_size2 = [5, 5, 5, 5] tensor_size2[dimension] = index.size(0) for func in index_add_functions: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor( size=tensor_size1, is_float=True ) tensor2 = self._get_random_test_tensor( size=tensor_size2, is_float=True ) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(dimension, index, tensor2) encrypted_out = getattr(encrypted, func)( dimension, index, encrypted2 ) private_type = tensor_type == MPCTensor self._check( encrypted_out, reference, "%s %s failed" % ("private" if private_type else "public", func), ) if func.endswith("_"): # Check in-place index_add worked self._check( encrypted, reference, "%s %s failed" % ("private" if private_type else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ( "private" if tensor_type == MPCTensor else "public", func, ), ) def test_scatter(self): """Test scatter/scatter_add function of encrypted tensor""" funcs = ["scatter", "scatter_", "scatter_add", "scatter_add_"] sizes = [(5, 5), (5, 5, 5), (5, 5, 5, 5)] for func in funcs: for size in sizes: for tensor_type in [lambda x: x, MPCTensor]: for dim in range(len(size)): tensor1 = self._get_random_test_tensor(size=size, is_float=True) tensor2 = self._get_random_test_tensor(size=size, is_float=True) index = self._get_random_test_tensor(size=size, is_float=False) index = index.abs().clamp(0, 4) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(dim, index, tensor2) encrypted_out = getattr(encrypted, func)(dim, index, encrypted2) private = tensor_type == MPCTensor self._check( encrypted_out, reference, "%s %s failed" % ("private" if private else "public", func), ) if func.endswith("_"): # Check in-place scatter/scatter_add worked self._check( encrypted, reference, "%s %s failed" % ("private" if private else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ("private" if private else "public", func), ) def test_broadcast_arithmetic_ops(self): """Test broadcast of arithmetic functions.""" arithmetic_functions = ["add", "sub", "mul", "div"] # TODO: Add broadcasting for pos_pow since it can take a tensor argument arithmetic_sizes = [ (), (1,), (2,), (1, 1), (1, 2), (2, 1), (2, 2), (1, 1, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 2, 2), (1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (2, 1, 1, 1), (2, 2, 2, 2), ] for tensor_type in [lambda x: x, MPCTensor]: for func in arithmetic_functions: for size1, size2 in itertools.combinations(arithmetic_sizes, 2): exclude_zero = True if func == "div" else False # multiply denominator by 10 to avoid dividing by small num const = 10 if func == "div" else 1 tensor1 = self._get_random_test_tensor(size=size1, is_float=True) tensor2 = self._get_random_test_tensor( size=size2, is_float=True, ex_zero=exclude_zero ) tensor2 *= const encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted1, func)(encrypted2) private = isinstance(encrypted2, MPCTensor) self._check( encrypted_out, reference, "%s %s broadcast failed" % ("private" if private else "public", func), ) # Test with integer tensor tensor2 = self._get_random_test_tensor( size=size2, is_float=False, ex_zero=exclude_zero ) tensor2 *= const reference = getattr(tensor1, func)(tensor2.float()) encrypted_out = getattr(encrypted1, func)(tensor2) self._check( encrypted_out, reference, "%s broadcast failed with public integer tensor" % func, ) def test_broadcast_matmul(self): """Test broadcast of matmul.""" matmul_sizes = [(1, 1), (1, 5), (5, 1), (5, 5)] batch_dims = [(), (1,), (5,), (1, 1), (1, 5), (5, 5)] for tensor_type in [lambda x: x, MPCTensor]: for size in matmul_sizes: for batch1, batch2 in itertools.combinations(batch_dims, 2): size1 = (*batch1, *size) size2 = (*batch2, *size) tensor1 = self._get_random_test_tensor(size=size1, is_float=True) tensor2 = self._get_random_test_tensor(size=size2, is_float=True) tensor2 = tensor2.transpose(-2, -1) encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = tensor1.matmul(tensor2) encrypted_out = encrypted1.matmul(encrypted2) private = isinstance(encrypted2, MPCTensor) self._check( encrypted_out, reference, "%s matmul broadcast failed" % ("private" if private else "public"), ) # Test with integer tensor tensor2 = self._get_random_test_tensor(size=size2, is_float=False) tensor2 = tensor2.float().transpose(-2, -1) reference = tensor1.matmul(tensor2) encrypted_out = encrypted1.matmul(tensor2) self._check( encrypted_out, reference, "matmul broadcast failed with public integer tensor", ) def test_inplace(self): """Test inplace vs. out-of-place functions""" for op in ["add", "sub", "mul", "div"]: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) reference = getattr(torch, op)(tensor1, tensor2) encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) input_tensor_id = id(encrypted1._tensor) input_encrypted_id = id(encrypted1) # Test that out-of-place functions do not modify the input private = isinstance(encrypted2, MPCTensor) encrypted_out = getattr(encrypted1, op)(encrypted2) self._check( encrypted1, tensor1, "%s out-of-place %s modifies input" % ("private" if private else "public", op), ) self._check( encrypted_out, reference, "%s out-of-place %s produces incorrect output" % ("private" if private else "public", op), ) self.assertFalse(id(encrypted_out._tensor) == input_tensor_id) self.assertFalse(id(encrypted_out) == input_encrypted_id) # Test that in-place functions modify the input encrypted_out = getattr(encrypted1, op + "_")(encrypted2) self._check( encrypted1, reference, "%s in-place %s_ does not modify input" % ("private" if private else "public", op), ) self._check( encrypted_out, reference, "%s in-place %s_ produces incorrect output" % ("private" if private else "public", op), ) self.assertTrue(id(encrypted_out._tensor) == input_tensor_id) self.assertTrue(id(encrypted_out) == input_encrypted_id) def test_copy_clone(self): """Tests shallow_copy and clone of encrypted tensors.""" sizes = [(5,), (1, 5), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) # test shallow_copy encrypted_tensor_shallow = encrypted_tensor.shallow_copy() self.assertEqual( id(encrypted_tensor_shallow._tensor), id(encrypted_tensor._tensor) ) self._check(encrypted_tensor_shallow, tensor, "shallow_copy failed") # test clone encrypted_tensor_clone = encrypted_tensor.clone() self.assertNotEqual( id(encrypted_tensor_clone._tensor), id(encrypted_tensor._tensor) ) self._check(encrypted_tensor_clone, tensor, "clone failed") def test_copy_(self): """Tests copy_ function.""" sizes = [(5,), (1, 5), (5, 10, 15)] for size in sizes: tensor1 = self._get_random_test_tensor(size=size, is_float=True) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = MPCTensor(tensor2) encrypted_tensor1.copy_(encrypted_tensor2) self._check(encrypted_tensor1, tensor2, "copy_ failed") def test_index_select(self): """Tests index_select of encrypted tensors.""" sizes = [(5,), (5, 10), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) indices = [[0], [0, 3], [0, 2, 4]] for dim in range(tensor.dim()): for index in indices: index_tensor = torch.tensor( index, dtype=torch.long, device=self.device ) reference = tensor.index_select(dim, index_tensor) encrypted_out = encrypted_tensor.index_select(dim, index_tensor) self._check( encrypted_out, reference, "index_select failed at dim {dim} and index {index}", ) def test_narrow(self): """Tests narrow function.""" sizes = [(5, 6), (5, 6, 7), (6, 7, 8, 9)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encr_tensor = MPCTensor(tensor) for dim in range(len(size)): for start in range(size[dim] - 2): for length in range(1, size[dim] - start): tensor_narrow = tensor.narrow(dim, start, length) encr_tensor_narrow = encr_tensor.narrow(dim, start, length) self._check( encr_tensor_narrow, tensor_narrow, "narrow failed along dimension %d" % dim, ) def test_repeat_expand(self): """Tests repeat and expand of encrypted tensors.""" sizes = [(1, 8), (4, 1, 8)] repeat_dims = [(4, 2, 1), (4, 2, 10)] expand_dims = [(4, 2, 8), (4, 5, 8), (10, 4, 5, 8)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dims in repeat_dims: encrypted_tensor_repeated = encrypted_tensor.repeat(*dims) # test that repeat copies tensor's data self.assertNotEqual( id(encrypted_tensor_repeated._tensor), id(encrypted_tensor._tensor) ) self._check( encrypted_tensor_repeated, tensor.repeat(*dims), f"repeat failed with dims {dims}", ) for dims in expand_dims: encrypted_tensor_expanded = encrypted_tensor.expand(*dims) # test that expand creates a view into the same underlying tensor self.assertNotEqual( id(encrypted_tensor_expanded.share), id(encrypted_tensor.share) ) self._check( encrypted_tensor_expanded, tensor.expand(*dims), f"repeat failed with dims {dims}", ) def test_view_flatten(self): """Tests view and flatten of encrypted tensors.""" sizes = [(100,), (4, 25), (2, 5, 10)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): self._check( encrypted_tensor.flatten(start_dim=dim), tensor.flatten(start_dim=dim), f"flatten failed with dim {dim}", ) shapes = [100, (5, 20), (10, 2, 5), (-1, 10)] for shape in shapes: self._check( encrypted_tensor.view(shape), tensor.view(shape), f"view failed with shape {shape}", ) def test_roll(self): """Tests roll of encrypted tensors.""" sizes = [(10, 1), (5, 2), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) roll_shifts = [1, 2, 3, (2, 1)] roll_dims = [0, 1, 0, (0, 1)] for shifts, dims in zip(roll_shifts, roll_dims): encrypted_tensor_rolled = encrypted_tensor.roll(shifts, dims=dims) self.assertEqual(encrypted_tensor_rolled.numel(), tensor.numel()) self._check( encrypted_tensor_rolled, tensor.roll(shifts, dims=dims), f"roll failed with shift {shifts} and dims {dims}", ) def test_unfold(self): """Tests unfold of encrypted tensors.""" tensor_sizes = [(8,), (15, 10, 5), (5, 10, 15, 20)] for tensor_size in tensor_sizes: tensor = self._get_random_test_tensor(size=tensor_size, is_float=True) encrypted_tensor = MPCTensor(tensor) for size, step in itertools.product(range(1, 4), range(1, 4)): # check unfold along higher dimension if possible for dim in range(tensor.dim()): self._check( encrypted_tensor.unfold(dim, size, step), tensor.unfold(dim, size, step), "unfold failed with dim " f"{dim}, size {size}, and step {step}", ) def test_to(self): """Tests Arithemetic/Binary SharedTensor type conversions.""" from crypten.mpc.ptype import ptype as Ptype tensor_sizes = [(), (1,), (5,), (1, 1), (5, 5), (1, 1, 1), (5, 5, 5)] for size in tensor_sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) binary_encrypted_tensor = encrypted_tensor.to(Ptype.binary) self.assertEqual(binary_encrypted_tensor.ptype, Ptype.binary) # check original encrypted_tensor was not modified after conversion self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to BinarySharedTensor.", ) encrypted_from_binary = binary_encrypted_tensor.to(Ptype.arithmetic) self._check( encrypted_from_binary, tensor, "to failed from BinarySharedTensor to ArithmeticSharedTensor", ) # Test API tensor = self._get_random_test_tensor(size=(5,), is_float=True) encrypted_tensor = MPCTensor(tensor) if torch.cuda.is_available(): encrypted_tensor = encrypted_tensor.to("cuda") self.assertEqual(encrypted_tensor.device.type, "cuda") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cuda", ) encrypted_tensor = encrypted_tensor.to(device="cuda") self.assertEqual(encrypted_tensor.device.type, "cuda") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cuda", ) encrypted_tensor = encrypted_tensor.to("cpu") self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cpu", ) encrypted_tensor = encrypted_tensor.to(device="cpu") self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cpu", ) encrypted_tensor = encrypted_tensor.to(ptype=Ptype.binary) self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.binary) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to BinarySharedTensor.", ) encrypted_tensor = encrypted_tensor.to(ptype=Ptype.arithmetic) self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to ArithmeticSharedTensor.", ) def test_cumsum(self): """Tests cumulative sum on encrypted tensors.""" sizes = [(8,), (5, 10), (15, 10, 5)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): self._check( encrypted_tensor.cumsum(dim), tensor.cumsum(dim), f"cumsum failed along {dim} dim", ) def test_trace(self): """Tests trace operation on 2D encrypted tensors.""" sizes = [(3, 3), (10, 10), (2, 3)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) self._check(encrypted_tensor.trace(), tensor.trace(), "trace failed") def test_flip(self): """Tests flip operation on encrypted tensors.""" sizes = [(5,), (5, 10), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) flip_dims = [(0,), (0, 1), (0, 1, 2)] for dims in flip_dims: if len(dims) <= tensor.dim(): self._check( encrypted_tensor.flip(dims), tensor.flip(dims), f"flip failed with {dims} dims", ) def test_control_flow_failure(self): """Tests that control flow fails as expected""" tensor = self._get_random_test_tensor(is_float=True) encrypted_tensor = MPCTensor(tensor) with self.assertRaises(RuntimeError): if encrypted_tensor: pass with self.assertRaises(RuntimeError): tensor = 5 if encrypted_tensor else 0 with self.assertRaises(RuntimeError): if False: pass elif encrypted_tensor: pass def test_where(self): """Tests where() conditional element selection""" sizes = [(10,), (5, 10), (1, 5, 10)] y_types = [lambda x: x, MPCTensor] for size, y_type in itertools.product(sizes, y_types): tensor1 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor1 = MPCTensor(tensor1) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor2 = y_type(tensor2) condition_tensor = ( self._get_random_test_tensor(max_value=1, size=size, is_float=False) + 1 ) condition_encrypted = MPCTensor(condition_tensor) condition_bool = condition_tensor.bool() reference_out = tensor1.where(condition_bool, tensor2) encrypted_out = encrypted_tensor1.where(condition_bool, encrypted_tensor2) y_is_private = y_type == MPCTensor self._check( encrypted_out, reference_out, f"{'private' if y_is_private else 'public'} y " "where failed with public condition", ) encrypted_out = encrypted_tensor1.where( condition_encrypted, encrypted_tensor2 ) self._check( encrypted_out, reference_out, f"{'private' if y_is_private else 'public'} y " "where failed with private condition", ) # test scalar y scalar = self._get_random_test_tensor(max_value=0, size=[1], is_float=True) self._check( encrypted_tensor1.where(condition_bool, scalar), tensor1.where(condition_bool, scalar), "where failed against scalar y with public condition", ) self._check( encrypted_tensor1.where(condition_encrypted, scalar), tensor1.where(condition_bool, scalar), "where failed against scalar y with private condition", ) def test_unbind(self): """Tests unbind""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted = MPCTensor(tensor) for dim in range(tensor.dim()): reference = tensor.unbind(dim) encrypted_out = encrypted.unbind(dim) self._check_tuple(encrypted_out, reference, "unbind failed") def test_split(self): """Tests split""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted = MPCTensor(tensor) for dim in range(tensor.dim()): # Get random split split = self._get_random_test_tensor( size=(), max_value=tensor.size(dim) ) split = split.abs().clamp(0, tensor.size(dim) - 1) split = split.item() # Test int split int_split = 1 if split == 0 else split reference = tensor.split(int_split, dim=dim) encrypted_out = encrypted.split(int_split, dim=dim) self._check_tuple(encrypted_out, reference, "split failed") # Test list split split = [split, tensor.size(dim) - split] reference = tensor.split(split, dim=dim) encrypted_out = encrypted.split(split, dim=dim) self._check_tuple(encrypted_out, reference, "split failed") def test_set(self): """Tests set correctly re-assigns encrypted shares""" sizes = [(1, 5), (5, 10), (15, 10, 5)] for size in sizes: tensor1 = self._get_random_test_tensor(size=size, is_float=True) encrypted1 = MPCTensor(tensor1) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted2 = MPCTensor(tensor2) # check encrypted set encrypted1.set(encrypted2) self._check( encrypted1, tensor2, f"set with encrypted other failed with size {size}" ) # check plain text set encrypted1 = MPCTensor(tensor1) encrypted1.set(tensor2) self._check( encrypted1, tensor2, f"set with unencrypted other failed with size {size}", ) def test_polynomial(self): """Tests polynomial function""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, max_value=3, is_float=True) encrypted = MPCTensor(tensor) for terms in range(1, 5): coeffs = self._get_random_test_tensor( size=(terms,), max_value=3, is_float=True ) reference = torch.zeros(size=tensor.size(), device=self.device) for i, term in enumerate(coeffs.tolist()): reference += term * tensor.pow(i + 1) # Test list coeffs encrypted_out = encrypted.polynomial(coeffs.tolist()) self._check(encrypted_out, reference, "polynomial failed") # Test plaintext tensor coeffs encrypted_out = encrypted.polynomial(coeffs) self._check(encrypted_out, reference, "polynomial failed") # Test encrypted tensor coeffs coeffs_enc = MPCTensor(coeffs) encrypted_out = encrypted.polynomial(coeffs_enc) self._check(encrypted_out, reference, "polynomial failed") def test_gather(self): """Test gather function of encrypted tensor""" sizes = [(5, 5), (5, 5, 5), (5, 5, 5, 5)] for size in sizes: for dim in range(len(size)): tensor = self._get_random_test_tensor(size=size, is_float=True) index = self._get_random_test_tensor(size=size, is_float=False) index = index.abs().clamp(0, 4) encrypted = MPCTensor(tensor) reference = tensor.gather(dim, index) encrypted_out = encrypted.gather(dim, index) self._check(encrypted_out, reference, f"gather failed with size {size}") def test_dropout(self): """ Tests the dropout functions. Directly compares the zero and non-zero entries of the input tensor, since we cannot force the encrypted and unencrypted versions to generate identical random output. Also confirms that the number of zeros in the encrypted dropout function is as expected. """ all_prob_values = [x * 0.2 for x in range(5)] def get_first_nonzero_value(x): x = x.flatten() x = x[x.abs().ge(1e-4)] x = x.take(torch.tensor(0)) return x # check that the encrypted and plaintext versions scale # identically, by testing on all-ones tensor for prob in all_prob_values: tensor = torch.ones([10, 10, 10], device=self.device).float() encr_tensor = MPCTensor(tensor) dropout_encr = encr_tensor.dropout(prob, training=True) dropout_decr = dropout_encr.get_plain_text() dropout_plain = F.dropout(tensor, prob, training=True) # All non-zero values should be identical in both tensors, so # compare any one of them decr_nonzero_value = get_first_nonzero_value(dropout_decr) plaintext_nonzero_value = get_first_nonzero_value(dropout_plain) self.assertTrue( math.isclose( decr_nonzero_value, plaintext_nonzero_value, rel_tol=1e-2, abs_tol=1e-2, ) ) for dropout_fn in ["dropout", "_feature_dropout"]: for prob in all_prob_values: for size in [(5, 10), (5, 10, 15), (5, 10, 15, 20)]: for inplace in [False, True]: for training in [False, True]: tensor = self._get_random_test_tensor( size=size, ex_zero=True, min_value=1.0, is_float=True ) encr_tensor = MPCTensor(tensor) dropout_encr = getattr(encr_tensor, dropout_fn)( prob, inplace=inplace, training=training ) if training: # Check the scaling for non-zero elements dropout_decr = dropout_encr.get_plain_text() scaled_tensor = tensor / (1 - prob) reference = dropout_decr.where( dropout_decr == 0, scaled_tensor ) else: reference = tensor self._check( dropout_encr, reference, f"dropout failed with size {size} and probability " f"{prob}", ) if inplace: self._check( encr_tensor, reference, f"in-place dropout failed with size {size} and " f"probability {prob}", ) else: self._check( encr_tensor, tensor, "out-of-place dropout modifies input", ) # Check that channels that are zeroed are all zeros if dropout_fn in [ "dropout2d", "dropout3d", "feature_dropout", ]: dropout_encr_flat = dropout_encr.flatten( start_dim=0, end_dim=1 ) dropout_flat = dropout_encr_flat.get_plain_text() for i in range(0, dropout_flat.size(0)): all_zeros = (dropout_flat[i] == 0).all() all_nonzeros = (dropout_flat[i] != 0).all() self.assertTrue( all_zeros or all_nonzeros, f"{dropout_fn} failed for size {size} with " f"training {training} and inplace {inplace}", ) # Check the expected number of zero elements # For speed, restrict test to single p = 0.4 encr_tensor = MPCTensor(torch.empty((int(1e5), 2, 2)).fill_(1).to(self.device)) dropout_encr = encr_tensor.dropout(0.4) dropout_tensor = dropout_encr.get_plain_text() frac_zero = float((dropout_tensor == 0).sum()) / dropout_tensor.nelement() self.assertTrue(math.isclose(frac_zero, 0.4, rel_tol=1e-2, abs_tol=1e-2)) def test_tuple_cache(self): # Skip RSS setting since it does not generate tuples if cfg.mpc.protocol == "replicated": return # TODO: encorporate wrap_rng for 3PC+ settings if comm.get().get_world_size() > 2: return provider = crypten.mpc.get_default_provider() # Test tracing attribute crypten.trace() self.assertTrue(provider.tracing) x = get_random_test_tensor(is_float=True) x = crypten.cryptensor(x) _ = x.square() _ = x * x _ = x.matmul(x.t()) _ = x.relu() y = x.unsqueeze(0) _ = y.conv1d(y, stride=2) # Populate reference requests ref_names = ["square"] ref_names += ["generate_additive_triple"] * 2 ref_names += ["generate_binary_triple"] * 7 + ["B2A_rng"] ref_names += ["generate_additive_triple"] * 2 ref_args = [ (torch.Size([1, 5]),), (torch.Size([1, 5]), torch.Size([1, 5]), "mul"), (torch.Size([1, 5]), torch.Size([5, 1]), "matmul"), (torch.Size([1, 1, 5]), torch.Size([1, 1, 5])), ] ref_args += [(torch.Size([2, 1, 1, 5]), torch.Size([2, 1, 1, 5]))] * 6 ref_args += [(torch.Size([1, 5]),)] ref_args += [(torch.Size([1, 5]), torch.Size([1, 5]), "mul")] ref_args += [(torch.Size([1, 1, 5]), torch.Size([1, 1, 5]), "conv1d")] kwargs = {"device": torch.device("cpu")} conv_kwargs = {"device": torch.device("cpu"), "stride": 2} requests = [(ref_names[i], ref_args[i], kwargs) for i in range(12)] requests += [(ref_names[12], ref_args[12], conv_kwargs)] self.assertEqual( provider.request_cache, requests, "TupleProvider request cache incorrect", ) crypten.trace(False) self.assertFalse(provider.tracing) # Check that cache populates as expected crypten.fill_cache() kwargs = frozenset(kwargs.items()) conv_kwargs = frozenset(conv_kwargs.items()) keys = [(ref_names[i], ref_args[i], kwargs) for i in range(12)] keys += [(ref_names[12], ref_args[12], conv_kwargs)] self.assertEqual( set(provider.tuple_cache.keys()), set(keys), "TupleProvider tuple_cache populated incorrectly", ) # Test that function calls return from cache when trace is off crypten.trace(False) _ = x.square() _ = x * x _ = x.matmul(x.t()) _ = x.relu() y = x.unsqueeze(0) _ = y.conv1d(y, stride=2) for v in provider.tuple_cache.values(): self.assertEqual( len(v), 0, msg="TupleProvider is not popping tuples properly from cache" ) # Run all unit tests with both TFP and TTP providers class TestTFP(MultiProcessTestCase, TestMPC): def setUp(self): self._original_provider = cfg.mpc.provider crypten.CrypTensor.set_grad_enabled(False) cfg.mpc.provider = "TFP" super(TestTFP, self).setUp() def tearDown(self): cfg.mpc.provider = self._original_provider crypten.CrypTensor.set_grad_enabled(True) super(TestTFP, self).tearDown() class TestTTP(MultiProcessTestCase, TestMPC): def setUp(self): self._original_provider = cfg.mpc.provider crypten.CrypTensor.set_grad_enabled(False) cfg.mpc.provider = "TTP" super(TestTTP, self).setUp() def tearDown(self): cfg.mpc.provider = self._original_provider crypten.CrypTensor.set_grad_enabled(True) super(TestTTP, self).tearDown() class Test3PC(MultiProcessTestCase, TestMPC): def setUp(self): super(Test3PC, self).setUp(world_size=3) class TestRSS(MultiProcessTestCase, TestMPC): def setUp(self): self._original_protocol = cfg.mpc.protocol cfg.mpc.protocol = "replicated" super(TestRSS, self).setUp(world_size=3) def tearDown(self): cfg.mpc.protocol = self._original_protocol super(TestRSS, self).tearDown() # This code only runs when executing the file outside the test harness (e.g. # via the buck target of another test) if __name__ == "__main__": unittest.main()
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import math import unittest import crypten import crypten.communicator as comm import torch import torch.nn.functional as F from crypten.common.functions.pooling import _pool2d_reshape from crypten.common.rng import generate_kbit_random_tensor, generate_random_ring_element from crypten.common.tensor_types import is_float_tensor from crypten.config import cfg from crypten.mpc import MPCTensor, ptype as Ptype from crypten.mpc.primitives import ArithmeticSharedTensor, BinarySharedTensor from test.multiprocess_test_case import MultiProcessTestCase, get_random_test_tensor class TestMPC(object): """ This class tests all functions of MPCTensor. """ def _get_random_test_tensor(self, *args, **kwargs): return get_random_test_tensor(device=self.device, *args, **kwargs) def _check(self, encrypted_tensor, reference, msg, dst=None, tolerance=None): if tolerance is None: tolerance = getattr(self, "default_tolerance", 0.05) tensor = encrypted_tensor.get_plain_text(dst=dst) if dst is not None and dst != self.rank: self.assertIsNone(tensor) return # Check sizes match self.assertTrue(tensor.size() == reference.size(), msg) self.assertTrue(is_float_tensor(reference), "reference must be a float") if tensor.device != reference.device: tensor = tensor.cpu() reference = reference.cpu() diff = (tensor - reference).abs_() norm_diff = diff.div(tensor.abs() + reference.abs()).abs_() test_passed = norm_diff.le(tolerance) + diff.le(tolerance * 0.1) test_passed = test_passed.gt(0).all().item() == 1 if not test_passed: logging.info(msg) logging.info("Result %s" % tensor) logging.info("Reference %s" % reference) logging.info("Result - Reference = %s" % (tensor - reference)) self.assertTrue(test_passed, msg=msg) def _check_tuple(self, encrypted_tuple, reference, msg, tolerance=None): self.assertTrue(isinstance(encrypted_tuple, tuple)) self.assertEqual(len(encrypted_tuple), len(reference)) for i in range(len(reference)): self._check(encrypted_tuple[i], reference[i], msg, tolerance=tolerance) def test_repr(self): a = self._get_random_test_tensor(size=(1,)) arithmetic = MPCTensor(a, ptype=Ptype.arithmetic) binary = MPCTensor(a, ptype=Ptype.binary) # Make sure these don't crash print(arithmetic) repr(arithmetic) print(binary) repr(binary) def test_from_shares(self): """Tests MPCTensor.from_shares() functionality.""" # settings for test: num_parties = int(self.world_size) size = (5, 4) def _generate_tensor(ptype): reference = self._get_random_test_tensor(size=size, is_float=False) # generate arithmetic sharing of reference tensor: if ptype == Ptype.arithmetic: zero_shares = generate_random_ring_element( (num_parties, *size), device=self.device ) zero_shares = zero_shares - zero_shares.roll(1, dims=0) shares = list(zero_shares.unbind(0)) shares[0] += reference # generate binary sharing of reference tensor: else: zero_shares = generate_kbit_random_tensor( (num_parties, *size), device=self.device ) zero_shares = zero_shares ^ zero_shares.roll(1, dims=0) shares = list(zero_shares.unbind(0)) shares[0] ^= reference # return shares and reference: return shares, reference # test both types: for ptype in [Ptype.arithmetic, Ptype.binary]: # generate shares, sync them between parties, and create tensor: shares, reference = _generate_tensor(ptype) share = comm.get().scatter(shares, 0) encrypted_tensor = MPCTensor.from_shares(share, ptype=ptype) # check resulting tensor: self.assertIsInstance(encrypted_tensor, MPCTensor) self.assertEqual(encrypted_tensor.ptype, ptype) self.assertIsInstance(encrypted_tensor._tensor, ptype.to_tensor()) decrypted_tensor = encrypted_tensor.reveal() self.assertTrue(torch.all(decrypted_tensor.eq(reference)).item()) def test_share_attr(self): """Tests share attribute getter and setter""" for is_float in (True, False): reference = self._get_random_test_tensor(is_float=is_float) encrypted_tensor = MPCTensor(reference) underlying_tensor = encrypted_tensor.share self.assertTrue( torch.equal(encrypted_tensor.share, underlying_tensor), "share getter failed", ) new_share = self._get_random_test_tensor(is_float=False) encrypted_tensor.share = new_share self.assertTrue( torch.equal(encrypted_tensor.share, new_share), "share setter failed" ) def test_encrypt_decrypt(self): """ Tests tensor encryption and decryption for both positive and negative values. """ sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 3, 32, 32), (5, 3, 32, 32), ] for size in sizes: # encryption and decryption without source: reference = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(reference) self._check(encrypted_tensor, reference, "en/decryption failed") for dst in range(self.world_size): self._check( encrypted_tensor, reference, "en/decryption failed", dst=dst ) # test creation via new() function: encrypted_tensor2 = encrypted_tensor.new(reference) self.assertIsInstance( encrypted_tensor2, MPCTensor, "new() returns incorrect type" ) self._check(encrypted_tensor2, reference, "en/decryption failed") # TODO: Implement broadcast_size on GPU if self.device.type == "cuda": continue # encryption and decryption with source: for src in range(self.world_size): input_tensor = reference if src == self.rank else [] encrypted_tensor = MPCTensor(input_tensor, src=src, broadcast_size=True) for dst in range(self.world_size): self._check( encrypted_tensor, reference, "en/decryption with broadcast_size failed", dst=dst, ) # MPCTensors cannot be initialized with None: with self.assertRaises(ValueError): _ = MPCTensor(None) def test_arithmetic(self): """Tests arithmetic functions on encrypted tensor.""" arithmetic_functions = ["add", "add_", "sub", "sub_", "mul", "mul_"] for func in arithmetic_functions: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted, func)(encrypted2) self._check( encrypted_out, reference, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) if "_" in func: # Check in-place op worked self._check( encrypted, reference, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ("private" if tensor_type == MPCTensor else "public", func), ) # Check encrypted vector with encrypted scalar works. tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True, size=(1,)) encrypted1 = MPCTensor(tensor1) encrypted2 = MPCTensor(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted1, func)(encrypted2) self._check(encrypted_out, reference, "private %s failed" % func) tensor = self._get_random_test_tensor(is_float=True) reference = tensor * tensor encrypted = MPCTensor(tensor) encrypted_out = encrypted.square() self._check(encrypted_out, reference, "square failed") # Test radd, rsub, and rmul reference = 2 + tensor1 encrypted = MPCTensor(tensor1) encrypted_out = 2 + encrypted self._check(encrypted_out, reference, "right add failed") reference = 2 - tensor1 encrypted_out = 2 - encrypted self._check(encrypted_out, reference, "right sub failed") reference = 2 * tensor1 encrypted_out = 2 * encrypted self._check(encrypted_out, reference, "right mul failed") def test_sum(self): """Tests sum reduction on encrypted tensor.""" tensor = self._get_random_test_tensor(size=(100, 100), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.sum(), tensor.sum(), "sum failed") for dim in [0, 1]: reference = tensor.sum(dim) encrypted_out = encrypted.sum(dim) self._check(encrypted_out, reference, "sum failed") def test_prod(self): """Tests prod reduction on encrypted tensor.""" tensor = self._get_random_test_tensor(size=(3, 3), max_value=3, is_float=False) encrypted = MPCTensor(tensor) self._check(encrypted.prod(), tensor.prod().float(), "prod failed") tensor = self._get_random_test_tensor( size=(5, 5, 5), max_value=3, is_float=False ) encrypted = MPCTensor(tensor) for dim in [0, 1, 2]: reference = tensor.prod(dim).float() encrypted_out = encrypted.prod(dim) self._check(encrypted_out, reference, "prod failed") def test_ptype(self): """Test that ptype attribute creates the correct type of encrypted tensor""" ptype_values = [crypten.mpc.arithmetic, crypten.mpc.binary] tensor_types = [ArithmeticSharedTensor, BinarySharedTensor] for i, curr_ptype in enumerate(ptype_values): tensor = self._get_random_test_tensor(is_float=False) encr_tensor = crypten.cryptensor(tensor, ptype=curr_ptype) assert isinstance(encr_tensor._tensor, tensor_types[i]), "ptype test failed" def test_div(self): """Tests division of encrypted tensor by scalar and tensor.""" for function in ["div", "div_"]: for scalar in [2, 2.0]: tensor = self._get_random_test_tensor(is_float=True) reference = tensor.float().div(scalar) encrypted_tensor = MPCTensor(tensor) encrypted_tensor = getattr(encrypted_tensor, function)(scalar) self._check(encrypted_tensor, reference, "scalar division failed") # multiply denominator by 10 to avoid dividing by small num divisor = self._get_random_test_tensor(is_float=True, ex_zero=True) * 10 reference = tensor.div(divisor) encrypted_tensor = MPCTensor(tensor) encrypted_tensor = getattr(encrypted_tensor, function)(divisor) self._check(encrypted_tensor, reference, "tensor division failed") def test_mean(self): """Tests computing means of encrypted tensors.""" tensor = self._get_random_test_tensor(size=(5, 10, 15), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.mean(), tensor.mean(), "mean failed") for dim in [0, 1, 2]: reference = tensor.mean(dim) encrypted_out = encrypted.mean(dim) self._check(encrypted_out, reference, "mean failed") def test_var(self): """Tests computing variances of encrypted tensors.""" tensor = self._get_random_test_tensor(size=(5, 10, 15), is_float=True) encrypted = MPCTensor(tensor) self._check(encrypted.var(), tensor.var(), "var failed") for dim in [0, 1, 2]: reference = tensor.var(dim) encrypted_out = encrypted.var(dim) self._check(encrypted_out, reference, "var failed") def test_matmul(self): """Test matrix multiplication.""" for tensor_type in [lambda x: x, MPCTensor]: tensor = self._get_random_test_tensor(max_value=7, is_float=True) for width in range(2, tensor.nelement()): matrix_size = (tensor.nelement(), width) matrix = self._get_random_test_tensor( max_value=7, size=matrix_size, is_float=True ) reference = tensor.matmul(matrix) encrypted_tensor = MPCTensor(tensor) matrix = tensor_type(matrix) encrypted_tensor = encrypted_tensor.matmul(matrix) self._check( encrypted_tensor, reference, "Private-%s matrix multiplication failed" % ("private" if tensor_type == MPCTensor else "public"), ) def test_dot_ger(self): """Test dot product of vector and encrypted tensor.""" for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True).squeeze() tensor2 = self._get_random_test_tensor(is_float=True).squeeze() dot_reference = tensor1.dot(tensor2) ger_reference = torch.ger(tensor1, tensor2) tensor2 = tensor_type(tensor2) # dot encrypted_tensor = MPCTensor(tensor1) encrypted_out = encrypted_tensor.dot(tensor2) self._check( encrypted_out, dot_reference, "%s dot product failed" % "private" if tensor_type == MPCTensor else "public", ) # ger encrypted_tensor = MPCTensor(tensor1) encrypted_out = encrypted_tensor.ger(tensor2) self._check( encrypted_out, ger_reference, "%s outer product failed" % "private" if tensor_type == MPCTensor else "public", ) def test_squeeze(self): tensor = self._get_random_test_tensor(is_float=True) for dim in [0, 1, 2]: # Test unsqueeze reference = tensor.unsqueeze(dim) encrypted = MPCTensor(tensor) encrypted_out = encrypted.unsqueeze(dim) self._check(encrypted_out, reference, "unsqueeze failed") # Test squeeze encrypted = MPCTensor(tensor.unsqueeze(0)) encrypted_out = encrypted.squeeze() self._check(encrypted_out, reference.squeeze(), "squeeze failed") # Check that the encrypted_out and encrypted point to the same # thing. encrypted_out[0:2] = torch.tensor( [0, 1], dtype=torch.float, device=self.device ) ref = encrypted.squeeze().get_plain_text() self._check(encrypted_out, ref, "squeeze failed") def test_transpose(self): sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 3, 32, 32), (5, 3, 32, 32), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) if len(size) == 2: # t() asserts dim == 2 reference = tensor.t() encrypted_out = encrypted_tensor.t() self._check(encrypted_out, reference, "t() failed") for dim0 in range(len(size)): for dim1 in range(len(size)): reference = tensor.transpose(dim0, dim1) encrypted_out = encrypted_tensor.transpose(dim0, dim1) self._check(encrypted_out, reference, "transpose failed") def test_conv1d_smaller_signal_one_channel(self): self._conv1d(5, 1) def test_conv1d_smaller_signal_many_channels(self): self._conv1d(5, 5) def test_conv1d_larger_signal_one_channel(self): self._conv1d(16, 1) def test_conv1d_larger_signal_many_channels(self): self._conv1d(16, 5) def _conv1d(self, signal_size, in_channels): """Test convolution of encrypted tensor with public/private tensors.""" nbatches = [1, 3] kernel_sizes = [1, 2, 3] ochannels = [1, 3, 6] paddings = [0, 1] strides = [1, 2] dilations = [1, 2] groupings = [1, 2] for func_name in ["conv1d", "conv_transpose1d"]: for kernel_type in [lambda x: x, MPCTensor]: for ( batches, kernel_size, out_channels, padding, stride, dilation, groups, ) in itertools.product( nbatches, kernel_sizes, ochannels, paddings, strides, dilations, groupings, ): # group convolution is not supported on GPU if self.device.type == "cuda" and groups > 1: continue input_size = (batches, in_channels * groups, signal_size) signal = self._get_random_test_tensor( size=input_size, is_float=True ) if func_name == "conv1d": k_size = (out_channels * groups, in_channels, kernel_size) else: k_size = (in_channels * groups, out_channels, kernel_size) kernel = self._get_random_test_tensor(size=k_size, is_float=True) reference = getattr(F, func_name)( signal, kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) encrypted_signal = MPCTensor(signal) encrypted_kernel = kernel_type(kernel) encrypted_conv = getattr(encrypted_signal, func_name)( encrypted_kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) self._check(encrypted_conv, reference, f"{func_name} failed") def test_conv2d_square_image_one_channel(self): self._conv2d((5, 5), 1, "conv2d") def test_conv_transpose2d_square_image_one_channel(self): self._conv2d((5, 5), 1, "conv_transpose2d") def test_conv2d_square_image_many_channels(self): self._conv2d((5, 5), 5, "conv2d") def test_conv_transpose2d_square_image_many_channels(self): self._conv2d((5, 5), 5, "conv_transpose2d") def test_conv2d_rectangular_image_one_channel(self): self._conv2d((16, 7), 1, "conv2d") def test_conv_transpose2d_rectangular_image_one_channel(self): self._conv2d((16, 7), 1, "conv_transpose2d") def test_conv2d_rectangular_image_many_channels(self): self._conv2d((16, 7), 5, "conv2d") def test_conv_transpose2d_rectangular_image_many_channels(self): self._conv2d((16, 7), 5, "conv_transpose2d") def _conv2d(self, image_size, in_channels, func_name): """Test convolution of encrypted tensor with public/private tensors.""" nbatches = [1, 3] kernel_sizes = [(1, 1), (2, 2), (2, 3)] ochannels = [1, 3] paddings = [0, 1, (0, 1)] strides = [1, 2, (1, 2)] dilations = [1, 2] groupings = [1, 2] assert func_name in [ "conv2d", "conv_transpose2d", ], f"Invalid func_name: {func_name}" for kernel_type in [lambda x: x, MPCTensor]: for ( batches, kernel_size, out_channels, padding, stride, dilation, groups, ) in itertools.product( nbatches, kernel_sizes, ochannels, paddings, strides, dilations, groupings, ): # group convolution is not supported on GPU if self.device.type == "cuda" and groups > 1: continue # sample input: input_size = (batches, in_channels * groups, *image_size) input = self._get_random_test_tensor(size=input_size, is_float=True) # sample filtering kernel: if func_name == "conv2d": k_size = (out_channels * groups, in_channels, *kernel_size) else: k_size = (in_channels * groups, out_channels, *kernel_size) kernel = self._get_random_test_tensor(size=k_size, is_float=True) # perform filtering: encr_matrix = MPCTensor(input) encr_kernel = kernel_type(kernel) encr_conv = getattr(encr_matrix, func_name)( encr_kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) # check that result is correct: reference = getattr(F, func_name)( input, kernel, padding=padding, stride=stride, dilation=dilation, groups=groups, ) self._check(encr_conv, reference, "%s failed" % func_name) def test_max_pooling(self): """Test max_pool of encrypted tensor.""" def _assert_index_match( indices, encrypted_indices, matrix_size, kernel_size, **kwargs, ): # Assert each kernel is one-hot self.assertTrue( encrypted_indices.get_plain_text() .sum(-1) .sum(-1) .eq(torch.ones_like(indices)) .all(), "Encrypted indices are not one-hot", ) # Populate tensor with kernel indices arange_size = matrix_size[-2:] index_values = torch.arange(arange_size.numel(), device=indices.device) index_values = index_values.view(arange_size) index_values = index_values.expand(matrix_size) # Ensure encrypted indices are correct index_mask, size = _pool2d_reshape(index_values, kernel_size, **kwargs) index_mask = index_mask.view(*size, kernel_size, kernel_size) crypten_indices = encrypted_indices.mul(index_mask).sum(-1).sum(-1) self._check( crypten_indices, indices.float(), "max_pool2d indexing is incorrect" ) dilations = [1, 2] for width in range(2, 5): for kernel_size in range(1, width): matrix_size = (1, 4, 5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) strides = list(range(1, kernel_size + 1)) + [(1, kernel_size)] paddings = range(kernel_size // 2 + 1) for ( stride, padding, dilation, ceil_mode, return_indices, ) in itertools.product( strides, paddings, dilations, [False, True], [False, True], ): kwargs = { "stride": stride, "padding": padding, "dilation": dilation, "ceil_mode": ceil_mode, "return_indices": return_indices, } # Skip kernels that lead to 0-size outputs if (kernel_size - 1) * dilation > width - 1: continue reference = F.max_pool2d(matrix, kernel_size, **kwargs) encrypted_matrix = MPCTensor(matrix) encrypted_pool = encrypted_matrix.max_pool2d(kernel_size, **kwargs) if return_indices: indices = reference[1] encrypted_indices = encrypted_pool[1] kwargs.pop("return_indices") _assert_index_match( indices, encrypted_indices, matrix.size(), kernel_size, **kwargs, ) encrypted_pool = encrypted_pool[0] reference = reference[0] self._check(encrypted_pool, reference, "max_pool2d failed") def test_avg_pooling(self): """Test avg_pool of encrypted tensor.""" for width in range(2, 5): for kernel_size in range(1, width): matrix_size = (1, 4, 5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) strides = list(range(1, kernel_size + 1)) + [(1, kernel_size)] paddings = range(kernel_size // 2 + 1) for stride, padding in itertools.product(strides, paddings): kwargs = {"stride": stride, "padding": padding} reference = F.avg_pool2d(matrix, kernel_size, **kwargs) encrypted_matrix = MPCTensor(matrix) encrypted_pool = encrypted_matrix.avg_pool2d(kernel_size, **kwargs) self._check(encrypted_pool, reference, "avg_pool2d failed") def test_adaptive_pooling(self): """test adaptive_avg_pool2d and adaptive_max_pool2d""" for in_size in range(1, 11): for out_size in list(range(1, in_size + 1)) + [None]: input_size = (1, in_size, in_size) output_size = (out_size, out_size) tensor = self._get_random_test_tensor( size=input_size, is_float=True ).unsqueeze(0) encrypted = MPCTensor(tensor) # Test adaptive_avg_pool2d reference = F.adaptive_avg_pool2d(tensor, output_size) encrypted_out = encrypted.adaptive_avg_pool2d(output_size) self._check(encrypted_out, reference, "adaptive_avg_pool2d failed") # Test adapvite_max_pool2d for return_indices in [False, True]: reference = F.adaptive_max_pool2d( tensor, output_size, return_indices=return_indices ) encrypted_out = encrypted.adaptive_max_pool2d( output_size, return_indices=return_indices ) if return_indices: encrypted_out = encrypted_out[0] reference = reference[0] self._check(encrypted_out, reference, "adaptive_max_pool2d failed") def test_take(self): """Tests take function on encrypted tensor""" tensor_size = [5, 5, 5, 5] index = torch.tensor( [[[1, 2], [3, 4]], [[4, 2], [1, 3]]], dtype=torch.long, device=self.device ) tensor = self._get_random_test_tensor(size=tensor_size, is_float=True) # Test when dimension!=None for dimension in range(0, 4): ndarray = tensor.cpu().numpy() reference = torch.from_numpy(ndarray.take(index.cpu(), dimension)) encrypted_tensor = MPCTensor(tensor) encrypted_out = encrypted_tensor.take(index, dimension) self._check(encrypted_out, reference, "take function failed: dimension set") # Test when dimension is default (i.e. None) sizes = [(15,), (5, 10), (15, 10, 5)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) take_indices = [[0], [10], [0, 5, 10]] for indices in take_indices: indices = torch.tensor(indices, device=self.device) self._check( encrypted_tensor.take(indices), tensor.take(indices), f"take failed with indices {indices}", ) def test_neg(self): """Test negative on encrypted tensor.""" for width in range(2, 5): matrix_size = (5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) encrypted_matrix = MPCTensor(matrix) self._check(-encrypted_matrix, -matrix, "__neg__ failed") for func_name in ["neg", "neg_"]: reference = getattr(matrix, func_name)() encrypted_output = getattr(encrypted_matrix, func_name)() self._check(encrypted_output, reference, "%s failed" % func_name) def test_relu(self): """Test relu on encrypted tensor.""" for width in range(2, 5): matrix_size = (5, width) matrix = self._get_random_test_tensor(size=matrix_size, is_float=True) # Generate some negative values matrix2 = self._get_random_test_tensor(size=matrix_size, is_float=True) matrix = matrix - matrix2 encrypted_matrix = MPCTensor(matrix) reference = F.relu_(matrix) encrypted_matrix = encrypted_matrix.relu() self._check(encrypted_matrix, reference, "relu failed") def test_comparators(self): """Test comparators (>, >=, <, <=, ==, !=)""" for comp in ["gt", "ge", "lt", "le", "eq", "ne"]: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = tensor_type(tensor2) reference = getattr(tensor1, comp)(tensor2).float() encrypted_out = getattr(encrypted_tensor1, comp)(encrypted_tensor2) self._check(encrypted_out, reference, "%s comparator failed" % comp) # Check deterministic example to guarantee all combinations tensor1 = torch.tensor([2.0, 3.0, 1.0, 2.0, 2.0]) tensor2 = torch.tensor([2.0, 2.0, 2.0, 3.0, 1.0]) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = tensor_type(tensor2) reference = getattr(tensor1, comp)(tensor2).float() encrypted_out = getattr(encrypted_tensor1, comp)(encrypted_tensor2) self._check(encrypted_out, reference, "%s comparator failed" % comp) def test_max_min_pairwise(self): """Tests max and min for the deterministic constant (n^2) algorithm""" self._max_min("pairwise") def test_max_min_log_reduction(self): """Tests max and min for log reduction algorithm""" self._max_min("log_reduction") def test_max_min_double_log_reduction(self): """Tests max and min for double log reduction algorithm""" self._max_min("double_log_reduction") def test_max_min_accelerated_cascade(self): """Tests max and min for accelerated cascading algorithm""" self._max_min("accelerated_cascade") def _max_min(self, method): """Test max and min for the specified algorithm""" sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] test_cases = [ torch.tensor( [[1, 1, 2, 1, 4, 1, 3, 4]], dtype=torch.float, device=self.device ) ] + [self._get_random_test_tensor(size=size, is_float=False) for size in sizes] for tensor in test_cases: tensor = tensor.float() encrypted_tensor = MPCTensor(tensor) for comp in ["max", "min"]: reference = getattr(tensor, comp)() with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)() self._check(encrypted_out, reference, "%s reduction failed" % comp) for dim in range(tensor.dim()): for keepdim in [False, True]: reference = getattr(tensor, comp)(dim, keepdim=keepdim) # Test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=False ) # Check max / min values are correct self._check( encrypted_out[0], reference[0], "%s reduction failed" % comp ) # Test argmax / argmin values are correct out_encr = encrypted_out[1] out_decr = out_encr.get_plain_text().long() argmax_ref = reference[1] # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. if not keepdim: out_decr = out_decr.unsqueeze(dim) argmax_ref = argmax_ref.unsqueeze(dim) mpc_result = tensor.gather(dim, out_decr) torch_result = tensor.gather(dim, argmax_ref) self.assertTrue( (mpc_result == torch_result).all().item(), "%s reduction failed" % comp, ) # Test indices with one_hot = True with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=True ) # Check argmax results val_ref = reference[0] out_encr = encrypted_out[1] out_decr = out_encr.get_plain_text() self.assertTrue((out_decr.sum(dim) == 1).all()) self.assertTrue( ( out_decr.mul(tensor).sum(dim, keepdim=keepdim) == val_ref ).all() ) def test_argmax_argmin_pairwise(self): """Tests argmax and argmin for the deterministic constant (n^2) algorithm""" self._argmax_argmin("pairwise") def test_argmax_argmin_log_reduction(self): """Tests argmax and argmin for log reduction algorithm""" self._argmax_argmin("log_reduction") def test_argmax_argmin_double_log_reduction(self): """Tests argmax and argmin for double log reduction algorithm""" self._argmax_argmin("double_log_reduction") def test_argmax_argmin_accelerated_cascade(self): """Tests max and min for accelerated cascading algorithm""" self._max_min("accelerated_cascade") def _argmax_argmin(self, method): """Test argmax and argmin for specified algorithm""" sizes = [ (), (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] test_cases = [ torch.tensor( [[1, 1, 2, 1, 4, 1, 3, 4]], dtype=torch.float, device=self.device ) ] + [self._get_random_test_tensor(size=size, is_float=False) for size in sizes] for tensor in test_cases: tensor = tensor.float() encrypted_tensor = MPCTensor(tensor) for comp in ["argmax", "argmin"]: cmp = comp[3:] value = getattr(tensor, cmp)() # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)(one_hot=False) # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. decrypted_out = encrypted_out.get_plain_text() if tensor.dim() == 0: # if input is 0-d, argmax should be 0 self.assertEqual(decrypted_out, 0) else: decrypted_val = tensor.flatten()[decrypted_out.long()] self.assertTrue(decrypted_val.eq(value).all().item()) # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)(one_hot=True) one_hot_indices = (tensor == value).float() decrypted_out = encrypted_out.get_plain_text() self.assertTrue(decrypted_out.sum() == 1) self.assertTrue(decrypted_out.mul(one_hot_indices).sum() == 1) for dim in range(tensor.dim()): for keepdim in [False, True]: # Compute one-hot argmax/min reference in plaintext values, indices = getattr(tensor, cmp)(dim, keepdim=keepdim) # test with one_hot = False with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=False ) # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value.abs decrypted_out = encrypted_out.get_plain_text() if not keepdim: decrypted_out = decrypted_out.unsqueeze(dim) indices = indices.unsqueeze(dim) decrypted_val = tensor.gather(dim, decrypted_out.long()) reference = tensor.gather(dim, indices) self.assertTrue(decrypted_val.eq(reference).all().item()) # test with one_hot = True with cfg.temp_override({"functions.max_method": method}): encrypted_out = getattr(encrypted_tensor, comp)( dim, keepdim=keepdim, one_hot=True ) decrypted_out = encrypted_out.get_plain_text() if not keepdim: values = values.unsqueeze(dim) one_hot_indices = tensor.eq(values).float() self.assertTrue(decrypted_out.sum(dim).eq(1).all()) self.assertTrue( decrypted_out.mul(one_hot_indices).sum(dim).eq(1).all() ) def test_abs_sign(self): """Test absolute value function""" for op in ["abs", "sign"]: tensor = self._get_random_test_tensor(is_float=True) if op == "sign": # do not test on 0 since torch.tensor([0]).sign() = 0 tensor = tensor + (tensor == 0).float() encrypted_tensor = MPCTensor(tensor) reference = getattr(tensor, op)() encrypted_out = getattr(encrypted_tensor, op)() self._check(encrypted_out, reference, "%s failed" % op) def test_approximations(self): """Test appoximate functions (exp, log, sqrt, reciprocal, pos_pow)""" def test_with_inputs(func, input): encrypted_tensor = MPCTensor(input) reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) # Test on [-10, 10] range full_range_cases = ["exp"] tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) for func in full_range_cases: test_with_inputs(func, tensor) # Test on [0, 10] range tensor[tensor == 0] = 1.0 non_zero_cases = ["reciprocal"] for func in non_zero_cases: test_with_inputs(func, tensor) # Test on [0, 10] range tensor = tensor[1001:] pos_cases = ["log", "sqrt"] for func in pos_cases: test_with_inputs(func, tensor) # Test pos_pow with several exponents encrypted_tensor = MPCTensor(tensor) # Reduced the max_value so approximations have less absolute error tensor_exponent = self._get_random_test_tensor( max_value=2, size=tensor.size(), is_float=True ) exponents = [-3, -2, -1, 0, 1, 2, 3, tensor_exponent] exponents += [MPCTensor(tensor_exponent)] for p in exponents: if isinstance(p, MPCTensor): reference = tensor.pow(p.get_plain_text()) else: reference = tensor.pow(p) encrypted_out = encrypted_tensor.pos_pow(p) self._check(encrypted_out, reference, f"pos_pow failed with power {p}") def test_norm(self): """Tests p-norm""" for p in [1, 1.5, 2, 3, float("inf"), "fro"]: for dim in [None, 0, 1, 2]: tensor = self._get_random_test_tensor(size=(3, 3, 3), is_float=True) / 5 if dim is None: reference = tensor.norm(p=p) else: reference = tensor.norm(p=p, dim=dim) encrypted = MPCTensor(tensor) encrypted_out = encrypted.norm(p=p, dim=dim) self._check(encrypted_out, reference, f"{p}-norm failed", tolerance=0.5) def test_logistic(self): """Tests logistic functions (sigmoid, tanh)""" tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) encrypted_tensor = MPCTensor(tensor) cases = ["sigmoid", "tanh"] for func in cases: reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) def test_hardtanh(self): tensor = torch.arange(-10, 10, dtype=torch.float32) encrypted = MPCTensor(tensor) for minval in range(-10, 10): for maxval in range(minval, 11): reference = torch.nn.functional.hardtanh(tensor, minval, maxval) encrypted_out = encrypted.hardtanh(minval, maxval) self._check(encrypted_out, reference, "hardtanh failed") def test_inplace_warning(self): """Tests that a warning is thrown that indicates that the `inplace` kwarg is ignored when a function is called with `inplace=True` """ tensor = get_random_test_tensor(is_float=True) encrypted = MPCTensor(tensor) functions = ["dropout", "_feature_dropout"] for func in functions: warning_str = ( f"CrypTen {func} does not support inplace computation during training." ) with self.assertLogs(logger=logging.getLogger(), level="WARNING") as cm: getattr(encrypted, func)(inplace=True) self.assertTrue(f"WARNING:root:{warning_str}" in cm.output) def test_cos_sin(self): """Tests trigonometric functions (cos, sin)""" tensor = torch.tensor( [0.01 * i for i in range(-1000, 1001, 1)], device=self.device ) encrypted_tensor = MPCTensor(tensor) cases = ["cos", "sin"] for func in cases: reference = getattr(tensor, func)() encrypted_out = getattr(encrypted_tensor, func)() self._check(encrypted_out, reference, "%s failed" % func) def test_softmax(self): """Test softmax and log_softmax function""" for softmax_fn in ["softmax", "log_softmax"]: # Test 0-dim tensor: tensor = self._get_random_test_tensor(size=(), is_float=True) reference = getattr(tensor, softmax_fn)(0) encrypted_tensor = MPCTensor(tensor) encrypted_out = getattr(encrypted_tensor, softmax_fn)(0) self._check(encrypted_out, reference, "0-dim tensor %s failed" % softmax_fn) # Test all other sizes sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 1), (5, 5), (1, 5, 5), (5, 1, 5), (5, 5, 1), (5, 5, 5), (1, 5, 5, 5), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) / 5 encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): reference = getattr(tensor, softmax_fn)(dim) encrypted_out = getattr(encrypted_tensor, softmax_fn)(dim) self._check(encrypted_out, reference, "%s failed" % softmax_fn) def test_get_set(self): """Tests element setting and getting by index""" for tensor_type in [lambda x: x, MPCTensor]: for size in range(1, 5): # Test __getitem__ tensor = self._get_random_test_tensor(size=(size, size), is_float=True) reference = tensor[:, 0] encrypted_tensor = MPCTensor(tensor) encrypted_out = encrypted_tensor[:, 0] self._check(encrypted_out, reference, "getitem failed") reference = tensor[0, :] encrypted_out = encrypted_tensor[0, :] self._check(encrypted_out, reference, "getitem failed") # Test __setitem__ tensor2 = self._get_random_test_tensor(size=(size,), is_float=True) reference = tensor.clone() reference[:, 0] = tensor2 encrypted_out = MPCTensor(tensor) encrypted2 = tensor_type(tensor2) encrypted_out[:, 0] = encrypted2 self._check( encrypted_out, reference, "%s setitem failed" % type(encrypted2) ) reference = tensor.clone() reference[0, :] = tensor2 encrypted_out = MPCTensor(tensor) encrypted2 = tensor_type(tensor2) encrypted_out[0, :] = encrypted2 self._check( encrypted_out, reference, "%s setitem failed" % type(encrypted2) ) def test_pad(self): """Tests padding""" sizes = [(1,), (5,), (1, 1), (5, 5), (5, 5, 5), (5, 3, 32, 32)] pads = [ (0, 0, 0, 0), (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1), (1, 1, 1, 1), (2, 2, 1, 1), (2, 2, 2, 2), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for pad in pads: for value in [0, 1, 10]: if tensor.dim() < 2: pad = pad[:2] reference = torch.nn.functional.pad(tensor, pad, value=value) encrypted_value = MPCTensor(value, device=self.device) encrypted_out = encrypted_tensor.pad(pad, value=encrypted_value) encrypted_out2 = encrypted_tensor.pad(pad, value=value) self._check(encrypted_out, reference, "pad failed") self._check(encrypted_out2, reference, "pad failed") def test_index_add(self): """Test index_add function of encrypted tensor""" index_add_functions = ["index_add", "index_add_"] tensor_size1 = [5, 5, 5, 5] index = torch.tensor( [1, 2, 3, 4, 4, 2, 1, 3], dtype=torch.long, device=self.device ) for dimension in range(0, 4): tensor_size2 = [5, 5, 5, 5] tensor_size2[dimension] = index.size(0) for func in index_add_functions: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor( size=tensor_size1, is_float=True ) tensor2 = self._get_random_test_tensor( size=tensor_size2, is_float=True ) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(dimension, index, tensor2) encrypted_out = getattr(encrypted, func)( dimension, index, encrypted2 ) private_type = tensor_type == MPCTensor self._check( encrypted_out, reference, "%s %s failed" % ("private" if private_type else "public", func), ) if func.endswith("_"): # Check in-place index_add worked self._check( encrypted, reference, "%s %s failed" % ("private" if private_type else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ( "private" if tensor_type == MPCTensor else "public", func, ), ) def test_scatter(self): """Test scatter/scatter_add function of encrypted tensor""" funcs = ["scatter", "scatter_", "scatter_add", "scatter_add_"] sizes = [(5, 5), (5, 5, 5), (5, 5, 5, 5)] for func in funcs: for size in sizes: for tensor_type in [lambda x: x, MPCTensor]: for dim in range(len(size)): tensor1 = self._get_random_test_tensor(size=size, is_float=True) tensor2 = self._get_random_test_tensor(size=size, is_float=True) index = self._get_random_test_tensor(size=size, is_float=False) index = index.abs().clamp(0, 4) encrypted = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(dim, index, tensor2) encrypted_out = getattr(encrypted, func)(dim, index, encrypted2) private = tensor_type == MPCTensor self._check( encrypted_out, reference, "%s %s failed" % ("private" if private else "public", func), ) if func.endswith("_"): # Check in-place scatter/scatter_add worked self._check( encrypted, reference, "%s %s failed" % ("private" if private else "public", func), ) else: # Check original is not modified self._check( encrypted, tensor1, "%s %s failed" % ("private" if private else "public", func), ) def test_broadcast_arithmetic_ops(self): """Test broadcast of arithmetic functions.""" arithmetic_functions = ["add", "sub", "mul", "div"] # TODO: Add broadcasting for pos_pow since it can take a tensor argument arithmetic_sizes = [ (), (1,), (2,), (1, 1), (1, 2), (2, 1), (2, 2), (1, 1, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 2, 2), (1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (2, 1, 1, 1), (2, 2, 2, 2), ] for tensor_type in [lambda x: x, MPCTensor]: for func in arithmetic_functions: for size1, size2 in itertools.combinations(arithmetic_sizes, 2): exclude_zero = True if func == "div" else False # multiply denominator by 10 to avoid dividing by small num const = 10 if func == "div" else 1 tensor1 = self._get_random_test_tensor(size=size1, is_float=True) tensor2 = self._get_random_test_tensor( size=size2, is_float=True, ex_zero=exclude_zero ) tensor2 *= const encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = getattr(tensor1, func)(tensor2) encrypted_out = getattr(encrypted1, func)(encrypted2) private = isinstance(encrypted2, MPCTensor) self._check( encrypted_out, reference, "%s %s broadcast failed" % ("private" if private else "public", func), ) # Test with integer tensor tensor2 = self._get_random_test_tensor( size=size2, is_float=False, ex_zero=exclude_zero ) tensor2 *= const reference = getattr(tensor1, func)(tensor2.float()) encrypted_out = getattr(encrypted1, func)(tensor2) self._check( encrypted_out, reference, "%s broadcast failed with public integer tensor" % func, ) def test_broadcast_matmul(self): """Test broadcast of matmul.""" matmul_sizes = [(1, 1), (1, 5), (5, 1), (5, 5)] batch_dims = [(), (1,), (5,), (1, 1), (1, 5), (5, 5)] for tensor_type in [lambda x: x, MPCTensor]: for size in matmul_sizes: for batch1, batch2 in itertools.combinations(batch_dims, 2): size1 = (*batch1, *size) size2 = (*batch2, *size) tensor1 = self._get_random_test_tensor(size=size1, is_float=True) tensor2 = self._get_random_test_tensor(size=size2, is_float=True) tensor2 = tensor2.transpose(-2, -1) encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) reference = tensor1.matmul(tensor2) encrypted_out = encrypted1.matmul(encrypted2) private = isinstance(encrypted2, MPCTensor) self._check( encrypted_out, reference, "%s matmul broadcast failed" % ("private" if private else "public"), ) # Test with integer tensor tensor2 = self._get_random_test_tensor(size=size2, is_float=False) tensor2 = tensor2.float().transpose(-2, -1) reference = tensor1.matmul(tensor2) encrypted_out = encrypted1.matmul(tensor2) self._check( encrypted_out, reference, "matmul broadcast failed with public integer tensor", ) def test_inplace(self): """Test inplace vs. out-of-place functions""" for op in ["add", "sub", "mul", "div"]: for tensor_type in [lambda x: x, MPCTensor]: tensor1 = self._get_random_test_tensor(is_float=True) tensor2 = self._get_random_test_tensor(is_float=True) reference = getattr(torch, op)(tensor1, tensor2) encrypted1 = MPCTensor(tensor1) encrypted2 = tensor_type(tensor2) input_tensor_id = id(encrypted1._tensor) input_encrypted_id = id(encrypted1) # Test that out-of-place functions do not modify the input private = isinstance(encrypted2, MPCTensor) encrypted_out = getattr(encrypted1, op)(encrypted2) self._check( encrypted1, tensor1, "%s out-of-place %s modifies input" % ("private" if private else "public", op), ) self._check( encrypted_out, reference, "%s out-of-place %s produces incorrect output" % ("private" if private else "public", op), ) self.assertFalse(id(encrypted_out._tensor) == input_tensor_id) self.assertFalse(id(encrypted_out) == input_encrypted_id) # Test that in-place functions modify the input encrypted_out = getattr(encrypted1, op + "_")(encrypted2) self._check( encrypted1, reference, "%s in-place %s_ does not modify input" % ("private" if private else "public", op), ) self._check( encrypted_out, reference, "%s in-place %s_ produces incorrect output" % ("private" if private else "public", op), ) self.assertTrue(id(encrypted_out._tensor) == input_tensor_id) self.assertTrue(id(encrypted_out) == input_encrypted_id) def test_copy_clone(self): """Tests shallow_copy and clone of encrypted tensors.""" sizes = [(5,), (1, 5), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) # test shallow_copy encrypted_tensor_shallow = encrypted_tensor.shallow_copy() self.assertEqual( id(encrypted_tensor_shallow._tensor), id(encrypted_tensor._tensor) ) self._check(encrypted_tensor_shallow, tensor, "shallow_copy failed") # test clone encrypted_tensor_clone = encrypted_tensor.clone() self.assertNotEqual( id(encrypted_tensor_clone._tensor), id(encrypted_tensor._tensor) ) self._check(encrypted_tensor_clone, tensor, "clone failed") def test_copy_(self): """Tests copy_ function.""" sizes = [(5,), (1, 5), (5, 10, 15)] for size in sizes: tensor1 = self._get_random_test_tensor(size=size, is_float=True) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor1 = MPCTensor(tensor1) encrypted_tensor2 = MPCTensor(tensor2) encrypted_tensor1.copy_(encrypted_tensor2) self._check(encrypted_tensor1, tensor2, "copy_ failed") def test_index_select(self): """Tests index_select of encrypted tensors.""" sizes = [(5,), (5, 10), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) indices = [[0], [0, 3], [0, 2, 4]] for dim in range(tensor.dim()): for index in indices: index_tensor = torch.tensor( index, dtype=torch.long, device=self.device ) reference = tensor.index_select(dim, index_tensor) encrypted_out = encrypted_tensor.index_select(dim, index_tensor) self._check( encrypted_out, reference, "index_select failed at dim {dim} and index {index}", ) def test_narrow(self): """Tests narrow function.""" sizes = [(5, 6), (5, 6, 7), (6, 7, 8, 9)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encr_tensor = MPCTensor(tensor) for dim in range(len(size)): for start in range(size[dim] - 2): for length in range(1, size[dim] - start): tensor_narrow = tensor.narrow(dim, start, length) encr_tensor_narrow = encr_tensor.narrow(dim, start, length) self._check( encr_tensor_narrow, tensor_narrow, "narrow failed along dimension %d" % dim, ) def test_repeat_expand(self): """Tests repeat and expand of encrypted tensors.""" sizes = [(1, 8), (4, 1, 8)] repeat_dims = [(4, 2, 1), (4, 2, 10)] expand_dims = [(4, 2, 8), (4, 5, 8), (10, 4, 5, 8)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dims in repeat_dims: encrypted_tensor_repeated = encrypted_tensor.repeat(*dims) # test that repeat copies tensor's data self.assertNotEqual( id(encrypted_tensor_repeated._tensor), id(encrypted_tensor._tensor) ) self._check( encrypted_tensor_repeated, tensor.repeat(*dims), f"repeat failed with dims {dims}", ) for dims in expand_dims: encrypted_tensor_expanded = encrypted_tensor.expand(*dims) # test that expand creates a view into the same underlying tensor self.assertNotEqual( id(encrypted_tensor_expanded.share), id(encrypted_tensor.share) ) self._check( encrypted_tensor_expanded, tensor.expand(*dims), f"repeat failed with dims {dims}", ) def test_view_flatten(self): """Tests view and flatten of encrypted tensors.""" sizes = [(100,), (4, 25), (2, 5, 10)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): self._check( encrypted_tensor.flatten(start_dim=dim), tensor.flatten(start_dim=dim), f"flatten failed with dim {dim}", ) shapes = [100, (5, 20), (10, 2, 5), (-1, 10)] for shape in shapes: self._check( encrypted_tensor.view(shape), tensor.view(shape), f"view failed with shape {shape}", ) def test_roll(self): """Tests roll of encrypted tensors.""" sizes = [(10, 1), (5, 2), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) roll_shifts = [1, 2, 3, (2, 1)] roll_dims = [0, 1, 0, (0, 1)] for shifts, dims in zip(roll_shifts, roll_dims): encrypted_tensor_rolled = encrypted_tensor.roll(shifts, dims=dims) self.assertEqual(encrypted_tensor_rolled.numel(), tensor.numel()) self._check( encrypted_tensor_rolled, tensor.roll(shifts, dims=dims), f"roll failed with shift {shifts} and dims {dims}", ) def test_unfold(self): """Tests unfold of encrypted tensors.""" tensor_sizes = [(8,), (15, 10, 5), (5, 10, 15, 20)] for tensor_size in tensor_sizes: tensor = self._get_random_test_tensor(size=tensor_size, is_float=True) encrypted_tensor = MPCTensor(tensor) for size, step in itertools.product(range(1, 4), range(1, 4)): # check unfold along higher dimension if possible for dim in range(tensor.dim()): self._check( encrypted_tensor.unfold(dim, size, step), tensor.unfold(dim, size, step), "unfold failed with dim " f"{dim}, size {size}, and step {step}", ) def test_to(self): """Tests Arithemetic/Binary SharedTensor type conversions.""" from crypten.mpc.ptype import ptype as Ptype tensor_sizes = [(), (1,), (5,), (1, 1), (5, 5), (1, 1, 1), (5, 5, 5)] for size in tensor_sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) binary_encrypted_tensor = encrypted_tensor.to(Ptype.binary) self.assertEqual(binary_encrypted_tensor.ptype, Ptype.binary) # check original encrypted_tensor was not modified after conversion self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to BinarySharedTensor.", ) encrypted_from_binary = binary_encrypted_tensor.to(Ptype.arithmetic) self._check( encrypted_from_binary, tensor, "to failed from BinarySharedTensor to ArithmeticSharedTensor", ) # Test API tensor = self._get_random_test_tensor(size=(5,), is_float=True) encrypted_tensor = MPCTensor(tensor) if torch.cuda.is_available(): encrypted_tensor = encrypted_tensor.to("cuda") self.assertEqual(encrypted_tensor.device.type, "cuda") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cuda", ) encrypted_tensor = encrypted_tensor.to(device="cuda") self.assertEqual(encrypted_tensor.device.type, "cuda") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cuda", ) encrypted_tensor = encrypted_tensor.to("cpu") self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cpu", ) encrypted_tensor = encrypted_tensor.to(device="cpu") self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to cpu", ) encrypted_tensor = encrypted_tensor.to(ptype=Ptype.binary) self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.binary) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to BinarySharedTensor.", ) encrypted_tensor = encrypted_tensor.to(ptype=Ptype.arithmetic) self.assertEqual(encrypted_tensor.device.type, "cpu") self.assertEqual(encrypted_tensor.ptype, Ptype.arithmetic) self._check( encrypted_tensor, tensor, "encrypted_tensor was modified during conversion to ArithmeticSharedTensor.", ) def test_cumsum(self): """Tests cumulative sum on encrypted tensors.""" sizes = [(8,), (5, 10), (15, 10, 5)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) for dim in range(tensor.dim()): self._check( encrypted_tensor.cumsum(dim), tensor.cumsum(dim), f"cumsum failed along {dim} dim", ) def test_trace(self): """Tests trace operation on 2D encrypted tensors.""" sizes = [(3, 3), (10, 10), (2, 3)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) self._check(encrypted_tensor.trace(), tensor.trace(), "trace failed") def test_flip(self): """Tests flip operation on encrypted tensors.""" sizes = [(5,), (5, 10), (5, 10, 15)] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor = MPCTensor(tensor) flip_dims = [(0,), (0, 1), (0, 1, 2)] for dims in flip_dims: if len(dims) <= tensor.dim(): self._check( encrypted_tensor.flip(dims), tensor.flip(dims), f"flip failed with {dims} dims", ) def test_control_flow_failure(self): """Tests that control flow fails as expected""" tensor = self._get_random_test_tensor(is_float=True) encrypted_tensor = MPCTensor(tensor) with self.assertRaises(RuntimeError): if encrypted_tensor: pass with self.assertRaises(RuntimeError): tensor = 5 if encrypted_tensor else 0 with self.assertRaises(RuntimeError): if False: pass elif encrypted_tensor: pass def test_where(self): """Tests where() conditional element selection""" sizes = [(10,), (5, 10), (1, 5, 10)] y_types = [lambda x: x, MPCTensor] for size, y_type in itertools.product(sizes, y_types): tensor1 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor1 = MPCTensor(tensor1) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted_tensor2 = y_type(tensor2) condition_tensor = ( self._get_random_test_tensor(max_value=1, size=size, is_float=False) + 1 ) condition_encrypted = MPCTensor(condition_tensor) condition_bool = condition_tensor.bool() reference_out = tensor1.where(condition_bool, tensor2) encrypted_out = encrypted_tensor1.where(condition_bool, encrypted_tensor2) y_is_private = y_type == MPCTensor self._check( encrypted_out, reference_out, f"{'private' if y_is_private else 'public'} y " "where failed with public condition", ) encrypted_out = encrypted_tensor1.where( condition_encrypted, encrypted_tensor2 ) self._check( encrypted_out, reference_out, f"{'private' if y_is_private else 'public'} y " "where failed with private condition", ) # test scalar y scalar = self._get_random_test_tensor(max_value=0, size=[1], is_float=True) self._check( encrypted_tensor1.where(condition_bool, scalar), tensor1.where(condition_bool, scalar), "where failed against scalar y with public condition", ) self._check( encrypted_tensor1.where(condition_encrypted, scalar), tensor1.where(condition_bool, scalar), "where failed against scalar y with private condition", ) def test_unbind(self): """Tests unbind""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted = MPCTensor(tensor) for dim in range(tensor.dim()): reference = tensor.unbind(dim) encrypted_out = encrypted.unbind(dim) self._check_tuple(encrypted_out, reference, "unbind failed") def test_split(self): """Tests split""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, is_float=True) encrypted = MPCTensor(tensor) for dim in range(tensor.dim()): # Get random split split = self._get_random_test_tensor( size=(), max_value=tensor.size(dim) ) split = split.abs().clamp(0, tensor.size(dim) - 1) split = split.item() # Test int split int_split = 1 if split == 0 else split reference = tensor.split(int_split, dim=dim) encrypted_out = encrypted.split(int_split, dim=dim) self._check_tuple(encrypted_out, reference, "split failed") # Test list split split = [split, tensor.size(dim) - split] reference = tensor.split(split, dim=dim) encrypted_out = encrypted.split(split, dim=dim) self._check_tuple(encrypted_out, reference, "split failed") def test_set(self): """Tests set correctly re-assigns encrypted shares""" sizes = [(1, 5), (5, 10), (15, 10, 5)] for size in sizes: tensor1 = self._get_random_test_tensor(size=size, is_float=True) encrypted1 = MPCTensor(tensor1) tensor2 = self._get_random_test_tensor(size=size, is_float=True) encrypted2 = MPCTensor(tensor2) # check encrypted set encrypted1.set(encrypted2) self._check( encrypted1, tensor2, f"set with encrypted other failed with size {size}" ) # check plain text set encrypted1 = MPCTensor(tensor1) encrypted1.set(tensor2) self._check( encrypted1, tensor2, f"set with unencrypted other failed with size {size}", ) def test_polynomial(self): """Tests polynomial function""" sizes = [ (1,), (5,), (1, 1), (1, 5), (5, 5), (1, 1, 1), (5, 5, 5), (1, 1, 1, 1), (5, 5, 5, 5), ] for size in sizes: tensor = self._get_random_test_tensor(size=size, max_value=3, is_float=True) encrypted = MPCTensor(tensor) for terms in range(1, 5): coeffs = self._get_random_test_tensor( size=(terms,), max_value=3, is_float=True ) reference = torch.zeros(size=tensor.size(), device=self.device) for i, term in enumerate(coeffs.tolist()): reference += term * tensor.pow(i + 1) # Test list coeffs encrypted_out = encrypted.polynomial(coeffs.tolist()) self._check(encrypted_out, reference, "polynomial failed") # Test plaintext tensor coeffs encrypted_out = encrypted.polynomial(coeffs) self._check(encrypted_out, reference, "polynomial failed") # Test encrypted tensor coeffs coeffs_enc = MPCTensor(coeffs) encrypted_out = encrypted.polynomial(coeffs_enc) self._check(encrypted_out, reference, "polynomial failed") def test_gather(self): """Test gather function of encrypted tensor""" sizes = [(5, 5), (5, 5, 5), (5, 5, 5, 5)] for size in sizes: for dim in range(len(size)): tensor = self._get_random_test_tensor(size=size, is_float=True) index = self._get_random_test_tensor(size=size, is_float=False) index = index.abs().clamp(0, 4) encrypted = MPCTensor(tensor) reference = tensor.gather(dim, index) encrypted_out = encrypted.gather(dim, index) self._check(encrypted_out, reference, f"gather failed with size {size}") def test_dropout(self): """ Tests the dropout functions. Directly compares the zero and non-zero entries of the input tensor, since we cannot force the encrypted and unencrypted versions to generate identical random output. Also confirms that the number of zeros in the encrypted dropout function is as expected. """ all_prob_values = [x * 0.2 for x in range(5)] def get_first_nonzero_value(x): x = x.flatten() x = x[x.abs().ge(1e-4)] x = x.take(torch.tensor(0)) return x # check that the encrypted and plaintext versions scale # identically, by testing on all-ones tensor for prob in all_prob_values: tensor = torch.ones([10, 10, 10], device=self.device).float() encr_tensor = MPCTensor(tensor) dropout_encr = encr_tensor.dropout(prob, training=True) dropout_decr = dropout_encr.get_plain_text() dropout_plain = F.dropout(tensor, prob, training=True) # All non-zero values should be identical in both tensors, so # compare any one of them decr_nonzero_value = get_first_nonzero_value(dropout_decr) plaintext_nonzero_value = get_first_nonzero_value(dropout_plain) self.assertTrue( math.isclose( decr_nonzero_value, plaintext_nonzero_value, rel_tol=1e-2, abs_tol=1e-2, ) ) for dropout_fn in ["dropout", "_feature_dropout"]: for prob in all_prob_values: for size in [(5, 10), (5, 10, 15), (5, 10, 15, 20)]: for inplace in [False, True]: for training in [False, True]: tensor = self._get_random_test_tensor( size=size, ex_zero=True, min_value=1.0, is_float=True ) encr_tensor = MPCTensor(tensor) dropout_encr = getattr(encr_tensor, dropout_fn)( prob, inplace=inplace, training=training ) if training: # Check the scaling for non-zero elements dropout_decr = dropout_encr.get_plain_text() scaled_tensor = tensor / (1 - prob) reference = dropout_decr.where( dropout_decr == 0, scaled_tensor ) else: reference = tensor self._check( dropout_encr, reference, f"dropout failed with size {size} and probability " f"{prob}", ) if inplace: self._check( encr_tensor, reference, f"in-place dropout failed with size {size} and " f"probability {prob}", ) else: self._check( encr_tensor, tensor, "out-of-place dropout modifies input", ) # Check that channels that are zeroed are all zeros if dropout_fn in [ "dropout2d", "dropout3d", "feature_dropout", ]: dropout_encr_flat = dropout_encr.flatten( start_dim=0, end_dim=1 ) dropout_flat = dropout_encr_flat.get_plain_text() for i in range(0, dropout_flat.size(0)): all_zeros = (dropout_flat[i] == 0).all() all_nonzeros = (dropout_flat[i] != 0).all() self.assertTrue( all_zeros or all_nonzeros, f"{dropout_fn} failed for size {size} with " f"training {training} and inplace {inplace}", ) # Check the expected number of zero elements # For speed, restrict test to single p = 0.4 encr_tensor = MPCTensor(torch.empty((int(1e5), 2, 2)).fill_(1).to(self.device)) dropout_encr = encr_tensor.dropout(0.4) dropout_tensor = dropout_encr.get_plain_text() frac_zero = float((dropout_tensor == 0).sum()) / dropout_tensor.nelement() self.assertTrue(math.isclose(frac_zero, 0.4, rel_tol=1e-2, abs_tol=1e-2)) def test_tuple_cache(self): # Skip RSS setting since it does not generate tuples if cfg.mpc.protocol == "replicated": return # TODO: encorporate wrap_rng for 3PC+ settings if comm.get().get_world_size() > 2: return provider = crypten.mpc.get_default_provider() # Test tracing attribute crypten.trace() self.assertTrue(provider.tracing) x = get_random_test_tensor(is_float=True) x = crypten.cryptensor(x) _ = x.square() _ = x * x _ = x.matmul(x.t()) _ = x.relu() y = x.unsqueeze(0) _ = y.conv1d(y, stride=2) # Populate reference requests ref_names = ["square"] ref_names += ["generate_additive_triple"] * 2 ref_names += ["generate_binary_triple"] * 7 + ["B2A_rng"] ref_names += ["generate_additive_triple"] * 2 ref_args = [ (torch.Size([1, 5]),), (torch.Size([1, 5]), torch.Size([1, 5]), "mul"), (torch.Size([1, 5]), torch.Size([5, 1]), "matmul"), (torch.Size([1, 1, 5]), torch.Size([1, 1, 5])), ] ref_args += [(torch.Size([2, 1, 1, 5]), torch.Size([2, 1, 1, 5]))] * 6 ref_args += [(torch.Size([1, 5]),)] ref_args += [(torch.Size([1, 5]), torch.Size([1, 5]), "mul")] ref_args += [(torch.Size([1, 1, 5]), torch.Size([1, 1, 5]), "conv1d")] kwargs = {"device": torch.device("cpu")} conv_kwargs = {"device": torch.device("cpu"), "stride": 2} requests = [(ref_names[i], ref_args[i], kwargs) for i in range(12)] requests += [(ref_names[12], ref_args[12], conv_kwargs)] self.assertEqual( provider.request_cache, requests, "TupleProvider request cache incorrect", ) crypten.trace(False) self.assertFalse(provider.tracing) # Check that cache populates as expected crypten.fill_cache() kwargs = frozenset(kwargs.items()) conv_kwargs = frozenset(conv_kwargs.items()) keys = [(ref_names[i], ref_args[i], kwargs) for i in range(12)] keys += [(ref_names[12], ref_args[12], conv_kwargs)] self.assertEqual( set(provider.tuple_cache.keys()), set(keys), "TupleProvider tuple_cache populated incorrectly", ) # Test that function calls return from cache when trace is off crypten.trace(False) _ = x.square() _ = x * x _ = x.matmul(x.t()) _ = x.relu() y = x.unsqueeze(0) _ = y.conv1d(y, stride=2) for v in provider.tuple_cache.values(): self.assertEqual( len(v), 0, msg="TupleProvider is not popping tuples properly from cache" ) # Run all unit tests with both TFP and TTP providers class TestTFP(MultiProcessTestCase, TestMPC): def setUp(self): self._original_provider = cfg.mpc.provider crypten.CrypTensor.set_grad_enabled(False) cfg.mpc.provider = "TFP" super(TestTFP, self).setUp() def tearDown(self): cfg.mpc.provider = self._original_provider crypten.CrypTensor.set_grad_enabled(True) super(TestTFP, self).tearDown() class TestTTP(MultiProcessTestCase, TestMPC): def setUp(self): self._original_provider = cfg.mpc.provider crypten.CrypTensor.set_grad_enabled(False) cfg.mpc.provider = "TTP" super(TestTTP, self).setUp() def tearDown(self): cfg.mpc.provider = self._original_provider crypten.CrypTensor.set_grad_enabled(True) super(TestTTP, self).tearDown() class Test3PC(MultiProcessTestCase, TestMPC): def setUp(self): super(Test3PC, self).setUp(world_size=3) class TestRSS(MultiProcessTestCase, TestMPC): def setUp(self): self._original_protocol = cfg.mpc.protocol cfg.mpc.protocol = "replicated" super(TestRSS, self).setUp(world_size=3) def tearDown(self): cfg.mpc.protocol = self._original_protocol super(TestRSS, self).tearDown() # This code only runs when executing the file outside the test harness (e.g. # via the buck target of another test) if __name__ == "__main__": unittest.main()
en
0.819829
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. This class tests all functions of MPCTensor. # Check sizes match # Make sure these don't crash Tests MPCTensor.from_shares() functionality. # settings for test: # generate arithmetic sharing of reference tensor: # generate binary sharing of reference tensor: # return shares and reference: # test both types: # generate shares, sync them between parties, and create tensor: # check resulting tensor: Tests share attribute getter and setter Tests tensor encryption and decryption for both positive and negative values. # encryption and decryption without source: # test creation via new() function: # TODO: Implement broadcast_size on GPU # encryption and decryption with source: # MPCTensors cannot be initialized with None: Tests arithmetic functions on encrypted tensor. # Check in-place op worked # Check original is not modified # Check encrypted vector with encrypted scalar works. # Test radd, rsub, and rmul Tests sum reduction on encrypted tensor. Tests prod reduction on encrypted tensor. Test that ptype attribute creates the correct type of encrypted tensor Tests division of encrypted tensor by scalar and tensor. # multiply denominator by 10 to avoid dividing by small num Tests computing means of encrypted tensors. Tests computing variances of encrypted tensors. Test matrix multiplication. Test dot product of vector and encrypted tensor. # dot # ger # Test unsqueeze # Test squeeze # Check that the encrypted_out and encrypted point to the same # thing. # t() asserts dim == 2 Test convolution of encrypted tensor with public/private tensors. # group convolution is not supported on GPU Test convolution of encrypted tensor with public/private tensors. # group convolution is not supported on GPU # sample input: # sample filtering kernel: # perform filtering: # check that result is correct: Test max_pool of encrypted tensor. # Assert each kernel is one-hot # Populate tensor with kernel indices # Ensure encrypted indices are correct # Skip kernels that lead to 0-size outputs Test avg_pool of encrypted tensor. test adaptive_avg_pool2d and adaptive_max_pool2d # Test adaptive_avg_pool2d # Test adapvite_max_pool2d Tests take function on encrypted tensor # Test when dimension!=None # Test when dimension is default (i.e. None) Test negative on encrypted tensor. Test relu on encrypted tensor. # Generate some negative values Test comparators (>, >=, <, <=, ==, !=) # Check deterministic example to guarantee all combinations Tests max and min for the deterministic constant (n^2) algorithm Tests max and min for log reduction algorithm Tests max and min for double log reduction algorithm Tests max and min for accelerated cascading algorithm Test max and min for the specified algorithm # Test with one_hot = False # Check max / min values are correct # Test argmax / argmin values are correct # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. # Test indices with one_hot = True # Check argmax results Tests argmax and argmin for the deterministic constant (n^2) algorithm Tests argmax and argmin for log reduction algorithm Tests argmax and argmin for double log reduction algorithm Tests max and min for accelerated cascading algorithm Test argmax and argmin for specified algorithm # test with one_hot = False # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value. # if input is 0-d, argmax should be 0 # test with one_hot = False # Compute one-hot argmax/min reference in plaintext # test with one_hot = False # Must index into tensor since ties are broken randomly # so crypten and PyTorch can return different indices. # This checks that they index to the same value.abs # test with one_hot = True Test absolute value function # do not test on 0 since torch.tensor([0]).sign() = 0 Test appoximate functions (exp, log, sqrt, reciprocal, pos_pow) # Test on [-10, 10] range # Test on [0, 10] range # Test on [0, 10] range # Test pos_pow with several exponents # Reduced the max_value so approximations have less absolute error Tests p-norm Tests logistic functions (sigmoid, tanh) Tests that a warning is thrown that indicates that the `inplace` kwarg is ignored when a function is called with `inplace=True` Tests trigonometric functions (cos, sin) Test softmax and log_softmax function # Test 0-dim tensor: # Test all other sizes Tests element setting and getting by index # Test __getitem__ # Test __setitem__ Tests padding Test index_add function of encrypted tensor # Check in-place index_add worked # Check original is not modified Test scatter/scatter_add function of encrypted tensor # Check in-place scatter/scatter_add worked # Check original is not modified Test broadcast of arithmetic functions. # TODO: Add broadcasting for pos_pow since it can take a tensor argument # multiply denominator by 10 to avoid dividing by small num # Test with integer tensor Test broadcast of matmul. # Test with integer tensor Test inplace vs. out-of-place functions # Test that out-of-place functions do not modify the input # Test that in-place functions modify the input Tests shallow_copy and clone of encrypted tensors. # test shallow_copy # test clone Tests copy_ function. Tests index_select of encrypted tensors. Tests narrow function. Tests repeat and expand of encrypted tensors. # test that repeat copies tensor's data # test that expand creates a view into the same underlying tensor Tests view and flatten of encrypted tensors. Tests roll of encrypted tensors. Tests unfold of encrypted tensors. # check unfold along higher dimension if possible Tests Arithemetic/Binary SharedTensor type conversions. # check original encrypted_tensor was not modified after conversion # Test API Tests cumulative sum on encrypted tensors. Tests trace operation on 2D encrypted tensors. Tests flip operation on encrypted tensors. Tests that control flow fails as expected Tests where() conditional element selection # test scalar y Tests unbind Tests split # Get random split # Test int split # Test list split Tests set correctly re-assigns encrypted shares # check encrypted set # check plain text set Tests polynomial function # Test list coeffs # Test plaintext tensor coeffs # Test encrypted tensor coeffs Test gather function of encrypted tensor Tests the dropout functions. Directly compares the zero and non-zero entries of the input tensor, since we cannot force the encrypted and unencrypted versions to generate identical random output. Also confirms that the number of zeros in the encrypted dropout function is as expected. # check that the encrypted and plaintext versions scale # identically, by testing on all-ones tensor # All non-zero values should be identical in both tensors, so # compare any one of them # Check the scaling for non-zero elements # Check that channels that are zeroed are all zeros # Check the expected number of zero elements # For speed, restrict test to single p = 0.4 # Skip RSS setting since it does not generate tuples # TODO: encorporate wrap_rng for 3PC+ settings # Test tracing attribute # Populate reference requests # Check that cache populates as expected # Test that function calls return from cache when trace is off # Run all unit tests with both TFP and TTP providers # This code only runs when executing the file outside the test harness (e.g. # via the buck target of another test)
2.069287
2
src/python/turicreate/__init__.py
rplom/turicreate
1
6630461
<filename>src/python/turicreate/__init__.py # -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause ''' @package turicreate ... Turi Create is a machine learning platform that enables data scientists and app developers to easily create intelligent applications at scale. ''' from __future__ import print_function as _ from __future__ import division as _ from __future__ import absolute_import as _ from ._deps import LazyModuleLoader as _LazyModuleLoader from ._deps import LazyCallable as _LazyCallable __version__ = '{{VERSION_STRING}}' from turicreate.version_info import __version__ from turicreate.toolkits import evaluation # expose name aggregate as global variable # this won't interfere with import turicreate.aggregate as agg aggregate = _LazyModuleLoader('turicreate.aggregate') toolkits = _LazyModuleLoader('turicreate.toolkits') # must load from turicreate.data_structures.sgraph import Vertex, Edge from turicreate.data_structures.sgraph import SGraph from turicreate.data_structures.sarray import SArray from turicreate.data_structures.sframe import SFrame from turicreate.data_structures.sketch import Sketch from turicreate.data_structures.image import Image from .data_structures.sarray_builder import SArrayBuilder from .data_structures.sframe_builder import SFrameBuilder ## bring load functions to the top level from turicreate.data_structures.sgraph import load_sgraph from turicreate.data_structures.sframe import load_sframe from turicreate.data_structures.sarray import load_sarray # lazy import under leaf module level import turicreate.toolkits.clustering as clustering from turicreate.toolkits.clustering import kmeans from turicreate.toolkits.clustering import dbscan # lazy import under leaf module level import turicreate.toolkits.graph_analytics as graph_analytics from turicreate.toolkits.graph_analytics import connected_components from turicreate.toolkits.graph_analytics import shortest_path from turicreate.toolkits.graph_analytics import kcore from turicreate.toolkits.graph_analytics import pagerank from turicreate.toolkits.graph_analytics import graph_coloring from turicreate.toolkits.graph_analytics import triangle_counting from turicreate.toolkits.graph_analytics import degree_counting from turicreate.toolkits.graph_analytics import label_propagation # lazy import under leaf module level import turicreate.toolkits.recommender as recommender from turicreate.toolkits.recommender import popularity_recommender from turicreate.toolkits.recommender import item_similarity_recommender from turicreate.toolkits.recommender import ranking_factorization_recommender from turicreate.toolkits.recommender import item_content_recommender from turicreate.toolkits.recommender import factorization_recommender # lazy load under leaf node level import turicreate.toolkits.regression as regression from turicreate.toolkits.regression import boosted_trees_regression from turicreate.toolkits.regression import random_forest_regression from turicreate.toolkits.regression import decision_tree_regression from turicreate.toolkits.regression import linear_regression # lazy load under leaf node level import turicreate.toolkits.classifier as classifier from turicreate.toolkits.classifier import svm_classifier from turicreate.toolkits.classifier import logistic_classifier from turicreate.toolkits.classifier import boosted_trees_classifier from turicreate.toolkits.classifier import random_forest_classifier from turicreate.toolkits.classifier import decision_tree_classifier from turicreate.toolkits.classifier import nearest_neighbor_classifier # lazy load under leaf node level from turicreate.toolkits.image_analysis import image_analysis # self-encaps modules without from import statements # we can use top-level lazy import for them distances = _LazyModuleLoader('turicreate.toolkits.distances') nearest_neighbors = _LazyModuleLoader('turicreate.toolkits.nearest_neighbors') topci_model = _LazyModuleLoader('turicreate.toolkits.topci_model') text_analytics = _LazyModuleLoader('turicreate.toolkits.text_analytics') text_classifier = _LazyModuleLoader('turicreate.toolkits.text_classifier') image_classifier = _LazyModuleLoader('turicreate.toolkits.image_classifier') image_similarity = _LazyModuleLoader('turicreate.toolkits.image_similarity') object_detector = _LazyModuleLoader('turicreate.toolkits.object_detector') one_shot_object_detector = _LazyModuleLoader('turicreate.toolkits.one_shot_object_detector') style_transfer = _LazyModuleLoader('turicreate.toolkits.style_transfer') activity_classifier = _LazyModuleLoader('turicreate.toolkits.activity_classifier') drawing_classifier = _LazyModuleLoader('turicreate.toolkits.drawing_classifier') # modules that don't expose attributes from __init__.py sound_classifier = _LazyModuleLoader('turicreate.toolkits.sound_classifier.sound_classifier') audio_analysis = _LazyModuleLoader('turicreate.toolkits.audio_analysis.audio_analysis') # lazy callable load_images = _LazyCallable(image_analysis, 'load_images') load_audio = _LazyCallable(audio_analysis, 'load_audio') load_model = _LazyCallable(_LazyModuleLoader( 'turicreate.toolkits._model'), 'load_model') ################### Extension Importing ######################## import turicreate.extensions from turicreate.extensions import ext_import turicreate.extensions._add_meta_path() # rewrite the extensions module class _extensions_wrapper(object): def __init__(self, wrapped): self._wrapped = wrapped self.__doc__ = wrapped.__doc__ def __getattr__(self, name): try: return getattr(self._wrapped, name) except: pass turicreate._connect.main.get_unity() return getattr(self._wrapped, name) import sys as _sys _sys.modules["turicreate.extensions"] = _extensions_wrapper(_sys.modules["turicreate.extensions"]) # rewrite the import extensions = _sys.modules["turicreate.extensions"] from .visualization import plot, show # internal util from turicreate._connect.main import launch as _launch _launch()
<filename>src/python/turicreate/__init__.py # -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause ''' @package turicreate ... Turi Create is a machine learning platform that enables data scientists and app developers to easily create intelligent applications at scale. ''' from __future__ import print_function as _ from __future__ import division as _ from __future__ import absolute_import as _ from ._deps import LazyModuleLoader as _LazyModuleLoader from ._deps import LazyCallable as _LazyCallable __version__ = '{{VERSION_STRING}}' from turicreate.version_info import __version__ from turicreate.toolkits import evaluation # expose name aggregate as global variable # this won't interfere with import turicreate.aggregate as agg aggregate = _LazyModuleLoader('turicreate.aggregate') toolkits = _LazyModuleLoader('turicreate.toolkits') # must load from turicreate.data_structures.sgraph import Vertex, Edge from turicreate.data_structures.sgraph import SGraph from turicreate.data_structures.sarray import SArray from turicreate.data_structures.sframe import SFrame from turicreate.data_structures.sketch import Sketch from turicreate.data_structures.image import Image from .data_structures.sarray_builder import SArrayBuilder from .data_structures.sframe_builder import SFrameBuilder ## bring load functions to the top level from turicreate.data_structures.sgraph import load_sgraph from turicreate.data_structures.sframe import load_sframe from turicreate.data_structures.sarray import load_sarray # lazy import under leaf module level import turicreate.toolkits.clustering as clustering from turicreate.toolkits.clustering import kmeans from turicreate.toolkits.clustering import dbscan # lazy import under leaf module level import turicreate.toolkits.graph_analytics as graph_analytics from turicreate.toolkits.graph_analytics import connected_components from turicreate.toolkits.graph_analytics import shortest_path from turicreate.toolkits.graph_analytics import kcore from turicreate.toolkits.graph_analytics import pagerank from turicreate.toolkits.graph_analytics import graph_coloring from turicreate.toolkits.graph_analytics import triangle_counting from turicreate.toolkits.graph_analytics import degree_counting from turicreate.toolkits.graph_analytics import label_propagation # lazy import under leaf module level import turicreate.toolkits.recommender as recommender from turicreate.toolkits.recommender import popularity_recommender from turicreate.toolkits.recommender import item_similarity_recommender from turicreate.toolkits.recommender import ranking_factorization_recommender from turicreate.toolkits.recommender import item_content_recommender from turicreate.toolkits.recommender import factorization_recommender # lazy load under leaf node level import turicreate.toolkits.regression as regression from turicreate.toolkits.regression import boosted_trees_regression from turicreate.toolkits.regression import random_forest_regression from turicreate.toolkits.regression import decision_tree_regression from turicreate.toolkits.regression import linear_regression # lazy load under leaf node level import turicreate.toolkits.classifier as classifier from turicreate.toolkits.classifier import svm_classifier from turicreate.toolkits.classifier import logistic_classifier from turicreate.toolkits.classifier import boosted_trees_classifier from turicreate.toolkits.classifier import random_forest_classifier from turicreate.toolkits.classifier import decision_tree_classifier from turicreate.toolkits.classifier import nearest_neighbor_classifier # lazy load under leaf node level from turicreate.toolkits.image_analysis import image_analysis # self-encaps modules without from import statements # we can use top-level lazy import for them distances = _LazyModuleLoader('turicreate.toolkits.distances') nearest_neighbors = _LazyModuleLoader('turicreate.toolkits.nearest_neighbors') topci_model = _LazyModuleLoader('turicreate.toolkits.topci_model') text_analytics = _LazyModuleLoader('turicreate.toolkits.text_analytics') text_classifier = _LazyModuleLoader('turicreate.toolkits.text_classifier') image_classifier = _LazyModuleLoader('turicreate.toolkits.image_classifier') image_similarity = _LazyModuleLoader('turicreate.toolkits.image_similarity') object_detector = _LazyModuleLoader('turicreate.toolkits.object_detector') one_shot_object_detector = _LazyModuleLoader('turicreate.toolkits.one_shot_object_detector') style_transfer = _LazyModuleLoader('turicreate.toolkits.style_transfer') activity_classifier = _LazyModuleLoader('turicreate.toolkits.activity_classifier') drawing_classifier = _LazyModuleLoader('turicreate.toolkits.drawing_classifier') # modules that don't expose attributes from __init__.py sound_classifier = _LazyModuleLoader('turicreate.toolkits.sound_classifier.sound_classifier') audio_analysis = _LazyModuleLoader('turicreate.toolkits.audio_analysis.audio_analysis') # lazy callable load_images = _LazyCallable(image_analysis, 'load_images') load_audio = _LazyCallable(audio_analysis, 'load_audio') load_model = _LazyCallable(_LazyModuleLoader( 'turicreate.toolkits._model'), 'load_model') ################### Extension Importing ######################## import turicreate.extensions from turicreate.extensions import ext_import turicreate.extensions._add_meta_path() # rewrite the extensions module class _extensions_wrapper(object): def __init__(self, wrapped): self._wrapped = wrapped self.__doc__ = wrapped.__doc__ def __getattr__(self, name): try: return getattr(self._wrapped, name) except: pass turicreate._connect.main.get_unity() return getattr(self._wrapped, name) import sys as _sys _sys.modules["turicreate.extensions"] = _extensions_wrapper(_sys.modules["turicreate.extensions"]) # rewrite the import extensions = _sys.modules["turicreate.extensions"] from .visualization import plot, show # internal util from turicreate._connect.main import launch as _launch _launch()
en
0.76344
# -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause @package turicreate ... Turi Create is a machine learning platform that enables data scientists and app developers to easily create intelligent applications at scale. # expose name aggregate as global variable # this won't interfere with import turicreate.aggregate as agg # must load ## bring load functions to the top level # lazy import under leaf module level # lazy import under leaf module level # lazy import under leaf module level # lazy load under leaf node level # lazy load under leaf node level # lazy load under leaf node level # self-encaps modules without from import statements # we can use top-level lazy import for them # modules that don't expose attributes from __init__.py # lazy callable ################### Extension Importing ######################## # rewrite the extensions module # rewrite the import # internal util
1.724162
2
main/threadpool.py
haruhi5/Advance-python-example
0
6630462
import logging import threading from concurrent.futures import ThreadPoolExecutor import time import random # Test function def test(item): s = random.randrange(1, 10) logging.info(f'Thread {item}: id = {threading.get_ident()}') logging.info(f'Thread {item}: name = {threading.current_thread().getName()}') time.sleep(s) logging.info(f'Thread {item}: finished') def main(): logging.basicConfig(format='%(levelname)s - %(asctime)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logging.info('Test Starting...') workers = 5 items = 15 with ThreadPoolExecutor(max_workers=workers) as executor: executor.map(test, range(items)) for i in range(5): print(i) logging.info('Test Finished') if __name__ == '__main__': main()
import logging import threading from concurrent.futures import ThreadPoolExecutor import time import random # Test function def test(item): s = random.randrange(1, 10) logging.info(f'Thread {item}: id = {threading.get_ident()}') logging.info(f'Thread {item}: name = {threading.current_thread().getName()}') time.sleep(s) logging.info(f'Thread {item}: finished') def main(): logging.basicConfig(format='%(levelname)s - %(asctime)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logging.info('Test Starting...') workers = 5 items = 15 with ThreadPoolExecutor(max_workers=workers) as executor: executor.map(test, range(items)) for i in range(5): print(i) logging.info('Test Finished') if __name__ == '__main__': main()
en
0.1013
# Test function
3.003041
3
astropy/io/fits/tests/test_fitsdiff.py
MatiasRepetto/astropy
0
6630463
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest import os from . import FitsTestCase from astropy.io.fits.convenience import writeto from astropy.io.fits.hdu import PrimaryHDU, hdulist from astropy.io.fits import Header, ImageHDU, HDUList, FITSDiff from astropy.io.fits.scripts import fitsdiff from astropy import __version__ as version class TestFITSDiff_script(FitsTestCase): def test_help(self): with pytest.raises(SystemExit) as e: fitsdiff.main(['-h']) assert e.value.code == 0 def test_version(self, capsys): with pytest.raises(SystemExit) as e: fitsdiff.main(['--version']) out = capsys.readouterr()[0] assert out == f'fitsdiff {version}' assert e.value.code == 0 def test_noargs(self): with pytest.raises(SystemExit) as e: fitsdiff.main([""]) assert e.value.code == 2 def test_oneargargs(self): with pytest.raises(SystemExit) as e: fitsdiff.main(["file1"]) assert e.value.code == 2 def test_nodiff(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 0 def test_onediff(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 12 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 1 def test_manydiff(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a + 1 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) out, err = capsys.readouterr() assert numdiff == 1 assert out.splitlines()[-4:] == [ ' a> 9', ' b> 10', ' ...', ' 100 different pixels found (100.00% different).'] numdiff = fitsdiff.main(['-n', '1', tmp_a, tmp_b]) out, err = capsys.readouterr() assert numdiff == 1 assert out.splitlines()[-4:] == [ ' a> 0', ' b> 1', ' ...', ' 100 different pixels found (100.00% different).'] def test_outputfile(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 12 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(['-o', self.temp('diff.txt'), tmp_a, tmp_b]) assert numdiff == 1 with open(self.temp('diff.txt')) as f: out = f.read() assert out.splitlines()[-4:] == [ ' Data differs at [1, 2]:', ' a> 10', ' b> 12', ' 1 different pixels found (1.00% different).'] def test_atol(self): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-a", "1", tmp_a, tmp_b]) assert numdiff == 0 numdiff = fitsdiff.main(["--exact", "-a", "1", tmp_a, tmp_b]) assert numdiff == 1 def test_rtol(self): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-r", "1e-1", tmp_a, tmp_b]) assert numdiff == 0 def test_rtol_diff(self, capsys): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-r", "1e-2", tmp_a, tmp_b]) assert numdiff == 1 out, err = capsys.readouterr() assert out == f""" fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.01, Absolute tolerance: 0.0 Primary HDU: Data contains differences: Data differs at [1, 2]: a> 10.0 ? ^ b> 11.0 ? ^ 1 different pixels found (1.00% different). """ assert err == "" def test_wildcard(self): tmp1 = self.temp("tmp_file1") with pytest.raises(SystemExit) as e: fitsdiff.main([tmp1+"*", "ACME"]) assert e.value.code == 2 def test_not_quiet(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 0 out, err = capsys.readouterr() assert out == f""" fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.0, Absolute tolerance: 0.0 No differences found. """ assert err == "" def test_quiet(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-q", tmp_a, tmp_b]) assert numdiff == 0 out, err = capsys.readouterr() assert out == "" assert err == "" def test_path(self, capsys): os.mkdir(self.temp('sub/')) tmp_b = self.temp('sub/ascii.fits') tmp_g = self.temp('sub/group.fits') tmp_h = self.data('group.fits') with hdulist.fitsopen(tmp_h) as hdu_b: hdu_b.writeto(tmp_g) writeto(tmp_b, np.arange(100).reshape(10, 10)) # one modified file and a directory assert fitsdiff.main(["-q", self.data_dir, tmp_b]) == 1 assert fitsdiff.main(["-q", tmp_b, self.data_dir]) == 1 # two directories tmp_d = self.temp('sub/') assert fitsdiff.main(["-q", self.data_dir, tmp_d]) == 1 assert fitsdiff.main(["-q", tmp_d, self.data_dir]) == 1 with pytest.warns(UserWarning, match=r"Field 'ORBPARM' has a repeat " r"count of 0 in its format code"): assert fitsdiff.main(["-q", self.data_dir, self.data_dir]) == 0 # no match tmp_c = self.data('arange.fits') fitsdiff.main([tmp_c, tmp_d]) out, err = capsys.readouterr() assert "'arange.fits' has no match in" in err # globbing with pytest.warns(UserWarning, match=r"Field 'ORBPARM' has a repeat " r"count of 0 in its format code"): assert fitsdiff.main(["-q", self.data_dir+'/*.fits', self.data_dir]) == 0 assert fitsdiff.main(["-q", self.data_dir+'/g*.fits', tmp_d]) == 0 # one file and a directory tmp_f = self.data('tb.fits') assert fitsdiff.main(["-q", tmp_f, self.data_dir]) == 0 assert fitsdiff.main(["-q", self.data_dir, tmp_f]) == 0 def test_ignore_hdus(self): a = np.arange(100).reshape(10, 10) b = a.copy() + 1 ha = Header([('A', 1), ('B', 2), ('C', 3)]) phdu_a = PrimaryHDU(header=ha) phdu_b = PrimaryHDU(header=ha) ihdu_a = ImageHDU(data=a, name='SCI') ihdu_b = ImageHDU(data=b, name='SCI') hdulist_a = HDUList([phdu_a, ihdu_a]) hdulist_b = HDUList([phdu_b, ihdu_b]) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdulist_a.writeto(tmp_a) hdulist_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 1 numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"]) assert numdiff == 0 def test_ignore_hdus_report(self, capsys): a = np.arange(100).reshape(10, 10) b = a.copy() + 1 ha = Header([('A', 1), ('B', 2), ('C', 3)]) phdu_a = PrimaryHDU(header=ha) phdu_b = PrimaryHDU(header=ha) ihdu_a = ImageHDU(data=a, name='SCI') ihdu_b = ImageHDU(data=b, name='SCI') hdulist_a = HDUList([phdu_a, ihdu_a]) hdulist_b = HDUList([phdu_b, ihdu_b]) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdulist_a.writeto(tmp_a) hdulist_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"]) assert numdiff == 0 out, err = capsys.readouterr() assert "testa.fits" in out assert "testb.fits" in out @pytest.mark.skip(reason="fails intentionally to show open files (see PR #10159)") def test_fitsdiff_openfile(tmpdir): """Make sure that failing FITSDiff doesn't leave open files.""" path1 = str(tmpdir.join("file1.fits")) path2 = str(tmpdir.join("file2.fits")) hdulist = HDUList([PrimaryHDU(), ImageHDU(data=np.zeros(5))]) hdulist.writeto(path1) hdulist[1].data[0] = 1 hdulist.writeto(path2) diff = FITSDiff(path1, path2) assert diff.identical, diff.report()
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest import os from . import FitsTestCase from astropy.io.fits.convenience import writeto from astropy.io.fits.hdu import PrimaryHDU, hdulist from astropy.io.fits import Header, ImageHDU, HDUList, FITSDiff from astropy.io.fits.scripts import fitsdiff from astropy import __version__ as version class TestFITSDiff_script(FitsTestCase): def test_help(self): with pytest.raises(SystemExit) as e: fitsdiff.main(['-h']) assert e.value.code == 0 def test_version(self, capsys): with pytest.raises(SystemExit) as e: fitsdiff.main(['--version']) out = capsys.readouterr()[0] assert out == f'fitsdiff {version}' assert e.value.code == 0 def test_noargs(self): with pytest.raises(SystemExit) as e: fitsdiff.main([""]) assert e.value.code == 2 def test_oneargargs(self): with pytest.raises(SystemExit) as e: fitsdiff.main(["file1"]) assert e.value.code == 2 def test_nodiff(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 0 def test_onediff(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 12 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 1 def test_manydiff(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a + 1 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) out, err = capsys.readouterr() assert numdiff == 1 assert out.splitlines()[-4:] == [ ' a> 9', ' b> 10', ' ...', ' 100 different pixels found (100.00% different).'] numdiff = fitsdiff.main(['-n', '1', tmp_a, tmp_b]) out, err = capsys.readouterr() assert numdiff == 1 assert out.splitlines()[-4:] == [ ' a> 0', ' b> 1', ' ...', ' 100 different pixels found (100.00% different).'] def test_outputfile(self): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 12 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(['-o', self.temp('diff.txt'), tmp_a, tmp_b]) assert numdiff == 1 with open(self.temp('diff.txt')) as f: out = f.read() assert out.splitlines()[-4:] == [ ' Data differs at [1, 2]:', ' a> 10', ' b> 12', ' 1 different pixels found (1.00% different).'] def test_atol(self): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-a", "1", tmp_a, tmp_b]) assert numdiff == 0 numdiff = fitsdiff.main(["--exact", "-a", "1", tmp_a, tmp_b]) assert numdiff == 1 def test_rtol(self): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-r", "1e-1", tmp_a, tmp_b]) assert numdiff == 0 def test_rtol_diff(self, capsys): a = np.arange(100, dtype=float).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() b[1, 0] = 11 hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-r", "1e-2", tmp_a, tmp_b]) assert numdiff == 1 out, err = capsys.readouterr() assert out == f""" fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.01, Absolute tolerance: 0.0 Primary HDU: Data contains differences: Data differs at [1, 2]: a> 10.0 ? ^ b> 11.0 ? ^ 1 different pixels found (1.00% different). """ assert err == "" def test_wildcard(self): tmp1 = self.temp("tmp_file1") with pytest.raises(SystemExit) as e: fitsdiff.main([tmp1+"*", "ACME"]) assert e.value.code == 2 def test_not_quiet(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 0 out, err = capsys.readouterr() assert out == f""" fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.0, Absolute tolerance: 0.0 No differences found. """ assert err == "" def test_quiet(self, capsys): a = np.arange(100).reshape(10, 10) hdu_a = PrimaryHDU(data=a) b = a.copy() hdu_b = PrimaryHDU(data=b) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdu_a.writeto(tmp_a) hdu_b.writeto(tmp_b) numdiff = fitsdiff.main(["-q", tmp_a, tmp_b]) assert numdiff == 0 out, err = capsys.readouterr() assert out == "" assert err == "" def test_path(self, capsys): os.mkdir(self.temp('sub/')) tmp_b = self.temp('sub/ascii.fits') tmp_g = self.temp('sub/group.fits') tmp_h = self.data('group.fits') with hdulist.fitsopen(tmp_h) as hdu_b: hdu_b.writeto(tmp_g) writeto(tmp_b, np.arange(100).reshape(10, 10)) # one modified file and a directory assert fitsdiff.main(["-q", self.data_dir, tmp_b]) == 1 assert fitsdiff.main(["-q", tmp_b, self.data_dir]) == 1 # two directories tmp_d = self.temp('sub/') assert fitsdiff.main(["-q", self.data_dir, tmp_d]) == 1 assert fitsdiff.main(["-q", tmp_d, self.data_dir]) == 1 with pytest.warns(UserWarning, match=r"Field 'ORBPARM' has a repeat " r"count of 0 in its format code"): assert fitsdiff.main(["-q", self.data_dir, self.data_dir]) == 0 # no match tmp_c = self.data('arange.fits') fitsdiff.main([tmp_c, tmp_d]) out, err = capsys.readouterr() assert "'arange.fits' has no match in" in err # globbing with pytest.warns(UserWarning, match=r"Field 'ORBPARM' has a repeat " r"count of 0 in its format code"): assert fitsdiff.main(["-q", self.data_dir+'/*.fits', self.data_dir]) == 0 assert fitsdiff.main(["-q", self.data_dir+'/g*.fits', tmp_d]) == 0 # one file and a directory tmp_f = self.data('tb.fits') assert fitsdiff.main(["-q", tmp_f, self.data_dir]) == 0 assert fitsdiff.main(["-q", self.data_dir, tmp_f]) == 0 def test_ignore_hdus(self): a = np.arange(100).reshape(10, 10) b = a.copy() + 1 ha = Header([('A', 1), ('B', 2), ('C', 3)]) phdu_a = PrimaryHDU(header=ha) phdu_b = PrimaryHDU(header=ha) ihdu_a = ImageHDU(data=a, name='SCI') ihdu_b = ImageHDU(data=b, name='SCI') hdulist_a = HDUList([phdu_a, ihdu_a]) hdulist_b = HDUList([phdu_b, ihdu_b]) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdulist_a.writeto(tmp_a) hdulist_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b]) assert numdiff == 1 numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"]) assert numdiff == 0 def test_ignore_hdus_report(self, capsys): a = np.arange(100).reshape(10, 10) b = a.copy() + 1 ha = Header([('A', 1), ('B', 2), ('C', 3)]) phdu_a = PrimaryHDU(header=ha) phdu_b = PrimaryHDU(header=ha) ihdu_a = ImageHDU(data=a, name='SCI') ihdu_b = ImageHDU(data=b, name='SCI') hdulist_a = HDUList([phdu_a, ihdu_a]) hdulist_b = HDUList([phdu_b, ihdu_b]) tmp_a = self.temp('testa.fits') tmp_b = self.temp('testb.fits') hdulist_a.writeto(tmp_a) hdulist_b.writeto(tmp_b) numdiff = fitsdiff.main([tmp_a, tmp_b, "-u", "SCI"]) assert numdiff == 0 out, err = capsys.readouterr() assert "testa.fits" in out assert "testb.fits" in out @pytest.mark.skip(reason="fails intentionally to show open files (see PR #10159)") def test_fitsdiff_openfile(tmpdir): """Make sure that failing FITSDiff doesn't leave open files.""" path1 = str(tmpdir.join("file1.fits")) path2 = str(tmpdir.join("file2.fits")) hdulist = HDUList([PrimaryHDU(), ImageHDU(data=np.zeros(5))]) hdulist.writeto(path1) hdulist[1].data[0] = 1 hdulist.writeto(path2) diff = FITSDiff(path1, path2) assert diff.identical, diff.report()
en
0.748929
# Licensed under a 3-clause BSD style license - see LICENSE.rst fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.01, Absolute tolerance: 0.0 Primary HDU: Data contains differences: Data differs at [1, 2]: a> 10.0 ? ^ b> 11.0 ? ^ 1 different pixels found (1.00% different). fitsdiff: {version} a: {tmp_a} b: {tmp_b} Maximum number of different data values to be reported: 10 Relative tolerance: 0.0, Absolute tolerance: 0.0 No differences found. # one modified file and a directory # two directories # no match # globbing # one file and a directory #10159)") Make sure that failing FITSDiff doesn't leave open files.
1.931735
2
weblogo-3.4_rd/test_corebio/test_nexus.py
go-bears/Final-Project
0
6630464
<reponame>go-bears/Final-Project #!/usr/bin/env python import unittest from corebio.seq_io._nexus import Nexus from test_corebio import * class test_nexus(unittest.TestCase): def test_create(self) : n = Nexus() self.assertNotEqual( n , None) def test_parse_f0(self) : f = testdata_stream("nexus/test_Nexus_input.nex") n= Nexus(f) #self.output_basics(n) expected = ['t1', "t2 the name", "isn'that [a] strange name?", "one should be punished, for (that)!", "t5","t6","t7","t8","t9"] taxa = n.taxlabels self.assertEqual( taxa, expected) f.close() def test_parse_protein(self) : f = testdata_stream("nexus/protein.nex") n = Nexus(f) f.close() def test_parse_dna(self) : f = testdata_stream("nexus/dna.nex") n = Nexus(f) taxa = n.taxlabels taxa.sort() self.assertEqual( len(taxa) ,10) self.assertEqual( taxa[0], "Carp") self.assertEqual( taxa[-1], "Whale") f.close() def test_TreeTest1(self): """Test Tree module.""" f = testdata_stream("nexus/test_Nexus_input.nex") n=Nexus(f) t3=n.trees[2] t2=n.trees[2] t3.root_with_outgroup(['t1','t5']) # Return node_id of common ancestor if # taxon_list is monophyletic, -1 otherwise. self.assertEqual( t3.is_monophyletic(['t1','t5']), 13) t3.split(parent_id=t3.search_taxon('t9')) f.close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest from corebio.seq_io._nexus import Nexus from test_corebio import * class test_nexus(unittest.TestCase): def test_create(self) : n = Nexus() self.assertNotEqual( n , None) def test_parse_f0(self) : f = testdata_stream("nexus/test_Nexus_input.nex") n= Nexus(f) #self.output_basics(n) expected = ['t1', "t2 the name", "isn'that [a] strange name?", "one should be punished, for (that)!", "t5","t6","t7","t8","t9"] taxa = n.taxlabels self.assertEqual( taxa, expected) f.close() def test_parse_protein(self) : f = testdata_stream("nexus/protein.nex") n = Nexus(f) f.close() def test_parse_dna(self) : f = testdata_stream("nexus/dna.nex") n = Nexus(f) taxa = n.taxlabels taxa.sort() self.assertEqual( len(taxa) ,10) self.assertEqual( taxa[0], "Carp") self.assertEqual( taxa[-1], "Whale") f.close() def test_TreeTest1(self): """Test Tree module.""" f = testdata_stream("nexus/test_Nexus_input.nex") n=Nexus(f) t3=n.trees[2] t2=n.trees[2] t3.root_with_outgroup(['t1','t5']) # Return node_id of common ancestor if # taxon_list is monophyletic, -1 otherwise. self.assertEqual( t3.is_monophyletic(['t1','t5']), 13) t3.split(parent_id=t3.search_taxon('t9')) f.close() if __name__ == '__main__': unittest.main()
en
0.288472
#!/usr/bin/env python #self.output_basics(n) Test Tree module. # Return node_id of common ancestor if # taxon_list is monophyletic, -1 otherwise.
2.513697
3
src/plugins/id.py
SaloxiddinTursunaliev/TelegramTaxiBot
0
6630465
<reponame>SaloxiddinTursunaliev/TelegramTaxiBot @bot.message_handler(commands=['id', 'Id']) def send_id(message): cur.execute('SELECT * from language where id = %s', [str(message.from_user.id)]) record = cur.fetchall() for row in record: userid = row[0] userlang = row[1] username = message.from_user.first_name.encode("utf-8") userid = message.from_user.id reply_msg = language[userlang]["ID_MSG"] gpid = message.chat.id if message.chat.type == "supergroup" or message.chat.type == "group": reply_msg = reply_msg + language[userlang]["INGP_ID_MSG"] if message.reply_to_message: repliedid = message.reply_to_message.from_user.id reply_msg = reply_msg + language[userlang]["REPLIED_ID_MSG"].format(repliedid) if message.reply_to_message.forward_from: reply_msg = reply_msg + language[userlang]["FORWARDED_ID_MSG"].format(message.reply_to_message.forward_from.id) try: reply_msg = reply_msg + language[userlang]["CHATID_ID_MSG"].format(message.reply_to_message.forward_from_chat.id) except: pass bot.reply_to(message, reply_msg.format(username, userid, gpid), parse_mode="Markdown")
@bot.message_handler(commands=['id', 'Id']) def send_id(message): cur.execute('SELECT * from language where id = %s', [str(message.from_user.id)]) record = cur.fetchall() for row in record: userid = row[0] userlang = row[1] username = message.from_user.first_name.encode("utf-8") userid = message.from_user.id reply_msg = language[userlang]["ID_MSG"] gpid = message.chat.id if message.chat.type == "supergroup" or message.chat.type == "group": reply_msg = reply_msg + language[userlang]["INGP_ID_MSG"] if message.reply_to_message: repliedid = message.reply_to_message.from_user.id reply_msg = reply_msg + language[userlang]["REPLIED_ID_MSG"].format(repliedid) if message.reply_to_message.forward_from: reply_msg = reply_msg + language[userlang]["FORWARDED_ID_MSG"].format(message.reply_to_message.forward_from.id) try: reply_msg = reply_msg + language[userlang]["CHATID_ID_MSG"].format(message.reply_to_message.forward_from_chat.id) except: pass bot.reply_to(message, reply_msg.format(username, userid, gpid), parse_mode="Markdown")
none
1
2.469614
2
christmasCTF/2016/house_of_daehee (unsolved)/debug.py
PurpEth/solved-hacking-problem
1
6630466
import gdb class AgainCommand(gdb.Command): def __init__(self): super(AgainCommand, self).__init__( "again", gdb.COMMAND_RUNNING ) def invoke(self, arg, from_tty): gdb.execute('tbreak *unlink+173') # b gdb.execute('tbreak *main+807') # c gdb.execute('tbreak *main+825') # b gdb.execute('tbreak *main+843') # a f = open('payload', 'w') f.write('12345678\xa1') f.close() gdb.execute('run < payload') class QuickViewCommand(gdb.Command): def __init__(self): super(QuickViewCommand, self).__init__( "qv", gdb.COMMAND_DATA ) def invoke(self, arg, from_tty): gdb.execute('x/40wx 0x555555757000') AgainCommand().invoke([], False) QuickViewCommand()
import gdb class AgainCommand(gdb.Command): def __init__(self): super(AgainCommand, self).__init__( "again", gdb.COMMAND_RUNNING ) def invoke(self, arg, from_tty): gdb.execute('tbreak *unlink+173') # b gdb.execute('tbreak *main+807') # c gdb.execute('tbreak *main+825') # b gdb.execute('tbreak *main+843') # a f = open('payload', 'w') f.write('12345678\xa1') f.close() gdb.execute('run < payload') class QuickViewCommand(gdb.Command): def __init__(self): super(QuickViewCommand, self).__init__( "qv", gdb.COMMAND_DATA ) def invoke(self, arg, from_tty): gdb.execute('x/40wx 0x555555757000') AgainCommand().invoke([], False) QuickViewCommand()
en
0.38951
# b # c # b # a
2.487408
2
src/developer/ffx/build/gn_generate_cmd.py
EnderNightLord-ChromeBook/zircon-rpi
14
6630467
<filename>src/developer/ffx/build/gn_generate_cmd.py #!/usr/bin/env python3.8 # Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # import argparse import os import string import sys # Root dir is 5 levels up from here. FUCHSIA_DIR = os.path.abspath( os.path.join( __file__, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)) sys.path += [os.path.join(FUCHSIA_DIR, 'third_party')] from jinja2 import Environment, FileSystemLoader def to_camel_case(snake_str): components = snake_str.split('_') return ''.join(x.title() for x in components[0:]) def wrap_deps(dep): return {'enum': to_camel_case(dep), 'lib': dep + '_args'} def main(args_list=None): parser = argparse.ArgumentParser(description='Generate FFX Command struct') parser.add_argument( '--out', help='The output file to generate', required=True) parser.add_argument( '--deps', help='Comma-seperated libraries to generate code from', required=True) parser.add_argument( '--template', help='The template file to use to generate code', required=True) if args_list: args = parser.parse_args(args_list) else: args = parser.parse_args() template_path = os.path.join(os.path.dirname(__file__), 'templates') env = Environment( loader=FileSystemLoader(template_path), trim_blocks=True, lstrip_blocks=True) template = env.get_template(args.template) libraries = args.deps.split(',') deps = map(wrap_deps, libraries) with open(args.out, 'w') as file: file.write(template.render(deps=deps)) if __name__ == '__main__': sys.exit(main())
<filename>src/developer/ffx/build/gn_generate_cmd.py #!/usr/bin/env python3.8 # Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # import argparse import os import string import sys # Root dir is 5 levels up from here. FUCHSIA_DIR = os.path.abspath( os.path.join( __file__, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)) sys.path += [os.path.join(FUCHSIA_DIR, 'third_party')] from jinja2 import Environment, FileSystemLoader def to_camel_case(snake_str): components = snake_str.split('_') return ''.join(x.title() for x in components[0:]) def wrap_deps(dep): return {'enum': to_camel_case(dep), 'lib': dep + '_args'} def main(args_list=None): parser = argparse.ArgumentParser(description='Generate FFX Command struct') parser.add_argument( '--out', help='The output file to generate', required=True) parser.add_argument( '--deps', help='Comma-seperated libraries to generate code from', required=True) parser.add_argument( '--template', help='The template file to use to generate code', required=True) if args_list: args = parser.parse_args(args_list) else: args = parser.parse_args() template_path = os.path.join(os.path.dirname(__file__), 'templates') env = Environment( loader=FileSystemLoader(template_path), trim_blocks=True, lstrip_blocks=True) template = env.get_template(args.template) libraries = args.deps.split(',') deps = map(wrap_deps, libraries) with open(args.out, 'w') as file: file.write(template.render(deps=deps)) if __name__ == '__main__': sys.exit(main())
en
0.902783
#!/usr/bin/env python3.8 # Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Root dir is 5 levels up from here.
2.186889
2
petl/test/io/test_sources.py
a-musing-moose/petl
0
6630468
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import zipfile from tempfile import NamedTemporaryFile from petl.compat import PY2 from petl.test.helpers import ieq, eq_ import petl as etl from petl.io.sources import StringSource, PopenSource, ZipSource, StdoutSource def test_stringsource(): table1 = (('foo', 'bar'), ('a', '1'), ('b', '2'), ('c', '2')) # test writing to a string buffer ss = StringSource() etl.tocsv(table1, ss) expect = "foo,bar\r\na,1\r\nb,2\r\nc,2\r\n" if not PY2: expect = expect.encode('ascii') actual = ss.getvalue() eq_(expect, actual) # test reading from a string buffer table2 = etl.fromcsv(StringSource(actual)) ieq(table1, table2) ieq(table1, table2) # test appending etl.appendcsv(table1, ss) actual = ss.getvalue() expect = "foo,bar\r\na,1\r\nb,2\r\nc,2\r\na,1\r\nb,2\r\nc,2\r\n" if not PY2: expect = expect.encode('ascii') eq_(expect, actual) def test_popensource(): expect = (('foo', 'bar'),) delimiter = ' ' actual = etl.fromcsv(PopenSource(r'echo foo bar', shell=True), delimiter=delimiter) ieq(expect, actual) def test_zipsource(): # setup table = [('foo', 'bar'), ('a', '1'), ('b', '2')] fn_tsv = NamedTemporaryFile().name etl.totsv(table, fn_tsv) fn_zip = NamedTemporaryFile().name z = zipfile.ZipFile(fn_zip, mode='w') z.write(fn_tsv, 'data.tsv') z.close() # test actual = etl.fromtsv(ZipSource(fn_zip, 'data.tsv')) ieq(table, actual) def test_stdoutsource(): table = [('foo', 'bar'), ('a', 1), ('b', 2)] etl.tocsv(table, StdoutSource(), encoding='ascii') etl.tohtml(table, StdoutSource(), encoding='ascii') etl.topickle(table, StdoutSource()) def test_stdoutsource_unicode(): table = [('foo', 'bar'), (u'Արամ Խաչատրյան', 1), (u'<NAME>', 2)] etl.tocsv(table, StdoutSource(), encoding='utf-8') etl.tohtml(table, StdoutSource(), encoding='utf-8') etl.topickle(table, StdoutSource())
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import zipfile from tempfile import NamedTemporaryFile from petl.compat import PY2 from petl.test.helpers import ieq, eq_ import petl as etl from petl.io.sources import StringSource, PopenSource, ZipSource, StdoutSource def test_stringsource(): table1 = (('foo', 'bar'), ('a', '1'), ('b', '2'), ('c', '2')) # test writing to a string buffer ss = StringSource() etl.tocsv(table1, ss) expect = "foo,bar\r\na,1\r\nb,2\r\nc,2\r\n" if not PY2: expect = expect.encode('ascii') actual = ss.getvalue() eq_(expect, actual) # test reading from a string buffer table2 = etl.fromcsv(StringSource(actual)) ieq(table1, table2) ieq(table1, table2) # test appending etl.appendcsv(table1, ss) actual = ss.getvalue() expect = "foo,bar\r\na,1\r\nb,2\r\nc,2\r\na,1\r\nb,2\r\nc,2\r\n" if not PY2: expect = expect.encode('ascii') eq_(expect, actual) def test_popensource(): expect = (('foo', 'bar'),) delimiter = ' ' actual = etl.fromcsv(PopenSource(r'echo foo bar', shell=True), delimiter=delimiter) ieq(expect, actual) def test_zipsource(): # setup table = [('foo', 'bar'), ('a', '1'), ('b', '2')] fn_tsv = NamedTemporaryFile().name etl.totsv(table, fn_tsv) fn_zip = NamedTemporaryFile().name z = zipfile.ZipFile(fn_zip, mode='w') z.write(fn_tsv, 'data.tsv') z.close() # test actual = etl.fromtsv(ZipSource(fn_zip, 'data.tsv')) ieq(table, actual) def test_stdoutsource(): table = [('foo', 'bar'), ('a', 1), ('b', 2)] etl.tocsv(table, StdoutSource(), encoding='ascii') etl.tohtml(table, StdoutSource(), encoding='ascii') etl.topickle(table, StdoutSource()) def test_stdoutsource_unicode(): table = [('foo', 'bar'), (u'Արամ Խաչատրյան', 1), (u'<NAME>', 2)] etl.tocsv(table, StdoutSource(), encoding='utf-8') etl.tohtml(table, StdoutSource(), encoding='utf-8') etl.topickle(table, StdoutSource())
en
0.696918
# -*- coding: utf-8 -*- # test writing to a string buffer # test reading from a string buffer # test appending # setup # test
2.376603
2
Condor/Tools/Autorun/shell.py
OriolOriolOriol/Condor
0
6630469
<filename>Condor/Tools/Autorun/shell.py # Import modules import os.path from os import remove __startup_path = os.path.join(os.getenv("APPDATA"), "Microsoft\\Windows\\Start Menu\\Programs\\Startup") """ Add to startup (startup dir) """ def Install(name, executable): payload = (f""" [InternetShortcut] URL=file://{os.path.abspath(executable)} """) target = os.path.join(__startup_path, name + ".url") with open(target, 'w') as file: file.write(payload) return True """ Delete from startup (startup dir) """ def Uninstall(name): target = os.path.join(__startup_path, name + ".url") try: remove(target) except FileNotFoundError: pass return not os.path.exists(name) """ Check if exists (startup dir) """ def Exists(name): target = os.path.join(__startup_path, name + ".url") return os.path.exists(target)
<filename>Condor/Tools/Autorun/shell.py # Import modules import os.path from os import remove __startup_path = os.path.join(os.getenv("APPDATA"), "Microsoft\\Windows\\Start Menu\\Programs\\Startup") """ Add to startup (startup dir) """ def Install(name, executable): payload = (f""" [InternetShortcut] URL=file://{os.path.abspath(executable)} """) target = os.path.join(__startup_path, name + ".url") with open(target, 'w') as file: file.write(payload) return True """ Delete from startup (startup dir) """ def Uninstall(name): target = os.path.join(__startup_path, name + ".url") try: remove(target) except FileNotFoundError: pass return not os.path.exists(name) """ Check if exists (startup dir) """ def Exists(name): target = os.path.join(__startup_path, name + ".url") return os.path.exists(target)
en
0.262843
# Import modules Add to startup (startup dir) [InternetShortcut] URL=file://{os.path.abspath(executable)} Delete from startup (startup dir) Check if exists (startup dir)
2.605238
3
tests/test_ulist.py
nclarey/pyg-base
0
6630470
from pyg_base import ulist, rng def test_rng(): assert rng(3) == list(range(3)) def test_ulist(): assert ulist([1,3,2,1]) == list([1,3,2]) assert ulist([1,3,2,1]) + 4 == list([1,3,2,4]) assert ulist([1,3,2,1]) + [4,1] == list([1,3,2,4]) assert ulist([1,3,2,1]) + [4,1,5] == list([1,3,2,4,5]) assert ulist([1,3,2,1]) & [1,3,4] == [1,3] assert ulist([1,3,2,1]) & 1 == [1] assert ulist([1,3,2,1]) & 4 == [] assert ulist([1,3,2,1]) - [1,3,4] == [2] assert ulist([1,3,2,1]) - 4 == ulist([1,3,2]) assert ulist([1,3,2,1]) - [4,5] == ulist([1,3,2]) def test_ulist_add(): assert ulist([1,2,3]) + 1 == ulist([1,2,3]) assert ulist([1,2,3]) + [1,2] == ulist([1,2,3]) assert ulist([1,2,3]).copy() == ulist([1,2,3])
from pyg_base import ulist, rng def test_rng(): assert rng(3) == list(range(3)) def test_ulist(): assert ulist([1,3,2,1]) == list([1,3,2]) assert ulist([1,3,2,1]) + 4 == list([1,3,2,4]) assert ulist([1,3,2,1]) + [4,1] == list([1,3,2,4]) assert ulist([1,3,2,1]) + [4,1,5] == list([1,3,2,4,5]) assert ulist([1,3,2,1]) & [1,3,4] == [1,3] assert ulist([1,3,2,1]) & 1 == [1] assert ulist([1,3,2,1]) & 4 == [] assert ulist([1,3,2,1]) - [1,3,4] == [2] assert ulist([1,3,2,1]) - 4 == ulist([1,3,2]) assert ulist([1,3,2,1]) - [4,5] == ulist([1,3,2]) def test_ulist_add(): assert ulist([1,2,3]) + 1 == ulist([1,2,3]) assert ulist([1,2,3]) + [1,2] == ulist([1,2,3]) assert ulist([1,2,3]).copy() == ulist([1,2,3])
none
1
2.92488
3
Athos/Networks/SqueezeNetCIFAR10/Squeezenet_model.py
shas19/EzPC
1
6630471
''' Authors: <NAME>. Copyright: Copyright (c) 2018 Microsoft Research 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. ** Parts of this code including the model itself, the training code and some other parts were taken from https://github.com/kaizouman/tensorsandbox/tree/master/cifar10/models/squeeze ** ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import Util import time import numpy import matplotlib import tensorflow as tf sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'TFCompiler')) import DumpTFMtData from argparse import ArgumentParser class SqueezeNet1Orig: def __init__(self): self.all_weights = [] def inference(self, images): # conv1 conv1 = self.conv_layer(images, size=3, filters=64, stride=1, decay=False, name='conv1') # pool1 pool1 = self.pool_layer(conv1, size=3, stride=2, name='pool1') # fire2 fire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2') # fire3 fire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3') # pool2 pool2 = self.pool_layer(fire3, size=3, stride=2, name='pool2') # fire4 fire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4') # fire5 fire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5') # Final squeeze to get ten classes conv2 = self.conv_layer(fire5, size=1, filters=10, stride=1, decay=False, name='squeeze') # Average pooling on spatial dimensions predictions = self.avg_layer(conv2, name='avg_pool') return predictions def pool_layer(self, inputs, size, stride, name): with tf.variable_scope(name) as scope: outputs = tf.nn.max_pool(inputs, ksize=[1,size,size,1], strides=[1,stride,stride,1], padding='SAME', name=name) return outputs def fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False): with tf.variable_scope(name) as scope: # Squeeze sub-layer squeezed_inputs = self.conv_layer(inputs, size=1, filters=s1x1, stride=1, decay=decay, name='s1x1') # Expand 1x1 sub-layer e1x1_outputs = self.conv_layer(squeezed_inputs, size=1, filters=e1x1, stride=1, decay=decay, name='e1x1') # Expand 3x3 sub-layer e3x3_outputs = self.conv_layer(squeezed_inputs, size=3, filters=e3x3, stride=1, decay=decay, name='e3x3') # Concatenate outputs along the last dimension (channel) return tf.concat([e1x1_outputs, e3x3_outputs], 3) def avg_layer(self, inputs, name): w = inputs.get_shape().as_list()[1] h = inputs.get_shape().as_list()[2] c = inputs.get_shape().as_list()[3] with tf.variable_scope(name) as scope: # Use current spatial dimensions as Kernel size to produce a scalar avg = tf.nn.avg_pool(inputs, ksize=[1,w,h,1], strides=[1,1,1,1], padding='VALID', name=scope.name) # Reshape output to remove spatial dimensions reduced to one return tf.reshape(avg, shape=[-1,c]) def conv_layer(self, inputs, size, filters, stride, decay, name): channels = inputs.shape[3] shape = [size, size, channels, filters] with tf.variable_scope(name + '/conv') as scope: weights = self._get_weights_var('weights', shape=shape, decay=decay) biases = self.get_cons_variable([filters], 0.0) conv = tf.nn.conv2d(inputs, weights, strides=[1,stride,stride,1], padding='SAME') pre_activation = tf.nn.bias_add(conv, biases) outputs= tf.nn.relu(pre_activation, name=scope.name) return outputs def get_cons_variable(self, shape, val): initial = tf.constant(val, shape=shape) temp = tf.Variable(initial) self.all_weights.append(temp) return temp def _get_weights_var(self, name, shape, decay=False): """Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor """ # Declare an initializer for this variable initializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32) # Declare variable (it is trainable by default) var = tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) if decay: # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size weight_decay = self.wd for x in shape: weight_decay /= x # Weight loss is L2 loss multiplied by weight decay weight_loss = tf.multiply(tf.nn.l2_loss(var), weight_decay, name='weight_loss') # Add weight loss for this variable to the global losses collection tf.add_to_collection('losses', weight_loss) self.all_weights.append(var) return var class SqueezeNet1: def __init__(self, use_cons_init): self.all_weights = [] self.debug_weights = [] self.use_cons_init = use_cons_init def inference(self, images): # conv1 conv1 = self.conv_layer(images, size=3, filters=64, stride=1, decay=False, name='conv1') # pool1 pool1 = self.pool_layer(conv1, size=3, stride=2, name='pool1') # fire2 fire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2') # fire3 fire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3') # pool2 pool2 = self.pool_layer(fire3, size=3, stride=2, name='pool2') # fire4 fire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4') # fire5 fire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5') # Final squeeze to get ten classes conv2 = self.conv_layer(fire5, size=1, filters=10, stride=1, decay=False, name='squeeze') # Average pooling on spatial dimensions predictions = self.avg_layer(conv2, name='avg_pool') return predictions def pool_layer(self, inputs, size, stride, name): with tf.variable_scope(name) as scope: outputs = tf.nn.max_pool(inputs, ksize=[1,size,size,1], strides=[1,stride,stride,1], padding='SAME', name=name) return outputs def fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False): with tf.variable_scope(name) as scope: # Squeeze sub-layer squeezed_inputs = self.conv_layer(inputs, size=1, filters=s1x1, stride=1, decay=decay, name='s1x1') # Expand 1x1 sub-layer e1x1_outputs = self.conv_layer(squeezed_inputs, size=1, filters=e1x1, stride=1, decay=decay, name='e1x1') # Expand 3x3 sub-layer e3x3_outputs = self.conv_layer(squeezed_inputs, size=3, filters=e3x3, stride=1, decay=decay, name='e3x3') # Concatenate outputs along the last dimension (channel) return tf.concat([e1x1_outputs, e3x3_outputs], 3) def avg_layer(self, inputs, name): w = inputs.get_shape().as_list()[1] h = inputs.get_shape().as_list()[2] c = inputs.get_shape().as_list()[3] with tf.variable_scope(name) as scope: # Use current spatial dimensions as Kernel size to produce a scalar avg = tf.nn.avg_pool(inputs, ksize=[1,w,h,1], strides=[1,1,1,1], padding='VALID', name=scope.name) # Reshape output to remove spatial dimensions reduced to one return tf.reshape(avg, shape=[-1,c]) def conv_layer(self, inputs, size, filters, stride, decay, name): channels = inputs.shape[3] shape = [size, size, channels, filters] with tf.variable_scope(name + '/conv') as scope: # For getting performance numbers, don't need to use the actual activations - just use constant activations if self.use_cons_init: weights = self.get_cons_variable(shape, 0.01) else: weights = self._get_weights_var('weights', shape=shape, decay=decay) biases = self.get_cons_variable([filters], 0.0) conv = tf.nn.conv2d(inputs, weights, strides=[1,stride,stride,1], padding='SAME') pre_activation = tf.nn.bias_add(conv, biases) outputs= tf.nn.relu(pre_activation, name=scope.name) return outputs def get_cons_variable(self, shape, val): initial = tf.constant(val, shape=shape) temp = tf.Variable(initial) self.all_weights.append(temp) return temp def _get_weights_var(self, name, shape, decay=False): """Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor """ # Declare an initializer for this variable initializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32) # Declare variable (it is trainable by default) var = tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) if decay: # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size weight_decay = self.wd for x in shape: weight_decay /= x # Weight loss is L2 loss multiplied by weight decay weight_loss = tf.multiply(tf.nn.l2_loss(var), weight_decay, name='weight_loss') # Add weight loss for this variable to the global losses collection tf.add_to_collection('losses', weight_loss) self.all_weights.append(var) return var def train(sqn, save_model_path): print('Starting train...') # Hyper parameters epochs = 1 batch_size = 128 keep_probability = 0.7 learning_rate = 0.001 n_batches = 5 #CIFAR10 dataset in the python version has 5 batches x = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x') y = tf.placeholder(tf.float32, shape=(None, 10), name='output_y') keep_prob = tf.placeholder(tf.float32, name='keep_prob') logits = sqn.inference(x) # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) l2Loss = sum(list(map(lambda x: tf.nn.l2_loss(x), sqn.all_weights))) beta = 1e-5 cost = cost + beta*l2Loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') valid_features, valid_labels = Util.load_preprocess_validation_data() testing_features, testing_labels = Util.load_preprocess_testing_data() print('Training now...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in Util.load_preprocess_training_batch(batch_i, batch_size): sess.run(optimizer, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability }) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') # Print stats loss = sess.run(cost, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability}) train_acc = sess.run(accuracy, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability}) valid_acc = sess.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob: keep_probability}) testing_acc = sess.run(accuracy, feed_dict={x: testing_features, y: testing_labels, keep_prob: keep_probability}) print('Loss: {:>10.4f} Train Acc: {:.6f} Validation Accuracy: {:.6f} Testing Acc: {:.6f}'.format(loss, train_acc, valid_acc, testing_acc)) if (epoch % 10 == 0): # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) #outputArgMax should only be used when findAcc is False def infer(sqn, sess, images, labels, restoreModelPath, findAccOrArgMaxOrPredVal=0, restoreWeights=True, onlysavegraph=False): assert(findAccOrArgMaxOrPredVal>=0 and findAccOrArgMaxOrPredVal<=2) if restoreWeights: assert(not(onlysavegraph)) if onlysavegraph: assert(findAccOrArgMaxOrPredVal==1) x = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x') if (not(onlysavegraph)): y = tf.placeholder(tf.int32, shape=(None, 10), name='output_y') logits = sqn.inference(x) if findAccOrArgMaxOrPredVal==0: correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') elif findAccOrArgMaxOrPredVal==1: logits = tf.argmax(logits, axis=1) elif findAccOrArgMaxOrPredVal==2: pass else: assert False print("Doing inference on ", len(images), " images.") feed_dict = {x: images} if not(onlysavegraph): feed_dict[y] = labels sess.run(tf.global_variables_initializer()) if onlysavegraph: output_tensor = None gg = tf.get_default_graph() for node in gg.as_graph_def().node: if node.name == 'ArgMax': output_tensor = gg.get_operation_by_name(node.name).outputs[0] optimized_graph_def = DumpTFMtData.save_graph_metadata(output_tensor, sess, feed_dict) return if restoreWeights: saver = tf.train.Saver(sqn.all_weights) saver.restore(sess, restoreModelPath) print("*************** Starting Prediction****************") start_time = time.time() if findAccOrArgMaxOrPredVal==0: predictions = sess.run([accuracy], feed_dict=feed_dict) else: predictions = sess.run([logits], feed_dict=feed_dict) end_time = time.time() print("*************** Done Prediction****************") duration = end_time - start_time print("Time taken in prediction : ", duration) print("Inference result = ", predictions) return predictions def getTrainedWeightsStrForm(sess, evalTensors, scalingFac): allWeightsStr = '' finalParameters = map(lambda x : sess.run(x), evalTensors) for curParameterVal in finalParameters: for xx in numpy.nditer(curParameterVal, order='C'): allWeightsStr += (str(int(xx * (1<<scalingFac))) + ' ') allWeightsStr += '\n\n' return allWeightsStr def findAndSaveCorrectTestImg(pred, features, actualLabels, correctImgFolder, incorrectImgFolder, textFolder, sess, sqn, scalingFac): #Run with findAcc=False and outputArgMax=False assert(len(pred)==1 and len(pred[0].shape)==2) modelPred = numpy.argmax(pred[0], axis=1) trueLabel = numpy.argmax(actualLabels, axis=1) print("Pred = ", pred) print("actualLabels = ", actualLabels) print("ModelPred = ", modelPred) print("TrueLabel = ", trueLabel) numImages = len(features) allWeightsStr = getTrainedWeightsStrForm(sess, sqn.all_weights, scalingFac) for ii in range(numImages): curImage = features[ii] if (modelPred[ii]==trueLabel[ii]): matplotlib.image.imsave(os.path.join(correctImgFolder, str(ii)+'-test.png'), curImage) else: matplotlib.image.imsave(os.path.join(incorrectImgFolder, str(ii)+'-test.png'), curImage) textInpFileName = os.path.join(textFolder, str(ii)+'-test-inp.txt') dumpCifar10Image(curImage, textInpFileName, scalingFac, 'w') with open(textInpFileName, 'a') as ff: ff.write(allWeightsStr) if (ii%10==0): print("Processing ", ii, " images done.") def main(): scalingFac = 12 findAccOrArgMaxOrPredVal = 0 restoreWeights = True onlysavegraph = False save_model_path = './TrainedModel/model' doTraining = False inp = None if (len(sys.argv) > 1): inp = sys.argv[1] if (inp == 'train'): doTraining = True elif (inp == 'savegraph'): findAccOrArgMaxOrPredVal = 1 restoreWeights = False onlysavegraph = True testing_features, testing_labels = Util.get_sample_points(2, 4555, 4556) elif (inp == 'testSingleTestInp'): testBatchInpNum = int(sys.argv[2]) findAccOrArgMaxOrPredVal = 1 restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1] elif (inp == 'testSingleTestInpAndSaveData'): testBatchInpNum = int(sys.argv[2]) findAccOrArgMaxOrPredVal = int(sys.argv[3]) restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1] # testing_features, testing_labels = numpy.full((1,32,32,3),0.01), numpy.full((1,10),0.01) elif (inp == 'savegraphAndDataBatch'): batchNum = int(sys.argv[2]) imgStartNum = int(sys.argv[3]) imgEndNum = int(sys.argv[4]) findAccOrArgMaxOrPredVal = 1 restoreWeights = False onlysavegraph = True testing_features, testing_labels = Util.get_sample_points(batchNum, imgStartNum, imgEndNum) elif (inp == 'testBatchInp'): imgStartNum = int(sys.argv[2]) imgEndNum = int(sys.argv[3]) findAccOrArgMaxOrPredVal = 1 restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[imgStartNum:imgEndNum], all_testing_labels[imgStartNum:imgEndNum] elif (inp == 'findAndSaveCorrectTestImg'): findAccOrArgMaxOrPredVal = 2 restoreWeights = True onlysavegraph = False testing_features, testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = testing_features[0:100], testing_labels[0:100] else: if (inp != ""): print("WARNING : Given option didn't match any known value.") testing_features, testing_labels = Util.load_preprocess_testing_data() sqn = SqueezeNet1(use_cons_init=onlysavegraph) if doTraining: train(sqn, save_model_path) else: with tf.Session() as sess: pred = infer(sqn, sess, testing_features, testing_labels, save_model_path, findAccOrArgMaxOrPredVal=findAccOrArgMaxOrPredVal, restoreWeights=restoreWeights, onlysavegraph=onlysavegraph) if findAccOrArgMaxOrPredVal==1 and not(onlysavegraph): print("Actual labels = ", testing_labels) print("ArgMax in actual label : ", numpy.argmax(testing_labels, axis=1)) if (inp == 'findAndSaveCorrectTestImg'): print('Running ' + inp) print(pred[0].shape) findAndSaveCorrectTestImg(pred, testing_features, testing_labels, './testPred/CorrectImg/', './testPred/IncorrectImg/', './testPred/TestInputs/', sess, sqn, scalingFac) if (inp == 'savegraphAndDataBatch' or inp=='testSingleTestInpAndSaveData'): imgFileName = 'SqNet_CIFAR_img.inp' weightsFileName = 'SqNet_CIFAR_weights.inp' for ii,curFeature in enumerate(testing_features): if ii == 0 : DumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'w') else: DumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'a') DumpTFMtData.dumpTrainedWeightsInt(sess, sqn.all_weights, weightsFileName, scalingFac, 'w') if __name__ == '__main__': main()
''' Authors: <NAME>. Copyright: Copyright (c) 2018 Microsoft Research 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. ** Parts of this code including the model itself, the training code and some other parts were taken from https://github.com/kaizouman/tensorsandbox/tree/master/cifar10/models/squeeze ** ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import Util import time import numpy import matplotlib import tensorflow as tf sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'TFCompiler')) import DumpTFMtData from argparse import ArgumentParser class SqueezeNet1Orig: def __init__(self): self.all_weights = [] def inference(self, images): # conv1 conv1 = self.conv_layer(images, size=3, filters=64, stride=1, decay=False, name='conv1') # pool1 pool1 = self.pool_layer(conv1, size=3, stride=2, name='pool1') # fire2 fire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2') # fire3 fire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3') # pool2 pool2 = self.pool_layer(fire3, size=3, stride=2, name='pool2') # fire4 fire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4') # fire5 fire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5') # Final squeeze to get ten classes conv2 = self.conv_layer(fire5, size=1, filters=10, stride=1, decay=False, name='squeeze') # Average pooling on spatial dimensions predictions = self.avg_layer(conv2, name='avg_pool') return predictions def pool_layer(self, inputs, size, stride, name): with tf.variable_scope(name) as scope: outputs = tf.nn.max_pool(inputs, ksize=[1,size,size,1], strides=[1,stride,stride,1], padding='SAME', name=name) return outputs def fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False): with tf.variable_scope(name) as scope: # Squeeze sub-layer squeezed_inputs = self.conv_layer(inputs, size=1, filters=s1x1, stride=1, decay=decay, name='s1x1') # Expand 1x1 sub-layer e1x1_outputs = self.conv_layer(squeezed_inputs, size=1, filters=e1x1, stride=1, decay=decay, name='e1x1') # Expand 3x3 sub-layer e3x3_outputs = self.conv_layer(squeezed_inputs, size=3, filters=e3x3, stride=1, decay=decay, name='e3x3') # Concatenate outputs along the last dimension (channel) return tf.concat([e1x1_outputs, e3x3_outputs], 3) def avg_layer(self, inputs, name): w = inputs.get_shape().as_list()[1] h = inputs.get_shape().as_list()[2] c = inputs.get_shape().as_list()[3] with tf.variable_scope(name) as scope: # Use current spatial dimensions as Kernel size to produce a scalar avg = tf.nn.avg_pool(inputs, ksize=[1,w,h,1], strides=[1,1,1,1], padding='VALID', name=scope.name) # Reshape output to remove spatial dimensions reduced to one return tf.reshape(avg, shape=[-1,c]) def conv_layer(self, inputs, size, filters, stride, decay, name): channels = inputs.shape[3] shape = [size, size, channels, filters] with tf.variable_scope(name + '/conv') as scope: weights = self._get_weights_var('weights', shape=shape, decay=decay) biases = self.get_cons_variable([filters], 0.0) conv = tf.nn.conv2d(inputs, weights, strides=[1,stride,stride,1], padding='SAME') pre_activation = tf.nn.bias_add(conv, biases) outputs= tf.nn.relu(pre_activation, name=scope.name) return outputs def get_cons_variable(self, shape, val): initial = tf.constant(val, shape=shape) temp = tf.Variable(initial) self.all_weights.append(temp) return temp def _get_weights_var(self, name, shape, decay=False): """Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor """ # Declare an initializer for this variable initializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32) # Declare variable (it is trainable by default) var = tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) if decay: # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size weight_decay = self.wd for x in shape: weight_decay /= x # Weight loss is L2 loss multiplied by weight decay weight_loss = tf.multiply(tf.nn.l2_loss(var), weight_decay, name='weight_loss') # Add weight loss for this variable to the global losses collection tf.add_to_collection('losses', weight_loss) self.all_weights.append(var) return var class SqueezeNet1: def __init__(self, use_cons_init): self.all_weights = [] self.debug_weights = [] self.use_cons_init = use_cons_init def inference(self, images): # conv1 conv1 = self.conv_layer(images, size=3, filters=64, stride=1, decay=False, name='conv1') # pool1 pool1 = self.pool_layer(conv1, size=3, stride=2, name='pool1') # fire2 fire2 = self.fire_layer(pool1, 32, 64, 64, decay=False, name='fire2') # fire3 fire3 = self.fire_layer(fire2, 32, 64, 64, decay=False, name='fire3') # pool2 pool2 = self.pool_layer(fire3, size=3, stride=2, name='pool2') # fire4 fire4 = self.fire_layer(pool2, 32, 128, 128, decay=False, name='fire4') # fire5 fire5 = self.fire_layer(fire4, 32, 128, 128, decay=False, name='fire5') # Final squeeze to get ten classes conv2 = self.conv_layer(fire5, size=1, filters=10, stride=1, decay=False, name='squeeze') # Average pooling on spatial dimensions predictions = self.avg_layer(conv2, name='avg_pool') return predictions def pool_layer(self, inputs, size, stride, name): with tf.variable_scope(name) as scope: outputs = tf.nn.max_pool(inputs, ksize=[1,size,size,1], strides=[1,stride,stride,1], padding='SAME', name=name) return outputs def fire_layer(self, inputs, s1x1, e1x1, e3x3, name, decay=False): with tf.variable_scope(name) as scope: # Squeeze sub-layer squeezed_inputs = self.conv_layer(inputs, size=1, filters=s1x1, stride=1, decay=decay, name='s1x1') # Expand 1x1 sub-layer e1x1_outputs = self.conv_layer(squeezed_inputs, size=1, filters=e1x1, stride=1, decay=decay, name='e1x1') # Expand 3x3 sub-layer e3x3_outputs = self.conv_layer(squeezed_inputs, size=3, filters=e3x3, stride=1, decay=decay, name='e3x3') # Concatenate outputs along the last dimension (channel) return tf.concat([e1x1_outputs, e3x3_outputs], 3) def avg_layer(self, inputs, name): w = inputs.get_shape().as_list()[1] h = inputs.get_shape().as_list()[2] c = inputs.get_shape().as_list()[3] with tf.variable_scope(name) as scope: # Use current spatial dimensions as Kernel size to produce a scalar avg = tf.nn.avg_pool(inputs, ksize=[1,w,h,1], strides=[1,1,1,1], padding='VALID', name=scope.name) # Reshape output to remove spatial dimensions reduced to one return tf.reshape(avg, shape=[-1,c]) def conv_layer(self, inputs, size, filters, stride, decay, name): channels = inputs.shape[3] shape = [size, size, channels, filters] with tf.variable_scope(name + '/conv') as scope: # For getting performance numbers, don't need to use the actual activations - just use constant activations if self.use_cons_init: weights = self.get_cons_variable(shape, 0.01) else: weights = self._get_weights_var('weights', shape=shape, decay=decay) biases = self.get_cons_variable([filters], 0.0) conv = tf.nn.conv2d(inputs, weights, strides=[1,stride,stride,1], padding='SAME') pre_activation = tf.nn.bias_add(conv, biases) outputs= tf.nn.relu(pre_activation, name=scope.name) return outputs def get_cons_variable(self, shape, val): initial = tf.constant(val, shape=shape) temp = tf.Variable(initial) self.all_weights.append(temp) return temp def _get_weights_var(self, name, shape, decay=False): """Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor """ # Declare an initializer for this variable initializer = tf.contrib.layers.xavier_initializer(uniform=False,dtype=tf.float32) # Declare variable (it is trainable by default) var = tf.get_variable(name=name, shape=shape, initializer=initializer, dtype=tf.float32) if decay: # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size weight_decay = self.wd for x in shape: weight_decay /= x # Weight loss is L2 loss multiplied by weight decay weight_loss = tf.multiply(tf.nn.l2_loss(var), weight_decay, name='weight_loss') # Add weight loss for this variable to the global losses collection tf.add_to_collection('losses', weight_loss) self.all_weights.append(var) return var def train(sqn, save_model_path): print('Starting train...') # Hyper parameters epochs = 1 batch_size = 128 keep_probability = 0.7 learning_rate = 0.001 n_batches = 5 #CIFAR10 dataset in the python version has 5 batches x = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x') y = tf.placeholder(tf.float32, shape=(None, 10), name='output_y') keep_prob = tf.placeholder(tf.float32, name='keep_prob') logits = sqn.inference(x) # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) l2Loss = sum(list(map(lambda x: tf.nn.l2_loss(x), sqn.all_weights))) beta = 1e-5 cost = cost + beta*l2Loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') valid_features, valid_labels = Util.load_preprocess_validation_data() testing_features, testing_labels = Util.load_preprocess_testing_data() print('Training now...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in Util.load_preprocess_training_batch(batch_i, batch_size): sess.run(optimizer, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability }) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') # Print stats loss = sess.run(cost, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability}) train_acc = sess.run(accuracy, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability}) valid_acc = sess.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob: keep_probability}) testing_acc = sess.run(accuracy, feed_dict={x: testing_features, y: testing_labels, keep_prob: keep_probability}) print('Loss: {:>10.4f} Train Acc: {:.6f} Validation Accuracy: {:.6f} Testing Acc: {:.6f}'.format(loss, train_acc, valid_acc, testing_acc)) if (epoch % 10 == 0): # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) #outputArgMax should only be used when findAcc is False def infer(sqn, sess, images, labels, restoreModelPath, findAccOrArgMaxOrPredVal=0, restoreWeights=True, onlysavegraph=False): assert(findAccOrArgMaxOrPredVal>=0 and findAccOrArgMaxOrPredVal<=2) if restoreWeights: assert(not(onlysavegraph)) if onlysavegraph: assert(findAccOrArgMaxOrPredVal==1) x = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name='input_x') if (not(onlysavegraph)): y = tf.placeholder(tf.int32, shape=(None, 10), name='output_y') logits = sqn.inference(x) if findAccOrArgMaxOrPredVal==0: correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') elif findAccOrArgMaxOrPredVal==1: logits = tf.argmax(logits, axis=1) elif findAccOrArgMaxOrPredVal==2: pass else: assert False print("Doing inference on ", len(images), " images.") feed_dict = {x: images} if not(onlysavegraph): feed_dict[y] = labels sess.run(tf.global_variables_initializer()) if onlysavegraph: output_tensor = None gg = tf.get_default_graph() for node in gg.as_graph_def().node: if node.name == 'ArgMax': output_tensor = gg.get_operation_by_name(node.name).outputs[0] optimized_graph_def = DumpTFMtData.save_graph_metadata(output_tensor, sess, feed_dict) return if restoreWeights: saver = tf.train.Saver(sqn.all_weights) saver.restore(sess, restoreModelPath) print("*************** Starting Prediction****************") start_time = time.time() if findAccOrArgMaxOrPredVal==0: predictions = sess.run([accuracy], feed_dict=feed_dict) else: predictions = sess.run([logits], feed_dict=feed_dict) end_time = time.time() print("*************** Done Prediction****************") duration = end_time - start_time print("Time taken in prediction : ", duration) print("Inference result = ", predictions) return predictions def getTrainedWeightsStrForm(sess, evalTensors, scalingFac): allWeightsStr = '' finalParameters = map(lambda x : sess.run(x), evalTensors) for curParameterVal in finalParameters: for xx in numpy.nditer(curParameterVal, order='C'): allWeightsStr += (str(int(xx * (1<<scalingFac))) + ' ') allWeightsStr += '\n\n' return allWeightsStr def findAndSaveCorrectTestImg(pred, features, actualLabels, correctImgFolder, incorrectImgFolder, textFolder, sess, sqn, scalingFac): #Run with findAcc=False and outputArgMax=False assert(len(pred)==1 and len(pred[0].shape)==2) modelPred = numpy.argmax(pred[0], axis=1) trueLabel = numpy.argmax(actualLabels, axis=1) print("Pred = ", pred) print("actualLabels = ", actualLabels) print("ModelPred = ", modelPred) print("TrueLabel = ", trueLabel) numImages = len(features) allWeightsStr = getTrainedWeightsStrForm(sess, sqn.all_weights, scalingFac) for ii in range(numImages): curImage = features[ii] if (modelPred[ii]==trueLabel[ii]): matplotlib.image.imsave(os.path.join(correctImgFolder, str(ii)+'-test.png'), curImage) else: matplotlib.image.imsave(os.path.join(incorrectImgFolder, str(ii)+'-test.png'), curImage) textInpFileName = os.path.join(textFolder, str(ii)+'-test-inp.txt') dumpCifar10Image(curImage, textInpFileName, scalingFac, 'w') with open(textInpFileName, 'a') as ff: ff.write(allWeightsStr) if (ii%10==0): print("Processing ", ii, " images done.") def main(): scalingFac = 12 findAccOrArgMaxOrPredVal = 0 restoreWeights = True onlysavegraph = False save_model_path = './TrainedModel/model' doTraining = False inp = None if (len(sys.argv) > 1): inp = sys.argv[1] if (inp == 'train'): doTraining = True elif (inp == 'savegraph'): findAccOrArgMaxOrPredVal = 1 restoreWeights = False onlysavegraph = True testing_features, testing_labels = Util.get_sample_points(2, 4555, 4556) elif (inp == 'testSingleTestInp'): testBatchInpNum = int(sys.argv[2]) findAccOrArgMaxOrPredVal = 1 restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1] elif (inp == 'testSingleTestInpAndSaveData'): testBatchInpNum = int(sys.argv[2]) findAccOrArgMaxOrPredVal = int(sys.argv[3]) restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[testBatchInpNum:testBatchInpNum+1], all_testing_labels[testBatchInpNum:testBatchInpNum+1] # testing_features, testing_labels = numpy.full((1,32,32,3),0.01), numpy.full((1,10),0.01) elif (inp == 'savegraphAndDataBatch'): batchNum = int(sys.argv[2]) imgStartNum = int(sys.argv[3]) imgEndNum = int(sys.argv[4]) findAccOrArgMaxOrPredVal = 1 restoreWeights = False onlysavegraph = True testing_features, testing_labels = Util.get_sample_points(batchNum, imgStartNum, imgEndNum) elif (inp == 'testBatchInp'): imgStartNum = int(sys.argv[2]) imgEndNum = int(sys.argv[3]) findAccOrArgMaxOrPredVal = 1 restoreWeights = True onlysavegraph = False all_testing_features, all_testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = all_testing_features[imgStartNum:imgEndNum], all_testing_labels[imgStartNum:imgEndNum] elif (inp == 'findAndSaveCorrectTestImg'): findAccOrArgMaxOrPredVal = 2 restoreWeights = True onlysavegraph = False testing_features, testing_labels = Util.load_preprocess_testing_data() testing_features, testing_labels = testing_features[0:100], testing_labels[0:100] else: if (inp != ""): print("WARNING : Given option didn't match any known value.") testing_features, testing_labels = Util.load_preprocess_testing_data() sqn = SqueezeNet1(use_cons_init=onlysavegraph) if doTraining: train(sqn, save_model_path) else: with tf.Session() as sess: pred = infer(sqn, sess, testing_features, testing_labels, save_model_path, findAccOrArgMaxOrPredVal=findAccOrArgMaxOrPredVal, restoreWeights=restoreWeights, onlysavegraph=onlysavegraph) if findAccOrArgMaxOrPredVal==1 and not(onlysavegraph): print("Actual labels = ", testing_labels) print("ArgMax in actual label : ", numpy.argmax(testing_labels, axis=1)) if (inp == 'findAndSaveCorrectTestImg'): print('Running ' + inp) print(pred[0].shape) findAndSaveCorrectTestImg(pred, testing_features, testing_labels, './testPred/CorrectImg/', './testPred/IncorrectImg/', './testPred/TestInputs/', sess, sqn, scalingFac) if (inp == 'savegraphAndDataBatch' or inp=='testSingleTestInpAndSaveData'): imgFileName = 'SqNet_CIFAR_img.inp' weightsFileName = 'SqNet_CIFAR_weights.inp' for ii,curFeature in enumerate(testing_features): if ii == 0 : DumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'w') else: DumpTFMtData.dumpImageDataInt(curFeature, imgFileName, scalingFac, 'a') DumpTFMtData.dumpTrainedWeightsInt(sess, sqn.all_weights, weightsFileName, scalingFac, 'w') if __name__ == '__main__': main()
en
0.79513
Authors: <NAME>. Copyright: Copyright (c) 2018 Microsoft Research 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. ** Parts of this code including the model itself, the training code and some other parts were taken from https://github.com/kaizouman/tensorsandbox/tree/master/cifar10/models/squeeze ** # conv1 # pool1 # fire2 # fire3 # pool2 # fire4 # fire5 # Final squeeze to get ten classes # Average pooling on spatial dimensions # Squeeze sub-layer # Expand 1x1 sub-layer # Expand 3x3 sub-layer # Concatenate outputs along the last dimension (channel) # Use current spatial dimensions as Kernel size to produce a scalar # Reshape output to remove spatial dimensions reduced to one Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor # Declare an initializer for this variable # Declare variable (it is trainable by default) # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size # Weight loss is L2 loss multiplied by weight decay # Add weight loss for this variable to the global losses collection # conv1 # pool1 # fire2 # fire3 # pool2 # fire4 # fire5 # Final squeeze to get ten classes # Average pooling on spatial dimensions # Squeeze sub-layer # Expand 1x1 sub-layer # Expand 3x3 sub-layer # Concatenate outputs along the last dimension (channel) # Use current spatial dimensions as Kernel size to produce a scalar # Reshape output to remove spatial dimensions reduced to one # For getting performance numbers, don't need to use the actual activations - just use constant activations Helper to create an initialized Variable with weight decay. The Variable is initialized using a normal distribution whose variance is provided by the xavier formula (ie inversely proportional to the number of inputs) Args: name: name of the tensor variable shape: the tensor shape decay: a boolean indicating if we apply decay to the tensor weights using a regularization loss Returns: Variable Tensor # Declare an initializer for this variable # Declare variable (it is trainable by default) # We apply a weight decay to this tensor var that is equal to the # model weight decay divided by the tensor size # Weight loss is L2 loss multiplied by weight decay # Add weight loss for this variable to the global losses collection # Hyper parameters #CIFAR10 dataset in the python version has 5 batches # Loss and Optimizer # Accuracy # Initializing the variables # Training cycle # Loop over all batches # Print stats # Save Model #outputArgMax should only be used when findAcc is False #Run with findAcc=False and outputArgMax=False # testing_features, testing_labels = numpy.full((1,32,32,3),0.01), numpy.full((1,10),0.01)
1.426519
1
cnn_models/help_fun.py
lijian10086/quantized_distillation
321
6630472
import torch import torch.nn as nn from torch.autograd import Variable import math import time import numpy as np import helpers.functions as mhf import random USE_CUDA = torch.cuda.is_available() def time_forward_pass(model, train_loader): model.eval() start_time = time.time() for idx_minibatch, data in enumerate(train_loader): # get the inputs inputs, labels = data inputs, labels = Variable(inputs, volatile=True), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) end_time = time.time() return end_time - start_time def evaluateModel(model, testLoader, fastEvaluation=True, maxExampleFastEvaluation=10000, k=1): 'if fastEvaluation is True, it will only check a subset of *maxExampleFastEvaluation* images of the test set' model.eval() correctClass = 0 totalNumExamples = 0 for idx_minibatch, data in enumerate(testLoader): # get the inputs inputs, labels = data inputs, labels = Variable(inputs, volatile=True), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) _, topk_predictions = outputs.topk(k, dim=1, largest=True, sorted=True) topk_predictions = topk_predictions.t() correct = topk_predictions.eq(labels.view(1, -1).expand_as(topk_predictions)) correctClass += correct.view(-1).float().sum(0, keepdim=True).data[0] totalNumExamples += len(labels) if fastEvaluation is True and totalNumExamples > maxExampleFastEvaluation: break return correctClass / totalNumExamples def forward_and_backward(model, batch, idx_batch, epoch, criterion=None, use_distillation_loss=False, teacher_model=None, temperature_distillation=2, ask_teacher_strategy='always', return_more_info=False): #TODO: return_more_info is just there for backward compatibility. A big refactoring is due here, and there one should #remove the return_more_info flag if criterion is None: criterion = nn.CrossEntropyLoss() if USE_CUDA: criterion = criterion.cuda() if use_distillation_loss is True and teacher_model is None: raise ValueError('To compute distillation loss you need to pass the teacher model') if not isinstance(ask_teacher_strategy, tuple): ask_teacher_strategy = (ask_teacher_strategy, ) inputs, labels = batch # wrap them in Variable inputs, labels = Variable(inputs), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() # forward + backward + optimize outputs = model(inputs) count_asked_teacher = 0 if use_distillation_loss: #if cutoff_entropy_value_distillation is not None, we use the distillation loss only on the examples #whose entropy is higher than the cutoff. weight_teacher_loss = 0.7 if 'entropy' in ask_teacher_strategy[0].lower(): prob_out = torch.nn.functional.softmax(outputs).data entropy = [mhf.get_entropy(prob_out[idx_b, :]) for idx_b in range(prob_out.size(0))] if ask_teacher_strategy[0].lower() == 'always': mask_distillation_loss = torch.ByteTensor([True]*outputs.size(0)) elif ask_teacher_strategy[0].lower() == 'cutoff_entropy': cutoff_entropy_value_distillation = ask_teacher_strategy[1] mask_distillation_loss = torch.ByteTensor([entr > cutoff_entropy_value_distillation for entr in entropy]) elif ask_teacher_strategy[0].lower() == 'random_entropy': max_entropy = math.log2(outputs.size(1)) #max possible entropy that happens with uniform distribution mask_distillation_loss = torch.ByteTensor([random.random() < entr/max_entropy for entr in entropy]) elif ask_teacher_strategy[0].lower() == 'incorrect_labels': _, predictions = outputs.max(dim=1) mask_distillation_loss = (predictions != labels).data.cpu() else: raise ValueError('ask_teacher_strategy is incorrectly formatted') index_distillation_loss = torch.arange(0, outputs.size(0))[mask_distillation_loss.view(-1, 1)].long() inverse_idx_distill_loss = torch.arange(0, outputs.size(0))[1-mask_distillation_loss.view(-1, 1)].long() if USE_CUDA: index_distillation_loss = index_distillation_loss.cuda() inverse_idx_distill_loss = inverse_idx_distill_loss.cuda() # this criterion is the distillation criterion according to Hinton's paper: # "Distilling the Knowledge in a Neural Network", Hinton et al. softmaxFunction, logSoftmaxFunction, KLDivLossFunction = nn.Softmax(dim=1), nn.LogSoftmax(dim=1), nn.KLDivLoss() if USE_CUDA: softmaxFunction, logSoftmaxFunction = softmaxFunction.cuda(), logSoftmaxFunction.cuda(), KLDivLossFunction = KLDivLossFunction.cuda() if index_distillation_loss.size() != torch.Size(): count_asked_teacher = index_distillation_loss.numel() # if index_distillation_loss is not empty volatile_inputs = Variable(inputs.data[index_distillation_loss, :], requires_grad=False) if USE_CUDA: volatile_inputs = volatile_inputs.cuda() outputsTeacher = teacher_model(volatile_inputs).detach() loss_masked = weight_teacher_loss * temperature_distillation**2 * KLDivLossFunction( logSoftmaxFunction(outputs[index_distillation_loss, :]/ temperature_distillation), softmaxFunction(outputsTeacher / temperature_distillation)) loss_masked += (1-weight_teacher_loss) * criterion(outputs[index_distillation_loss, :], labels[index_distillation_loss]) else: loss_masked = 0 if inverse_idx_distill_loss.size() != torch.Size(): #if inverse_idx_distill is not empty loss_normal = criterion(outputs[inverse_idx_distill_loss, :], labels[inverse_idx_distill_loss]) else: loss_normal = 0 loss = loss_masked + loss_normal else: loss = criterion(outputs, labels) loss.backward() if return_more_info: count_total = inputs.size(0) return loss.data[0], count_asked_teacher, count_total else: return loss.data[0] def add_gradient_noise(model, idx_batch, epoch, number_minibatches_per_epoch): # Adding random gaussian noise as in the paper "Adding gradient noise improves learning # for very deep networks" for p in model.parameters(): gaussianNoise = torch.Tensor(p.grad.size()) if USE_CUDA: gaussianNoise = gaussianNoise.cuda() # here nu = 0.01, gamma = 0.55, t is the minibatch count = epoch*total_length +idx_minibatch stdDev = (0.01 / (1 + epoch * number_minibatches_per_epoch + idx_batch) ** 0.55) ** 0.5 gaussianNoise.normal_(0, std=stdDev) p.grad.data.add_(gaussianNoise) class LearningRateScheduler: def __init__(self, initial_learning_rate, learning_rate_type='generic'): if learning_rate_type not in ('generic', 'cifar100', 'imagenet', 'quant_points_cifar100'): raise ValueError('Wrong learning rate type specified') self.initial_learning_rate = initial_learning_rate self.learning_rate_type = learning_rate_type self.current_learning_rate = initial_learning_rate #variables for the generic method self.old_validation_error = float('inf') self.epochs_since_validation_error_dropped = 0 self.total_number_of_learning_rate_halves = 0 self.epochs_to_wait_for_halving = 0 #variables for quant_points_cifar100 self.best_validation_error = float('inf') def update_learning_rate(self, epoch, validation_error): if self.learning_rate_type == 'cifar100': optim_factor = 0 if (epoch > 160): optim_factor = 3 elif (epoch > 120): optim_factor = 2 elif (epoch > 60): optim_factor = 1 new_learning_rate = self.initial_learning_rate * math.pow(0.2, optim_factor) self.current_learning_rate = new_learning_rate stop_training = False return new_learning_rate, stop_training if self.learning_rate_type == 'imagenet': new_learning_rate = self.initial_learning_rate * (0.1 ** (epoch // 30)) stop_training = False return new_learning_rate, stop_training if self.learning_rate_type in ('generic', 'quant_points_cifar100'): if self.learning_rate_type == 'generic': epoch_to_wait_before_reducing_rate = 10 epochs_to_wait_after_halving = 8 epoch_to_wait_before_stopping = 30 total_halves_before_stopping = 11 elif self.learning_rate_type == 'quant_points_cifar100': epoch_to_wait_before_reducing_rate = 2 epochs_to_wait_after_halving = 0 epoch_to_wait_before_stopping = float('inf') total_halves_before_stopping = float('inf') else: raise ValueError new_learning_rate = self.current_learning_rate stop_training = False # we have a 0.1% error band if validation_error + 0.001 < self.old_validation_error: self.old_validation_error = validation_error self.epochs_since_validation_error_dropped = 0 else: self.epochs_since_validation_error_dropped += 1 self.epochs_to_wait_for_halving = max(self.epochs_to_wait_for_halving - 1, 0) if self.epochs_since_validation_error_dropped >= epoch_to_wait_before_reducing_rate and \ self.epochs_to_wait_for_halving == 0: # if validation error does not drop for 10 epochs in a row, halve the learning rate # but don't halve it for at least 8 epochs after halving. self.epochs_to_wait_for_halving = epochs_to_wait_after_halving self.total_number_of_learning_rate_halves += 1 new_learning_rate = self.current_learning_rate / 2 self.current_learning_rate = new_learning_rate if self.epochs_since_validation_error_dropped > epoch_to_wait_before_stopping or \ self.total_number_of_learning_rate_halves > total_halves_before_stopping: # stop training if validation rate hasn't dropped in 30 epochs or if learning rates was halved 11 times already # i.e. it was reduced by 2048 times. stop_training = True return new_learning_rate, stop_training
import torch import torch.nn as nn from torch.autograd import Variable import math import time import numpy as np import helpers.functions as mhf import random USE_CUDA = torch.cuda.is_available() def time_forward_pass(model, train_loader): model.eval() start_time = time.time() for idx_minibatch, data in enumerate(train_loader): # get the inputs inputs, labels = data inputs, labels = Variable(inputs, volatile=True), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) end_time = time.time() return end_time - start_time def evaluateModel(model, testLoader, fastEvaluation=True, maxExampleFastEvaluation=10000, k=1): 'if fastEvaluation is True, it will only check a subset of *maxExampleFastEvaluation* images of the test set' model.eval() correctClass = 0 totalNumExamples = 0 for idx_minibatch, data in enumerate(testLoader): # get the inputs inputs, labels = data inputs, labels = Variable(inputs, volatile=True), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) _, topk_predictions = outputs.topk(k, dim=1, largest=True, sorted=True) topk_predictions = topk_predictions.t() correct = topk_predictions.eq(labels.view(1, -1).expand_as(topk_predictions)) correctClass += correct.view(-1).float().sum(0, keepdim=True).data[0] totalNumExamples += len(labels) if fastEvaluation is True and totalNumExamples > maxExampleFastEvaluation: break return correctClass / totalNumExamples def forward_and_backward(model, batch, idx_batch, epoch, criterion=None, use_distillation_loss=False, teacher_model=None, temperature_distillation=2, ask_teacher_strategy='always', return_more_info=False): #TODO: return_more_info is just there for backward compatibility. A big refactoring is due here, and there one should #remove the return_more_info flag if criterion is None: criterion = nn.CrossEntropyLoss() if USE_CUDA: criterion = criterion.cuda() if use_distillation_loss is True and teacher_model is None: raise ValueError('To compute distillation loss you need to pass the teacher model') if not isinstance(ask_teacher_strategy, tuple): ask_teacher_strategy = (ask_teacher_strategy, ) inputs, labels = batch # wrap them in Variable inputs, labels = Variable(inputs), Variable(labels) if USE_CUDA: inputs = inputs.cuda() labels = labels.cuda() # forward + backward + optimize outputs = model(inputs) count_asked_teacher = 0 if use_distillation_loss: #if cutoff_entropy_value_distillation is not None, we use the distillation loss only on the examples #whose entropy is higher than the cutoff. weight_teacher_loss = 0.7 if 'entropy' in ask_teacher_strategy[0].lower(): prob_out = torch.nn.functional.softmax(outputs).data entropy = [mhf.get_entropy(prob_out[idx_b, :]) for idx_b in range(prob_out.size(0))] if ask_teacher_strategy[0].lower() == 'always': mask_distillation_loss = torch.ByteTensor([True]*outputs.size(0)) elif ask_teacher_strategy[0].lower() == 'cutoff_entropy': cutoff_entropy_value_distillation = ask_teacher_strategy[1] mask_distillation_loss = torch.ByteTensor([entr > cutoff_entropy_value_distillation for entr in entropy]) elif ask_teacher_strategy[0].lower() == 'random_entropy': max_entropy = math.log2(outputs.size(1)) #max possible entropy that happens with uniform distribution mask_distillation_loss = torch.ByteTensor([random.random() < entr/max_entropy for entr in entropy]) elif ask_teacher_strategy[0].lower() == 'incorrect_labels': _, predictions = outputs.max(dim=1) mask_distillation_loss = (predictions != labels).data.cpu() else: raise ValueError('ask_teacher_strategy is incorrectly formatted') index_distillation_loss = torch.arange(0, outputs.size(0))[mask_distillation_loss.view(-1, 1)].long() inverse_idx_distill_loss = torch.arange(0, outputs.size(0))[1-mask_distillation_loss.view(-1, 1)].long() if USE_CUDA: index_distillation_loss = index_distillation_loss.cuda() inverse_idx_distill_loss = inverse_idx_distill_loss.cuda() # this criterion is the distillation criterion according to Hinton's paper: # "Distilling the Knowledge in a Neural Network", Hinton et al. softmaxFunction, logSoftmaxFunction, KLDivLossFunction = nn.Softmax(dim=1), nn.LogSoftmax(dim=1), nn.KLDivLoss() if USE_CUDA: softmaxFunction, logSoftmaxFunction = softmaxFunction.cuda(), logSoftmaxFunction.cuda(), KLDivLossFunction = KLDivLossFunction.cuda() if index_distillation_loss.size() != torch.Size(): count_asked_teacher = index_distillation_loss.numel() # if index_distillation_loss is not empty volatile_inputs = Variable(inputs.data[index_distillation_loss, :], requires_grad=False) if USE_CUDA: volatile_inputs = volatile_inputs.cuda() outputsTeacher = teacher_model(volatile_inputs).detach() loss_masked = weight_teacher_loss * temperature_distillation**2 * KLDivLossFunction( logSoftmaxFunction(outputs[index_distillation_loss, :]/ temperature_distillation), softmaxFunction(outputsTeacher / temperature_distillation)) loss_masked += (1-weight_teacher_loss) * criterion(outputs[index_distillation_loss, :], labels[index_distillation_loss]) else: loss_masked = 0 if inverse_idx_distill_loss.size() != torch.Size(): #if inverse_idx_distill is not empty loss_normal = criterion(outputs[inverse_idx_distill_loss, :], labels[inverse_idx_distill_loss]) else: loss_normal = 0 loss = loss_masked + loss_normal else: loss = criterion(outputs, labels) loss.backward() if return_more_info: count_total = inputs.size(0) return loss.data[0], count_asked_teacher, count_total else: return loss.data[0] def add_gradient_noise(model, idx_batch, epoch, number_minibatches_per_epoch): # Adding random gaussian noise as in the paper "Adding gradient noise improves learning # for very deep networks" for p in model.parameters(): gaussianNoise = torch.Tensor(p.grad.size()) if USE_CUDA: gaussianNoise = gaussianNoise.cuda() # here nu = 0.01, gamma = 0.55, t is the minibatch count = epoch*total_length +idx_minibatch stdDev = (0.01 / (1 + epoch * number_minibatches_per_epoch + idx_batch) ** 0.55) ** 0.5 gaussianNoise.normal_(0, std=stdDev) p.grad.data.add_(gaussianNoise) class LearningRateScheduler: def __init__(self, initial_learning_rate, learning_rate_type='generic'): if learning_rate_type not in ('generic', 'cifar100', 'imagenet', 'quant_points_cifar100'): raise ValueError('Wrong learning rate type specified') self.initial_learning_rate = initial_learning_rate self.learning_rate_type = learning_rate_type self.current_learning_rate = initial_learning_rate #variables for the generic method self.old_validation_error = float('inf') self.epochs_since_validation_error_dropped = 0 self.total_number_of_learning_rate_halves = 0 self.epochs_to_wait_for_halving = 0 #variables for quant_points_cifar100 self.best_validation_error = float('inf') def update_learning_rate(self, epoch, validation_error): if self.learning_rate_type == 'cifar100': optim_factor = 0 if (epoch > 160): optim_factor = 3 elif (epoch > 120): optim_factor = 2 elif (epoch > 60): optim_factor = 1 new_learning_rate = self.initial_learning_rate * math.pow(0.2, optim_factor) self.current_learning_rate = new_learning_rate stop_training = False return new_learning_rate, stop_training if self.learning_rate_type == 'imagenet': new_learning_rate = self.initial_learning_rate * (0.1 ** (epoch // 30)) stop_training = False return new_learning_rate, stop_training if self.learning_rate_type in ('generic', 'quant_points_cifar100'): if self.learning_rate_type == 'generic': epoch_to_wait_before_reducing_rate = 10 epochs_to_wait_after_halving = 8 epoch_to_wait_before_stopping = 30 total_halves_before_stopping = 11 elif self.learning_rate_type == 'quant_points_cifar100': epoch_to_wait_before_reducing_rate = 2 epochs_to_wait_after_halving = 0 epoch_to_wait_before_stopping = float('inf') total_halves_before_stopping = float('inf') else: raise ValueError new_learning_rate = self.current_learning_rate stop_training = False # we have a 0.1% error band if validation_error + 0.001 < self.old_validation_error: self.old_validation_error = validation_error self.epochs_since_validation_error_dropped = 0 else: self.epochs_since_validation_error_dropped += 1 self.epochs_to_wait_for_halving = max(self.epochs_to_wait_for_halving - 1, 0) if self.epochs_since_validation_error_dropped >= epoch_to_wait_before_reducing_rate and \ self.epochs_to_wait_for_halving == 0: # if validation error does not drop for 10 epochs in a row, halve the learning rate # but don't halve it for at least 8 epochs after halving. self.epochs_to_wait_for_halving = epochs_to_wait_after_halving self.total_number_of_learning_rate_halves += 1 new_learning_rate = self.current_learning_rate / 2 self.current_learning_rate = new_learning_rate if self.epochs_since_validation_error_dropped > epoch_to_wait_before_stopping or \ self.total_number_of_learning_rate_halves > total_halves_before_stopping: # stop training if validation rate hasn't dropped in 30 epochs or if learning rates was halved 11 times already # i.e. it was reduced by 2048 times. stop_training = True return new_learning_rate, stop_training
en
0.85981
# get the inputs # get the inputs #TODO: return_more_info is just there for backward compatibility. A big refactoring is due here, and there one should #remove the return_more_info flag # wrap them in Variable # forward + backward + optimize #if cutoff_entropy_value_distillation is not None, we use the distillation loss only on the examples #whose entropy is higher than the cutoff. #max possible entropy that happens with uniform distribution # this criterion is the distillation criterion according to Hinton's paper: # "Distilling the Knowledge in a Neural Network", Hinton et al. # if index_distillation_loss is not empty #if inverse_idx_distill is not empty # Adding random gaussian noise as in the paper "Adding gradient noise improves learning # for very deep networks" # here nu = 0.01, gamma = 0.55, t is the minibatch count = epoch*total_length +idx_minibatch #variables for the generic method #variables for quant_points_cifar100 # we have a 0.1% error band # if validation error does not drop for 10 epochs in a row, halve the learning rate # but don't halve it for at least 8 epochs after halving. # stop training if validation rate hasn't dropped in 30 epochs or if learning rates was halved 11 times already # i.e. it was reduced by 2048 times.
2.1504
2
src/Python/Visualization/NormalsDemo.py
cvandijck/VTKExamples
309
6630473
<filename>src/Python/Visualization/NormalsDemo.py #!/usr/bin/env python """ """ import vtk def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() polyData = ReadPolyData(fileName) # A renderer. renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d("White")) # Create background colors for each viewport. backgroundColors = list() backgroundColors.append(colors.GetColor3d("Cornsilk")) backgroundColors.append(colors.GetColor3d("NavajoWhite")) backgroundColors.append(colors.GetColor3d("Tan")) # Create a renderer for each view port. ren = list() ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren[0].SetViewport(0, 0, 1.0 / 3.0, 1) # Input ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1) # Normals (no split) ren[2].SetViewport(2.0 / 3.0, 0, 1, 1) # Normals (split) # Shared camera. camera = vtk.vtkCamera() normals = vtk.vtkPolyDataNormals() normals.SetInputData(polyData) normals.SetFeatureAngle(30.0) for i in range(0, 3): if i == 0: normals.ComputePointNormalsOff() elif i == 1: normals.ComputePointNormalsOn() normals.SplittingOff() else: normals.ComputePointNormalsOn() normals.SplittingOn() normals.Update() normalsPolyData = vtk.vtkPolyData() normalsPolyData.DeepCopy(normals.GetOutput()) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(normalsPolyData) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Peacock")) actor.GetProperty().SetDiffuse(.7) actor.GetProperty().SetSpecularPower(20) actor.GetProperty().SetSpecular(.5) # add the actor ren[i].SetBackground(backgroundColors[i]) ren[i].SetActiveCamera(camera) ren[i].AddActor(actor) # Render window. renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren[0]) renwin.AddRenderer(ren[1]) renwin.AddRenderer(ren[2]) # An interactor. interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) renwin.SetSize(900, 300) ren[0].GetActiveCamera().SetFocalPoint(0, 0, 0) ren[0].GetActiveCamera().SetPosition(1, 0, 0) ren[0].GetActiveCamera().SetViewUp(0, 0, -1) ren[0].ResetCamera() ren[0].GetActiveCamera().Azimuth(120) ren[0].GetActiveCamera().Elevation(30) ren[0].GetActiveCamera().Dolly(1.1) ren[0].ResetCameraClippingRange() renwin.Render() ren[0].ResetCamera() renwin.Render() # Start. interactor.Initialize() interactor.Start() def get_program_parameters(): import argparse description = 'Surface normal generation.' epilogue = ''' (a) Faceted model without normals. (b) Polygons must be consistently oriented to accurately compute normals. (c) Sharp edges are poorly represented using shared normals as shown on the corners of this model. (d) Normal generation with sharp edges split. ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('filename1', help='42400-IDGH.stl.') args = parser.parse_args() return args.filename1 def ReadPolyData(file_name): import os path, extension = os.path.splitext(file_name) extension = extension.lower() if extension == ".ply": reader = vtk.vtkPLYReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".vtp": reader = vtk.vtkXMLpoly_dataReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".obj": reader = vtk.vtkOBJReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".stl": reader = vtk.vtkSTLReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".vtk": reader = vtk.vtkpoly_dataReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".g": reader = vtk.vtkBYUReader() reader.SetGeometryFileName(file_name) reader.Update() poly_data = reader.GetOutput() else: # Return a None if the extension is unknown. poly_data = None return poly_data if __name__ == '__main__': main()
<filename>src/Python/Visualization/NormalsDemo.py #!/usr/bin/env python """ """ import vtk def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() polyData = ReadPolyData(fileName) # A renderer. renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d("White")) # Create background colors for each viewport. backgroundColors = list() backgroundColors.append(colors.GetColor3d("Cornsilk")) backgroundColors.append(colors.GetColor3d("NavajoWhite")) backgroundColors.append(colors.GetColor3d("Tan")) # Create a renderer for each view port. ren = list() ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren[0].SetViewport(0, 0, 1.0 / 3.0, 1) # Input ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1) # Normals (no split) ren[2].SetViewport(2.0 / 3.0, 0, 1, 1) # Normals (split) # Shared camera. camera = vtk.vtkCamera() normals = vtk.vtkPolyDataNormals() normals.SetInputData(polyData) normals.SetFeatureAngle(30.0) for i in range(0, 3): if i == 0: normals.ComputePointNormalsOff() elif i == 1: normals.ComputePointNormalsOn() normals.SplittingOff() else: normals.ComputePointNormalsOn() normals.SplittingOn() normals.Update() normalsPolyData = vtk.vtkPolyData() normalsPolyData.DeepCopy(normals.GetOutput()) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(normalsPolyData) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Peacock")) actor.GetProperty().SetDiffuse(.7) actor.GetProperty().SetSpecularPower(20) actor.GetProperty().SetSpecular(.5) # add the actor ren[i].SetBackground(backgroundColors[i]) ren[i].SetActiveCamera(camera) ren[i].AddActor(actor) # Render window. renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren[0]) renwin.AddRenderer(ren[1]) renwin.AddRenderer(ren[2]) # An interactor. interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) renwin.SetSize(900, 300) ren[0].GetActiveCamera().SetFocalPoint(0, 0, 0) ren[0].GetActiveCamera().SetPosition(1, 0, 0) ren[0].GetActiveCamera().SetViewUp(0, 0, -1) ren[0].ResetCamera() ren[0].GetActiveCamera().Azimuth(120) ren[0].GetActiveCamera().Elevation(30) ren[0].GetActiveCamera().Dolly(1.1) ren[0].ResetCameraClippingRange() renwin.Render() ren[0].ResetCamera() renwin.Render() # Start. interactor.Initialize() interactor.Start() def get_program_parameters(): import argparse description = 'Surface normal generation.' epilogue = ''' (a) Faceted model without normals. (b) Polygons must be consistently oriented to accurately compute normals. (c) Sharp edges are poorly represented using shared normals as shown on the corners of this model. (d) Normal generation with sharp edges split. ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('filename1', help='42400-IDGH.stl.') args = parser.parse_args() return args.filename1 def ReadPolyData(file_name): import os path, extension = os.path.splitext(file_name) extension = extension.lower() if extension == ".ply": reader = vtk.vtkPLYReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".vtp": reader = vtk.vtkXMLpoly_dataReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".obj": reader = vtk.vtkOBJReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".stl": reader = vtk.vtkSTLReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".vtk": reader = vtk.vtkpoly_dataReader() reader.SetFileName(file_name) reader.Update() poly_data = reader.GetOutput() elif extension == ".g": reader = vtk.vtkBYUReader() reader.SetGeometryFileName(file_name) reader.Update() poly_data = reader.GetOutput() else: # Return a None if the extension is unknown. poly_data = None return poly_data if __name__ == '__main__': main()
en
0.808083
#!/usr/bin/env python # A renderer. # Create background colors for each viewport. # Create a renderer for each view port. # Input # Normals (no split) # Normals (split) # Shared camera. # mapper # add the actor # Render window. # An interactor. # Start. (a) Faceted model without normals. (b) Polygons must be consistently oriented to accurately compute normals. (c) Sharp edges are poorly represented using shared normals as shown on the corners of this model. (d) Normal generation with sharp edges split. # Return a None if the extension is unknown.
2.566708
3
src/api/pdi/domain/operation/DataOperation.py
ahmetcagriakca/pythondataintegrator
1
6630474
<filename>src/api/pdi/domain/operation/DataOperation.py from typing import List from pdip.data import Entity from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.orm import relationship from pdi.domain.base import Base from pdi.domain.base.operation.DataOperationBase import DataOperationBase from pdi.domain.operation.DataOperationContact import DataOperationContact from pdi.domain.operation.DataOperationIntegration import DataOperationIntegration from pdi.domain.operation.DataOperationJob import DataOperationJob class DataOperation(DataOperationBase, Entity, Base): __tablename__ = "DataOperation" __table_args__ = {"schema": "Operation"} DefinitionId = Column(Integer, ForeignKey('Operation.Definition.Id')) Name = Column(String(100), index=True, unique=False, nullable=False) Definition = relationship("Definition", back_populates="DataOperations") DataOperationJobs: List[DataOperationJob] = relationship("DataOperationJob", back_populates="DataOperation") Integrations: List[DataOperationIntegration] = relationship("DataOperationIntegration", back_populates="DataOperation") Contacts: List[DataOperationContact] = relationship("DataOperationContact", back_populates="DataOperation")
<filename>src/api/pdi/domain/operation/DataOperation.py from typing import List from pdip.data import Entity from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.orm import relationship from pdi.domain.base import Base from pdi.domain.base.operation.DataOperationBase import DataOperationBase from pdi.domain.operation.DataOperationContact import DataOperationContact from pdi.domain.operation.DataOperationIntegration import DataOperationIntegration from pdi.domain.operation.DataOperationJob import DataOperationJob class DataOperation(DataOperationBase, Entity, Base): __tablename__ = "DataOperation" __table_args__ = {"schema": "Operation"} DefinitionId = Column(Integer, ForeignKey('Operation.Definition.Id')) Name = Column(String(100), index=True, unique=False, nullable=False) Definition = relationship("Definition", back_populates="DataOperations") DataOperationJobs: List[DataOperationJob] = relationship("DataOperationJob", back_populates="DataOperation") Integrations: List[DataOperationIntegration] = relationship("DataOperationIntegration", back_populates="DataOperation") Contacts: List[DataOperationContact] = relationship("DataOperationContact", back_populates="DataOperation")
none
1
2.252126
2
model/qalexnet.py
XueYue404/QNN
0
6630475
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import seaborn as sns import math from torch.utils.data import DataLoader from torch.autograd import Function #从本项目中import from model.quant import QuantConv2d from model.quant import QuantLinear from model.quant import QuantGrad ''' AlexNet分类器,用于CIFAR10 用法: network = AlexNet(isquant=True,bitA=4,bitW=8) ''' class AlexNet(nn.Module): def __init__(self,isquant=True,bitA=8,bitW=16,bitG=16): super(AlexNet, self).__init__() self.isquant = isquant self.bitA = bitA self.bitW = bitW self.bitG = bitG if self.isquant == True: self.cnn = nn.Sequential( # 卷积层1,3通道输入,96个卷积核,核大小7*7,步长2,填充2 # 经过该层图像大小变为32-7+2*2 / 2 +1,15*15 # 经3*3最大池化,2步长,图像变为15-3 / 2 + 1, 7*7 QuantConv2d(3, 96, 7, 2, 2,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), # 卷积层2,96输入通道,256个卷积核,核大小5*5,步长1,填充2 # 经过该层图像变为7-5+2*2 / 1 + 1,7*7 # 经3*3最大池化,2步长,图像变为7-3 / 2 + 1, 3*3 QuantConv2d(96, 256, 5, 1, 2,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), # 卷积层3,256输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(256, 384, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), # 卷积层3,384输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(384, 384, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), # 卷积层3,384输入通道,256个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(384, 256, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True) ) self.fc = nn.Sequential( # 256个feature,每个feature 3*3 QuantLinear(256*3*3, 1024,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(), QuantLinear(1024, 512,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(), QuantLinear(512, 10,a_bits=self.bitA,w_bits=self.bitW) ) else: self.cnn = nn.Sequential( nn.Conv2d(3, 96, 7, 2, 2), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), nn.Conv2d(96, 256, 5, 1, 2), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), nn.Conv2d(256, 384, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(384, 384, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, 3, 1, 1), nn.ReLU(inplace=True) ) self.fc = nn.Sequential( nn.Linear(256*3*3, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 10) ) def forward(self, x): x = self.cnn(x) x = x.view(x.size()[0], -1) x = self.fc(x) return x
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import seaborn as sns import math from torch.utils.data import DataLoader from torch.autograd import Function #从本项目中import from model.quant import QuantConv2d from model.quant import QuantLinear from model.quant import QuantGrad ''' AlexNet分类器,用于CIFAR10 用法: network = AlexNet(isquant=True,bitA=4,bitW=8) ''' class AlexNet(nn.Module): def __init__(self,isquant=True,bitA=8,bitW=16,bitG=16): super(AlexNet, self).__init__() self.isquant = isquant self.bitA = bitA self.bitW = bitW self.bitG = bitG if self.isquant == True: self.cnn = nn.Sequential( # 卷积层1,3通道输入,96个卷积核,核大小7*7,步长2,填充2 # 经过该层图像大小变为32-7+2*2 / 2 +1,15*15 # 经3*3最大池化,2步长,图像变为15-3 / 2 + 1, 7*7 QuantConv2d(3, 96, 7, 2, 2,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), # 卷积层2,96输入通道,256个卷积核,核大小5*5,步长1,填充2 # 经过该层图像变为7-5+2*2 / 1 + 1,7*7 # 经3*3最大池化,2步长,图像变为7-3 / 2 + 1, 3*3 QuantConv2d(96, 256, 5, 1, 2,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), # 卷积层3,256输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(256, 384, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), # 卷积层3,384输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(384, 384, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True), # 卷积层3,384输入通道,256个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 QuantConv2d(384, 256, 3, 1, 1,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(inplace=True) ) self.fc = nn.Sequential( # 256个feature,每个feature 3*3 QuantLinear(256*3*3, 1024,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(), QuantLinear(1024, 512,a_bits=self.bitA,w_bits=self.bitW), QuantGrad(bitG = self.bitG), nn.ReLU(), QuantLinear(512, 10,a_bits=self.bitA,w_bits=self.bitW) ) else: self.cnn = nn.Sequential( nn.Conv2d(3, 96, 7, 2, 2), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), nn.Conv2d(96, 256, 5, 1, 2), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 0), nn.Conv2d(256, 384, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(384, 384, 3, 1, 1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, 3, 1, 1), nn.ReLU(inplace=True) ) self.fc = nn.Sequential( nn.Linear(256*3*3, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 10) ) def forward(self, x): x = self.cnn(x) x = x.view(x.size()[0], -1) x = self.fc(x) return x
zh
0.729663
#从本项目中import AlexNet分类器,用于CIFAR10 用法: network = AlexNet(isquant=True,bitA=4,bitW=8) # 卷积层1,3通道输入,96个卷积核,核大小7*7,步长2,填充2 # 经过该层图像大小变为32-7+2*2 / 2 +1,15*15 # 经3*3最大池化,2步长,图像变为15-3 / 2 + 1, 7*7 # 卷积层2,96输入通道,256个卷积核,核大小5*5,步长1,填充2 # 经过该层图像变为7-5+2*2 / 1 + 1,7*7 # 经3*3最大池化,2步长,图像变为7-3 / 2 + 1, 3*3 # 卷积层3,256输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 # 卷积层3,384输入通道,384个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 # 卷积层3,384输入通道,256个卷积核,核大小3*3,步长1,填充1 # 经过该层图像变为3-3+2*1 / 1 + 1,3*3 # 256个feature,每个feature 3*3
2.779815
3
scitbx/suffixtree/test/tst_single.py
rimmartin/cctbx_project
0
6630476
from __future__ import division from scitbx import suffixtree from scitbx.suffixtree import single import unittest class TestWord(unittest.TestCase): def test_single_word(self): word = single.word() ld = word.length_descriptor() self.assertEqual( len( word ), 0 ) self.assertEqual( ld(), 0 ) self.assertEqual( list( word.substring( 0, ld() ) ), [] ) c1 = object() c2 = object() word.append( c1 ) self.assertEqual( len( word ), 1 ) self.assertEqual( ld(), 1 ) self.assertEqual( word[0], c1 ) self.assertEqual( list( word ), [ c1 ] ) word.append( c2 ) self.assertEqual( len( word ), 2 ) self.assertEqual( ld(), 2 ) self.assertEqual( word[0], c1 ) self.assertEqual( word[1], c2 ) self.assertEqual( list( word ), [ c1, c2 ] ) self.assertEqual( list( word.substring( 0, 0 ) ), [] ) self.assertEqual( list( word.substring( 0, 1 ) ), [ c1 ] ) self.assertEqual( list( word.substring( 0, 2 ) ), [ c1, c2 ] ) self.assertEqual( list( word.substring( 1, 1 ) ), [] ) self.assertEqual( list( word.substring( 1, 2 ) ), [ c2 ] ) class TestEdge(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.branch = single.edge.branch( start = 1, stop = 2 ) self.word = single.word() self.leaf = single.edge.leaf( start = 4, length = self.word.length_descriptor(), label = 6 ) def test_root(self): self.assertEqual( self.root.start, 0 ) self.assertRaises( RuntimeError, setattr, self.root, "start", 1 ) self.assertEqual( self.root.stop, 0 ) self.assertRaises( RuntimeError, getattr, self.root, "label" ) self.assertRaises( RuntimeError, getattr, self.root, "parent" ) self.assertRaises( RuntimeError, setattr, self.root, "parent", self.branch ) self.assertRaises( RuntimeError, getattr, self.root, "suffix" ) self.assertRaises( RuntimeError, setattr, self.root, "suffix", self.branch ) self.assertTrue( self.root.is_root() ) self.assertFalse( self.root.is_leaf() ) self.assertTrue( self.root.is_empty() ) self.assertEqual( self.root.keys(), [] ) self.assertFalse( 1 in self.root ) self.assertTrue( 1 not in self.root ) self.assertRaises( KeyError, self.root.__getitem__, 1 ) self.root[1] = self.branch self.root[1] = self.leaf self.root[2] = self.branch self.assertFalse( self.root.is_empty() ) self.assertEqual( set( self.root.keys() ), set( [ 1, 2 ] ) ) self.assertEqual( set( self.root.values() ), set( [ self.branch, self.leaf ] ) ) self.assertTrue( 1 in self.root ) self.assertTrue( 2 in self.root ) self.assertEqual( self.root[1], self.leaf ) self.assertEqual( self.root[2], self.branch ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) self.assertEqual( self.root, cr ) self.assertEqual( hash( self.root ), hash( cr ) ) self.assertNotEqual( single.edge.root(), cr ) self.assertEqual( cr.start, 0 ) self.assertEqual( cr.stop, 0 ) self.assertRaises( RuntimeError, getattr, cr, "label" ) self.assertRaises( RuntimeError, getattr, cr, "parent" ) self.assertRaises( RuntimeError, getattr, cr, "suffix" ) self.assertTrue( cr.is_root() ) self.assertFalse( cr.is_leaf() ) self.assertTrue( cr.is_empty() ) self.assertEqual( cr.keys(), [] ) self.assertEqual( cr.values(), [] ) self.assertFalse( 1 in cr ) self.assertTrue( 1 not in cr ) self.assertRaises( KeyError, cr.__getitem__, 1 ) def test_branch(self): self.assertEqual( self.branch.start, 1 ) self.branch.start = 3 self.assertEqual( self.branch.start, 3 ) self.assertEqual( self.branch.stop, 2 ) self.assertRaises( RuntimeError, getattr, self.branch, "label" ) self.assertEqual( self.branch.parent, None ) self.branch.parent = self.root self.assertTrue( isinstance( self.branch.parent, single.edge ) ) self.assertEqual( self.branch.parent, self.root ) self.assertEqual( self.branch.suffix, None ) self.branch.suffix = self.root self.assertTrue( isinstance( self.branch.parent, single.edge ) ) self.assertEqual( self.branch.suffix, self.root ) self.assertFalse( self.branch.is_root() ) self.assertFalse( self.branch.is_leaf() ) self.assertTrue( self.branch.is_empty() ) self.assertEqual( self.branch.keys(), [] ) self.assertFalse( 1 in self.branch ) self.assertTrue( 1 not in self.branch ) self.assertRaises( KeyError, self.branch.__getitem__, 1 ) self.branch[1] = self.root self.branch[1] = self.leaf self.branch[2] = self.root self.assertFalse( self.branch.is_empty() ) self.assertEqual( set( self.branch.keys() ), set( [ 1, 2 ] ) ) self.assertEqual( set( self.branch.values() ), set( [ self.root, self.leaf ] ) ) self.assertTrue( 1 in self.branch ) self.assertTrue( 2 in self.branch ) self.assertEqual( self.branch[1], self.leaf ) self.assertEqual( self.branch[2], self.root ) def test_const_branch(self): cb = single.const_edge.from_edge( self.branch ) self.assertEqual( self.branch, cb ) self.assertEqual( hash( self.branch ), hash( cb ) ) self.assertNotEqual( single.edge.branch( start = 1, stop = 2 ), cb ) self.assertEqual( cb.start, 1 ) self.assertEqual( cb.stop, 2 ) self.assertRaises( RuntimeError, getattr, cb, "label" ) self.assertEqual( cb.parent, None ) self.branch.parent = self.root self.assertTrue( isinstance( cb.parent, single.const_edge ) ) self.assertEqual( cb.parent, self.root ) self.assertEqual( cb.suffix, None ) self.branch.suffix = self.root self.assertTrue( isinstance( cb.suffix, single.const_edge ) ) self.assertEqual( cb.suffix, self.root ) self.assertFalse( cb.is_root() ) self.assertFalse( cb.is_leaf() ) self.assertTrue( cb.is_empty() ) self.assertEqual( cb.keys(), [] ) self.assertEqual( cb.values(), [] ) self.assertFalse( 1 in cb ) self.assertTrue( 1 not in cb ) self.assertRaises( KeyError, cb.__getitem__, 1 ) def test_leaf(self): self.assertEqual( self.leaf.start, 4 ) self.leaf.start = 5 self.assertEqual( self.leaf.start, 5 ) ld = self.word.length_descriptor() self.assertEqual( self.leaf.stop, ld() ) self.word.append( 1 ) self.word.append( 2 ) self.assertEqual( self.leaf.stop, ld() ) self.assertEqual( self.leaf.label, 6 ) self.assertEqual( self.leaf.parent, None ) self.leaf.parent = self.root self.assertTrue( isinstance( self.leaf.parent, single.edge ) ) self.assertEqual( self.leaf.parent, self.root ) self.assertRaises( RuntimeError, getattr, self.leaf, "suffix" ) self.assertRaises( RuntimeError, setattr, self.leaf, "suffix", self.branch ) self.assertFalse( self.leaf.is_root() ) self.assertTrue( self.leaf.is_leaf() ) self.assertTrue( self.leaf.is_empty() ) self.assertEqual( self.leaf.keys(), [] ) self.assertEqual( self.leaf.values(), [] ) self.assertFalse( 1 in self.leaf ) self.assertTrue( 1 not in self.leaf ) self.assertRaises( RuntimeError, self.leaf.__getitem__, 1 ) self.assertRaises( RuntimeError, self.leaf.__setitem__, 1, self.root ) def test_const_leaf(self): cl = single.const_edge.from_edge( self.leaf ) self.assertEqual( self.leaf, cl ) self.assertEqual( hash( self.leaf ), hash( cl ) ) self.assertNotEqual( single.edge.leaf( start = 4, length = self.word.length_descriptor(), label = 6 ), cl, ) self.assertEqual( cl.start, 4 ) ld = self.word.length_descriptor() self.assertEqual( cl.stop, ld() ) self.word.append( 1 ) self.word.append( 2 ) self.assertEqual( cl.stop, ld() ) self.assertEqual( cl.label, 6 ) self.assertEqual( cl.parent, None ) self.leaf.parent = self.root self.assertTrue( isinstance( cl.parent, single.const_edge ) ) self.assertEqual( cl.parent, self.root ) self.assertRaises( RuntimeError, getattr, cl, "suffix" ) self.assertFalse( cl.is_root() ) self.assertTrue( cl.is_leaf() ) self.assertTrue( cl.is_empty() ) self.assertEqual( cl.keys(), [] ) self.assertEqual( cl.values(), [] ) self.assertFalse( 1 in cl ) self.assertTrue( 1 not in cl ) self.assertRaises( KeyError, cl.__getitem__, 1 ) class TestPreOrder(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.word = single.word() length = self.word.length_descriptor() self.edge_named = { "r_b1": single.edge.branch( start = 0, stop = 3 ), "r_b2": single.edge.branch( start = 1, stop = 3 ), "r_l1": single.edge.leaf( start = 4, length = length, label = 6 ), "r_b1_b1": single.edge.branch( start = 2, stop = 3 ), "r_b1_l1": single.edge.leaf( start = 4, length = length, label = 7 ), "r_b1_b1_l1": single.edge.leaf( start = 4, length = length, label = 8 ), "r_b1_b1_l2": single.edge.leaf( start = 4, length = length, label = 9 ), "r_b2_l1": single.edge.leaf( start = 4, length = length, label = 10 ), "r_b2_l2": single.edge.leaf( start = 4, length = length, label = 11 ), } self.root[ "r_b1" ] = self.edge_named[ "r_b1" ] self.root[ "r_b2" ] = self.edge_named[ "r_b2" ] self.root[ "r_l1" ] = self.edge_named[ "r_l1" ] self.edge_named[ "r_b1" ][ "r_b1_b1" ] = self.edge_named[ "r_b1_b1" ] self.edge_named[ "r_b1" ][ "r_b1_l1" ] = self.edge_named[ "r_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l1" ] = self.edge_named[ "r_b1_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l2" ] = self.edge_named[ "r_b1_b1_l2" ] self.edge_named[ "r_b2" ][ "r_b2_l1" ] = self.edge_named[ "r_b2_l1" ] self.edge_named[ "r_b2" ][ "r_b2_l2" ] = self.edge_named[ "r_b2_l2" ] def test_single_root(self): root = single.edge.root() res = list( root.preorder_iteration() ) self.assertEqual( res, [ root ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cr = single.const_edge.from_edge( root ) res = list( cr.preorder_iteration() ) self.assertEqual( res, [ cr ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_branch(self): branch = single.edge.branch( start = 0, stop = 3 ) res = list( branch.preorder_iteration() ) self.assertEqual( res, [ branch ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cb = single.const_edge.from_edge( branch ) res = list( cb.preorder_iteration() ) self.assertEqual( res, [ cb ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_leaf(self): word = single.word() leaf = single.edge.leaf( start = 4, length = word.length_descriptor(), label = 6 ) res = list( leaf.preorder_iteration() ) self.assertEqual( res, [ leaf ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cl = single.const_edge.from_edge( leaf ) res = list( cl.preorder_iteration() ) self.assertEqual( res, [ cl ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def check_leaf_named(self, result, leafname): self.assertEqual( result[0], self.edge_named[ leafname ] ) result.pop( 0 ) def check_r_b2(self, result): action_for = { "r_b2_l1": lambda result: self.check_leaf_named( result, "r_b2_l1" ), "r_b2_l2": lambda result: self.check_leaf_named( result, "r_b2_l2" ), } self.assertEqual( result[0], self.edge_named[ "r_b2" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b2" ].keys(): action_for[ key ]( result = result ) def check_r_b1_b1(self, result): action_for = { "r_b1_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_b1_l1" ), "r_b1_b1_l2": lambda result: self.check_leaf_named( result, "r_b1_b1_l2" ), } self.assertEqual( result[0], self.edge_named[ "r_b1_b1" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b1_b1" ].keys(): action_for[ key ]( result = result ) def check_r_b1(self, result): action_for = { "r_b1_b1": self.check_r_b1_b1, "r_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_l1" ), } self.assertEqual( result[0], self.edge_named[ "r_b1" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b1" ].keys(): action_for[ key ]( result = result ) def check_root(self, result): action_for = { "r_b1": self.check_r_b1, "r_b2": self.check_r_b2, "r_l1": lambda result: self.check_leaf_named( result, "r_l1" ), } self.assertEqual( result[0], self.root ) result.pop( 0 ) for key in self.root.keys(): action_for[ key ]( result = result ) def test_r_b2(self): result = list( self.edge_named[ "r_b2" ].preorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b2( result ) self.assertEqual( result, [] ) def test_r_b1_b1(self): result = list( self.edge_named[ "r_b1_b1" ].preorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b1_b1( result ) self.assertEqual( result, [] ) def test_r_b1(self): result = list( self.edge_named[ "r_b1" ].preorder_iteration() ) self.assertEqual( len( result ), 5 ) self.check_r_b1( result ) self.assertEqual( result, [] ) def test_root(self): result = list( self.root.preorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) result = list( cr.preorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.const_edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) class TestPostOrder(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.word = single.word() length = self.word.length_descriptor() self.edge_named = { "r_b1": single.edge.branch( start = 0, stop = 3 ), "r_b2": single.edge.branch( start = 1, stop = 3 ), "r_l1": single.edge.leaf( start = 4, length = length, label = 6 ), "r_b1_b1": single.edge.branch( start = 2, stop = 3 ), "r_b1_l1": single.edge.leaf( start = 4, length = length, label = 7 ), "r_b1_b1_l1": single.edge.leaf( start = 4, length = length, label = 8 ), "r_b1_b1_l2": single.edge.leaf( start = 4, length = length, label = 9 ), "r_b2_l1": single.edge.leaf( start = 4, length = length, label = 10 ), "r_b2_l2": single.edge.leaf( start = 4, length = length, label = 11 ), } self.root[ "r_b1" ] = self.edge_named[ "r_b1" ] self.root[ "r_b2" ] = self.edge_named[ "r_b2" ] self.root[ "r_l1" ] = self.edge_named[ "r_l1" ] self.edge_named[ "r_b1" ][ "r_b1_b1" ] = self.edge_named[ "r_b1_b1" ] self.edge_named[ "r_b1" ][ "r_b1_l1" ] = self.edge_named[ "r_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l1" ] = self.edge_named[ "r_b1_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l2" ] = self.edge_named[ "r_b1_b1_l2" ] self.edge_named[ "r_b2" ][ "r_b2_l1" ] = self.edge_named[ "r_b2_l1" ] self.edge_named[ "r_b2" ][ "r_b2_l2" ] = self.edge_named[ "r_b2_l2" ] def test_single_root(self): root = single.edge.root() res = list( root.postorder_iteration() ) self.assertEqual( res, [ root ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cr = single.const_edge.from_edge( root ) res = list( cr.postorder_iteration() ) self.assertEqual( res, [ cr ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_branch(self): branch = single.edge.branch( start = 0, stop = 3 ) res = list( branch.postorder_iteration() ) self.assertEqual( res, [ branch ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cb = single.const_edge.from_edge( branch ) res = list( cb.postorder_iteration() ) self.assertEqual( res, [ cb ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_leaf(self): word = single.word() leaf = single.edge.leaf( start = 4, length = word.length_descriptor(), label = 6 ) res = list( leaf.postorder_iteration() ) self.assertEqual( res, [ leaf ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cl = single.const_edge.from_edge( leaf ) res = list( cl.postorder_iteration() ) self.assertEqual( res, [ cl ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def check_leaf_named(self, result, leafname): self.assertEqual( result[0], self.edge_named[ leafname ] ) result.pop( 0 ) def check_r_b2(self, result): action_for = { "r_b2_l1": lambda result: self.check_leaf_named( result, "r_b2_l1" ), "r_b2_l2": lambda result: self.check_leaf_named( result, "r_b2_l2" ), } for key in self.edge_named[ "r_b2" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b2" ] ) result.pop( 0 ) def check_r_b1_b1(self, result): action_for = { "r_b1_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_b1_l1" ), "r_b1_b1_l2": lambda result: self.check_leaf_named( result, "r_b1_b1_l2" ), } for key in self.edge_named[ "r_b1_b1" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b1_b1" ] ) result.pop( 0 ) def check_r_b1(self, result): action_for = { "r_b1_b1": self.check_r_b1_b1, "r_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_l1" ), } for key in self.edge_named[ "r_b1" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b1" ] ) result.pop( 0 ) def check_root(self, result): action_for = { "r_b1": self.check_r_b1, "r_b2": self.check_r_b2, "r_l1": lambda result: self.check_leaf_named( result, "r_l1" ), } for key in self.root.keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.root ) result.pop( 0 ) def test_r_b2(self): result = list( self.edge_named[ "r_b2" ].postorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b2( result ) self.assertEqual( result, [] ) def test_r_b1_b1(self): result = list( self.edge_named[ "r_b1_b1" ].postorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b1_b1( result ) self.assertEqual( result, [] ) def test_r_b1(self): result = list( self.edge_named[ "r_b1" ].postorder_iteration() ) self.assertEqual( len( result ), 5 ) self.check_r_b1( result ) self.assertEqual( result, [] ) def test_root(self): result = list( self.root.postorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) result = list( cr.postorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.const_edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) class TestTree(unittest.TestCase): def test_tree(self): tree = single.tree() self.assertEqual( tree.in_construction, False ) w = tree.word self.assertTrue( isinstance( w, single.word ) ) self.assertEqual( w.length_descriptor()(), 0 ) r = tree.root self.assertTrue( isinstance( r, single.const_edge ) ) self.assertEqual( r.keys(), [] ) def test_ukkonen1(self): tree = single.tree() self.assertEqual( tree.in_construction, False ) builder = single.ukkonen( tree ) self.assertTrue( tree.in_construction ) self.assertTrue( builder.is_attached ) self.assertTrue( builder.is_valid ) self.assertRaises( RuntimeError, single.ukkonen, tree ) builder.detach() self.assertFalse( builder.is_attached ) self.assertTrue( builder.is_valid ) self.assertFalse( tree.in_construction ) self.assertRaises( RuntimeError, builder.append, "a" ) def test_ukkonen2(self): tree = single.tree() builder = single.ukkonen( tree ) builder.append( glyph = "a" ) self.assertTrue( builder.is_valid ) builder.append( glyph = "n" ) self.assertTrue( builder.is_valid ) builder.detach() self.assertFalse( builder.is_attached ) self.assertFalse( tree.in_construction ) builder = single.ukkonen( tree ) self.assertTrue( builder.is_valid ) self.assertTrue( builder.is_attached ) self.assertTrue( tree.in_construction ) builder.append( glyph = "a" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "n" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "a" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "s" ) self.assertTrue( builder.is_valid ) builder.detach() self.assertFalse( builder.is_attached ) self.assertFalse( tree.in_construction ) builder = single.ukkonen( tree ) self.assertTrue( builder.is_valid ) self.assertTrue( builder.is_attached ) self.assertTrue( tree.in_construction ) builder.append( glyph = "$" ) self.assertTrue( builder.is_valid ) builder.detach() root = tree.root self.assertTrue( root.is_root() ) self.assertEqual( set( root.keys() ), set( [ "a", "n", "s", "$" ] ) ) b_a = root[ "a" ] self.assertFalse( b_a.is_root() ) self.assertFalse( b_a.is_leaf() ) self.assertEqual( b_a.start, 0 ) self.assertEqual( b_a.stop, 1 ) self.assertEqual( set( b_a.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_a.parent, root ) b_a_n = b_a[ "n" ] self.assertFalse( b_a_n.is_root() ) self.assertFalse( b_a_n.is_leaf() ) self.assertEqual( b_a_n.start, 1 ) self.assertEqual( b_a_n.stop, 3 ) self.assertEqual( set( b_a_n.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_a_n.parent, b_a ) b_a_n_n = b_a_n[ "n" ] self.assertTrue( b_a_n_n.is_leaf() ) self.assertEqual( b_a_n_n.start, 3 ) self.assertEqual( b_a_n_n.stop, 7 ) self.assertEqual( b_a_n_n.label, 0 ) self.assertEqual( b_a_n_n.parent, b_a_n ) b_a_n_s = b_a_n[ "s" ] self.assertTrue( b_a_n_s.is_leaf() ) self.assertEqual( b_a_n_s.start, 5 ) self.assertEqual( b_a_n_s.stop, 7 ) self.assertEqual( b_a_n_s.label, 2 ) self.assertEqual( b_a_n_s.parent, b_a_n ) b_a_s = b_a[ "s" ] self.assertTrue( b_a_s.is_leaf() ) self.assertEqual( b_a_s.start, 5 ) self.assertEqual( b_a_s.stop, 7 ) self.assertEqual( b_a_s.label, 4 ) self.assertEqual( b_a_s.parent, b_a ) b_n = root[ "n" ] self.assertFalse( b_n.is_root() ) self.assertFalse( b_n.is_leaf() ) self.assertEqual( b_n.start, 1 ) self.assertEqual( b_n.stop, 3 ) self.assertEqual( set( b_n.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_n.parent, root ) b_n_n = b_n[ "n" ] self.assertTrue( b_n_n.is_leaf() ) self.assertEqual( b_n_n.start, 3 ) self.assertEqual( b_n_n.stop, 7 ) self.assertEqual( b_n_n.label, 1 ) self.assertEqual( b_n_n.parent, b_n ) b_n_s = b_n[ "s" ] self.assertTrue( b_n_s.is_leaf() ) self.assertEqual( b_n_s.start, 5 ) self.assertEqual( b_n_s.stop, 7 ) self.assertEqual( b_n_s.label, 3 ) self.assertEqual( b_n_s.parent, b_n ) b_s = root[ "s" ] self.assertTrue( b_s.is_leaf() ) self.assertEqual( b_s.start, 5 ) self.assertEqual( b_s.stop, 7 ) self.assertEqual( b_s.label, 5 ) self.assertEqual( b_s.parent, root ) b_dl = root[ "$" ] self.assertTrue( b_dl.is_leaf() ) self.assertEqual( b_dl.start, 6 ) self.assertEqual( b_dl.stop, 7 ) self.assertEqual( b_dl.label, 6 ) self.assertEqual( b_dl.parent, root ) self.assertEqual( b_a.suffix, root ) self.assertEqual( b_n.suffix, b_a ) self.assertEqual( b_a_n.suffix, b_n ) class TestMatchingStatistics(unittest.TestCase): def test(self): tree = single.tree() result = list( single.matching_statistics( tree, list( "ABC" ) ) ) self.assertEqual( result, [ ( 0, ( tree.root, 0 ) ) ] * 3 ) builder = single.ukkonen( tree = tree ) for c in "TTAGC$": builder.append( c ) self.assertRaises( RuntimeError, single.matching_statistics, tree, list() ); builder.detach() root = tree.root branch_t = root[ "T" ] leaf_0 = branch_t[ "T" ] leaf_1 = branch_t[ "A" ] leaf_2 = root[ "A" ] leaf_3 = root[ "G" ] leaf_4 = root[ "C" ] result = list( single.matching_statistics( tree, [] ) ) self.assertEqual( result, [] ) result = list( single.matching_statistics( tree, list( "QTTATTATTTAGCQWTTAGFK" ) ) ) self.assertEqual( result, [ ( 0, ( root, 0 ) ), ( 3, ( leaf_0, 3 ) ), ( 2, ( leaf_1, 3 ) ), ( 1, ( leaf_2, 3 ) ), ( 3, ( leaf_0, 3 ) ), ( 2, ( leaf_1, 3 ) ), ( 1, ( leaf_2, 3 ) ), ( 2, ( leaf_0, 2 ) ), ( 5, ( leaf_0, 5 ) ), ( 4, ( leaf_1, 5 ) ), ( 3, ( leaf_2, 5 ) ), ( 2, ( leaf_3, 5 ) ), ( 1, ( leaf_4, 5 ) ), ( 0, ( root, 0 ) ), ( 0, ( root, 0 ) ), ( 4, ( leaf_0, 4 ) ), ( 3, ( leaf_1, 4 ) ), ( 2, ( leaf_2, 4 ) ), ( 1, ( leaf_3, 4 ) ), ( 0, ( root, 0 ) ), ( 0, ( root, 0 ) ), ] ) class TestLeafIndices(unittest.TestCase): def test(self): tree = single.tree() result = list( single.matching_statistics( tree, list( "ABC" ) ) ) self.assertEqual( result, [ ( 0, ( tree.root, 0 ) ) ] * 3 ) builder = single.ukkonen( tree = tree ) for c in "TTAGC$": builder.append( c ) builder.detach() leaf_indices_below = suffixtree.calculate_leaf_indices( root = tree.root ) root = tree.root branch_t = root[ "T" ] leaf_0 = branch_t[ "T" ] leaf_1 = branch_t[ "A" ] leaf_2 = root[ "A" ] leaf_3 = root[ "G" ] leaf_4 = root[ "C" ] leaf_5 = root[ "$" ] self.assertEqual( leaf_indices_below[ leaf_0 ], [ 0 ] ) self.assertEqual( leaf_indices_below[ leaf_1 ], [ 1 ] ) self.assertEqual( leaf_indices_below[ leaf_2 ], [ 2 ] ) self.assertEqual( leaf_indices_below[ leaf_3 ], [ 3 ] ) self.assertEqual( leaf_indices_below[ leaf_4 ], [ 4 ] ) self.assertEqual( leaf_indices_below[ leaf_5 ], [ 5 ] ) self.assertEqual( sorted( leaf_indices_below[ branch_t ] ), [ 0, 1 ] ) self.assertEqual( sorted( leaf_indices_below[ root ] ), range( 6 ) ) suite_word = unittest.TestLoader().loadTestsFromTestCase( TestWord ) suite_edge = unittest.TestLoader().loadTestsFromTestCase( TestEdge ) suite_preorder = unittest.TestLoader().loadTestsFromTestCase( TestPreOrder ) suite_postorder = unittest.TestLoader().loadTestsFromTestCase( TestPostOrder ) suite_tree = unittest.TestLoader().loadTestsFromTestCase( TestTree ) suite_msi = unittest.TestLoader().loadTestsFromTestCase( TestMatchingStatistics ) suite_leaf_indices = unittest.TestLoader().loadTestsFromTestCase( TestLeafIndices ) alltests = unittest.TestSuite( [ suite_word, suite_edge, suite_preorder, suite_postorder, suite_tree, suite_msi, suite_leaf_indices, ] ) def load_tests(loader, tests, pattern): return alltests if __name__ == "__main__": unittest.TextTestRunner( verbosity = 2 ).run( alltests )
from __future__ import division from scitbx import suffixtree from scitbx.suffixtree import single import unittest class TestWord(unittest.TestCase): def test_single_word(self): word = single.word() ld = word.length_descriptor() self.assertEqual( len( word ), 0 ) self.assertEqual( ld(), 0 ) self.assertEqual( list( word.substring( 0, ld() ) ), [] ) c1 = object() c2 = object() word.append( c1 ) self.assertEqual( len( word ), 1 ) self.assertEqual( ld(), 1 ) self.assertEqual( word[0], c1 ) self.assertEqual( list( word ), [ c1 ] ) word.append( c2 ) self.assertEqual( len( word ), 2 ) self.assertEqual( ld(), 2 ) self.assertEqual( word[0], c1 ) self.assertEqual( word[1], c2 ) self.assertEqual( list( word ), [ c1, c2 ] ) self.assertEqual( list( word.substring( 0, 0 ) ), [] ) self.assertEqual( list( word.substring( 0, 1 ) ), [ c1 ] ) self.assertEqual( list( word.substring( 0, 2 ) ), [ c1, c2 ] ) self.assertEqual( list( word.substring( 1, 1 ) ), [] ) self.assertEqual( list( word.substring( 1, 2 ) ), [ c2 ] ) class TestEdge(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.branch = single.edge.branch( start = 1, stop = 2 ) self.word = single.word() self.leaf = single.edge.leaf( start = 4, length = self.word.length_descriptor(), label = 6 ) def test_root(self): self.assertEqual( self.root.start, 0 ) self.assertRaises( RuntimeError, setattr, self.root, "start", 1 ) self.assertEqual( self.root.stop, 0 ) self.assertRaises( RuntimeError, getattr, self.root, "label" ) self.assertRaises( RuntimeError, getattr, self.root, "parent" ) self.assertRaises( RuntimeError, setattr, self.root, "parent", self.branch ) self.assertRaises( RuntimeError, getattr, self.root, "suffix" ) self.assertRaises( RuntimeError, setattr, self.root, "suffix", self.branch ) self.assertTrue( self.root.is_root() ) self.assertFalse( self.root.is_leaf() ) self.assertTrue( self.root.is_empty() ) self.assertEqual( self.root.keys(), [] ) self.assertFalse( 1 in self.root ) self.assertTrue( 1 not in self.root ) self.assertRaises( KeyError, self.root.__getitem__, 1 ) self.root[1] = self.branch self.root[1] = self.leaf self.root[2] = self.branch self.assertFalse( self.root.is_empty() ) self.assertEqual( set( self.root.keys() ), set( [ 1, 2 ] ) ) self.assertEqual( set( self.root.values() ), set( [ self.branch, self.leaf ] ) ) self.assertTrue( 1 in self.root ) self.assertTrue( 2 in self.root ) self.assertEqual( self.root[1], self.leaf ) self.assertEqual( self.root[2], self.branch ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) self.assertEqual( self.root, cr ) self.assertEqual( hash( self.root ), hash( cr ) ) self.assertNotEqual( single.edge.root(), cr ) self.assertEqual( cr.start, 0 ) self.assertEqual( cr.stop, 0 ) self.assertRaises( RuntimeError, getattr, cr, "label" ) self.assertRaises( RuntimeError, getattr, cr, "parent" ) self.assertRaises( RuntimeError, getattr, cr, "suffix" ) self.assertTrue( cr.is_root() ) self.assertFalse( cr.is_leaf() ) self.assertTrue( cr.is_empty() ) self.assertEqual( cr.keys(), [] ) self.assertEqual( cr.values(), [] ) self.assertFalse( 1 in cr ) self.assertTrue( 1 not in cr ) self.assertRaises( KeyError, cr.__getitem__, 1 ) def test_branch(self): self.assertEqual( self.branch.start, 1 ) self.branch.start = 3 self.assertEqual( self.branch.start, 3 ) self.assertEqual( self.branch.stop, 2 ) self.assertRaises( RuntimeError, getattr, self.branch, "label" ) self.assertEqual( self.branch.parent, None ) self.branch.parent = self.root self.assertTrue( isinstance( self.branch.parent, single.edge ) ) self.assertEqual( self.branch.parent, self.root ) self.assertEqual( self.branch.suffix, None ) self.branch.suffix = self.root self.assertTrue( isinstance( self.branch.parent, single.edge ) ) self.assertEqual( self.branch.suffix, self.root ) self.assertFalse( self.branch.is_root() ) self.assertFalse( self.branch.is_leaf() ) self.assertTrue( self.branch.is_empty() ) self.assertEqual( self.branch.keys(), [] ) self.assertFalse( 1 in self.branch ) self.assertTrue( 1 not in self.branch ) self.assertRaises( KeyError, self.branch.__getitem__, 1 ) self.branch[1] = self.root self.branch[1] = self.leaf self.branch[2] = self.root self.assertFalse( self.branch.is_empty() ) self.assertEqual( set( self.branch.keys() ), set( [ 1, 2 ] ) ) self.assertEqual( set( self.branch.values() ), set( [ self.root, self.leaf ] ) ) self.assertTrue( 1 in self.branch ) self.assertTrue( 2 in self.branch ) self.assertEqual( self.branch[1], self.leaf ) self.assertEqual( self.branch[2], self.root ) def test_const_branch(self): cb = single.const_edge.from_edge( self.branch ) self.assertEqual( self.branch, cb ) self.assertEqual( hash( self.branch ), hash( cb ) ) self.assertNotEqual( single.edge.branch( start = 1, stop = 2 ), cb ) self.assertEqual( cb.start, 1 ) self.assertEqual( cb.stop, 2 ) self.assertRaises( RuntimeError, getattr, cb, "label" ) self.assertEqual( cb.parent, None ) self.branch.parent = self.root self.assertTrue( isinstance( cb.parent, single.const_edge ) ) self.assertEqual( cb.parent, self.root ) self.assertEqual( cb.suffix, None ) self.branch.suffix = self.root self.assertTrue( isinstance( cb.suffix, single.const_edge ) ) self.assertEqual( cb.suffix, self.root ) self.assertFalse( cb.is_root() ) self.assertFalse( cb.is_leaf() ) self.assertTrue( cb.is_empty() ) self.assertEqual( cb.keys(), [] ) self.assertEqual( cb.values(), [] ) self.assertFalse( 1 in cb ) self.assertTrue( 1 not in cb ) self.assertRaises( KeyError, cb.__getitem__, 1 ) def test_leaf(self): self.assertEqual( self.leaf.start, 4 ) self.leaf.start = 5 self.assertEqual( self.leaf.start, 5 ) ld = self.word.length_descriptor() self.assertEqual( self.leaf.stop, ld() ) self.word.append( 1 ) self.word.append( 2 ) self.assertEqual( self.leaf.stop, ld() ) self.assertEqual( self.leaf.label, 6 ) self.assertEqual( self.leaf.parent, None ) self.leaf.parent = self.root self.assertTrue( isinstance( self.leaf.parent, single.edge ) ) self.assertEqual( self.leaf.parent, self.root ) self.assertRaises( RuntimeError, getattr, self.leaf, "suffix" ) self.assertRaises( RuntimeError, setattr, self.leaf, "suffix", self.branch ) self.assertFalse( self.leaf.is_root() ) self.assertTrue( self.leaf.is_leaf() ) self.assertTrue( self.leaf.is_empty() ) self.assertEqual( self.leaf.keys(), [] ) self.assertEqual( self.leaf.values(), [] ) self.assertFalse( 1 in self.leaf ) self.assertTrue( 1 not in self.leaf ) self.assertRaises( RuntimeError, self.leaf.__getitem__, 1 ) self.assertRaises( RuntimeError, self.leaf.__setitem__, 1, self.root ) def test_const_leaf(self): cl = single.const_edge.from_edge( self.leaf ) self.assertEqual( self.leaf, cl ) self.assertEqual( hash( self.leaf ), hash( cl ) ) self.assertNotEqual( single.edge.leaf( start = 4, length = self.word.length_descriptor(), label = 6 ), cl, ) self.assertEqual( cl.start, 4 ) ld = self.word.length_descriptor() self.assertEqual( cl.stop, ld() ) self.word.append( 1 ) self.word.append( 2 ) self.assertEqual( cl.stop, ld() ) self.assertEqual( cl.label, 6 ) self.assertEqual( cl.parent, None ) self.leaf.parent = self.root self.assertTrue( isinstance( cl.parent, single.const_edge ) ) self.assertEqual( cl.parent, self.root ) self.assertRaises( RuntimeError, getattr, cl, "suffix" ) self.assertFalse( cl.is_root() ) self.assertTrue( cl.is_leaf() ) self.assertTrue( cl.is_empty() ) self.assertEqual( cl.keys(), [] ) self.assertEqual( cl.values(), [] ) self.assertFalse( 1 in cl ) self.assertTrue( 1 not in cl ) self.assertRaises( KeyError, cl.__getitem__, 1 ) class TestPreOrder(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.word = single.word() length = self.word.length_descriptor() self.edge_named = { "r_b1": single.edge.branch( start = 0, stop = 3 ), "r_b2": single.edge.branch( start = 1, stop = 3 ), "r_l1": single.edge.leaf( start = 4, length = length, label = 6 ), "r_b1_b1": single.edge.branch( start = 2, stop = 3 ), "r_b1_l1": single.edge.leaf( start = 4, length = length, label = 7 ), "r_b1_b1_l1": single.edge.leaf( start = 4, length = length, label = 8 ), "r_b1_b1_l2": single.edge.leaf( start = 4, length = length, label = 9 ), "r_b2_l1": single.edge.leaf( start = 4, length = length, label = 10 ), "r_b2_l2": single.edge.leaf( start = 4, length = length, label = 11 ), } self.root[ "r_b1" ] = self.edge_named[ "r_b1" ] self.root[ "r_b2" ] = self.edge_named[ "r_b2" ] self.root[ "r_l1" ] = self.edge_named[ "r_l1" ] self.edge_named[ "r_b1" ][ "r_b1_b1" ] = self.edge_named[ "r_b1_b1" ] self.edge_named[ "r_b1" ][ "r_b1_l1" ] = self.edge_named[ "r_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l1" ] = self.edge_named[ "r_b1_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l2" ] = self.edge_named[ "r_b1_b1_l2" ] self.edge_named[ "r_b2" ][ "r_b2_l1" ] = self.edge_named[ "r_b2_l1" ] self.edge_named[ "r_b2" ][ "r_b2_l2" ] = self.edge_named[ "r_b2_l2" ] def test_single_root(self): root = single.edge.root() res = list( root.preorder_iteration() ) self.assertEqual( res, [ root ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cr = single.const_edge.from_edge( root ) res = list( cr.preorder_iteration() ) self.assertEqual( res, [ cr ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_branch(self): branch = single.edge.branch( start = 0, stop = 3 ) res = list( branch.preorder_iteration() ) self.assertEqual( res, [ branch ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cb = single.const_edge.from_edge( branch ) res = list( cb.preorder_iteration() ) self.assertEqual( res, [ cb ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_leaf(self): word = single.word() leaf = single.edge.leaf( start = 4, length = word.length_descriptor(), label = 6 ) res = list( leaf.preorder_iteration() ) self.assertEqual( res, [ leaf ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cl = single.const_edge.from_edge( leaf ) res = list( cl.preorder_iteration() ) self.assertEqual( res, [ cl ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def check_leaf_named(self, result, leafname): self.assertEqual( result[0], self.edge_named[ leafname ] ) result.pop( 0 ) def check_r_b2(self, result): action_for = { "r_b2_l1": lambda result: self.check_leaf_named( result, "r_b2_l1" ), "r_b2_l2": lambda result: self.check_leaf_named( result, "r_b2_l2" ), } self.assertEqual( result[0], self.edge_named[ "r_b2" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b2" ].keys(): action_for[ key ]( result = result ) def check_r_b1_b1(self, result): action_for = { "r_b1_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_b1_l1" ), "r_b1_b1_l2": lambda result: self.check_leaf_named( result, "r_b1_b1_l2" ), } self.assertEqual( result[0], self.edge_named[ "r_b1_b1" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b1_b1" ].keys(): action_for[ key ]( result = result ) def check_r_b1(self, result): action_for = { "r_b1_b1": self.check_r_b1_b1, "r_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_l1" ), } self.assertEqual( result[0], self.edge_named[ "r_b1" ] ) result.pop( 0 ) for key in self.edge_named[ "r_b1" ].keys(): action_for[ key ]( result = result ) def check_root(self, result): action_for = { "r_b1": self.check_r_b1, "r_b2": self.check_r_b2, "r_l1": lambda result: self.check_leaf_named( result, "r_l1" ), } self.assertEqual( result[0], self.root ) result.pop( 0 ) for key in self.root.keys(): action_for[ key ]( result = result ) def test_r_b2(self): result = list( self.edge_named[ "r_b2" ].preorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b2( result ) self.assertEqual( result, [] ) def test_r_b1_b1(self): result = list( self.edge_named[ "r_b1_b1" ].preorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b1_b1( result ) self.assertEqual( result, [] ) def test_r_b1(self): result = list( self.edge_named[ "r_b1" ].preorder_iteration() ) self.assertEqual( len( result ), 5 ) self.check_r_b1( result ) self.assertEqual( result, [] ) def test_root(self): result = list( self.root.preorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) result = list( cr.preorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.const_edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) class TestPostOrder(unittest.TestCase): def setUp(self): self.root = single.edge.root() self.word = single.word() length = self.word.length_descriptor() self.edge_named = { "r_b1": single.edge.branch( start = 0, stop = 3 ), "r_b2": single.edge.branch( start = 1, stop = 3 ), "r_l1": single.edge.leaf( start = 4, length = length, label = 6 ), "r_b1_b1": single.edge.branch( start = 2, stop = 3 ), "r_b1_l1": single.edge.leaf( start = 4, length = length, label = 7 ), "r_b1_b1_l1": single.edge.leaf( start = 4, length = length, label = 8 ), "r_b1_b1_l2": single.edge.leaf( start = 4, length = length, label = 9 ), "r_b2_l1": single.edge.leaf( start = 4, length = length, label = 10 ), "r_b2_l2": single.edge.leaf( start = 4, length = length, label = 11 ), } self.root[ "r_b1" ] = self.edge_named[ "r_b1" ] self.root[ "r_b2" ] = self.edge_named[ "r_b2" ] self.root[ "r_l1" ] = self.edge_named[ "r_l1" ] self.edge_named[ "r_b1" ][ "r_b1_b1" ] = self.edge_named[ "r_b1_b1" ] self.edge_named[ "r_b1" ][ "r_b1_l1" ] = self.edge_named[ "r_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l1" ] = self.edge_named[ "r_b1_b1_l1" ] self.edge_named[ "r_b1_b1" ][ "r_b1_b1_l2" ] = self.edge_named[ "r_b1_b1_l2" ] self.edge_named[ "r_b2" ][ "r_b2_l1" ] = self.edge_named[ "r_b2_l1" ] self.edge_named[ "r_b2" ][ "r_b2_l2" ] = self.edge_named[ "r_b2_l2" ] def test_single_root(self): root = single.edge.root() res = list( root.postorder_iteration() ) self.assertEqual( res, [ root ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cr = single.const_edge.from_edge( root ) res = list( cr.postorder_iteration() ) self.assertEqual( res, [ cr ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_branch(self): branch = single.edge.branch( start = 0, stop = 3 ) res = list( branch.postorder_iteration() ) self.assertEqual( res, [ branch ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cb = single.const_edge.from_edge( branch ) res = list( cb.postorder_iteration() ) self.assertEqual( res, [ cb ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def test_single_leaf(self): word = single.word() leaf = single.edge.leaf( start = 4, length = word.length_descriptor(), label = 6 ) res = list( leaf.postorder_iteration() ) self.assertEqual( res, [ leaf ] ) self.assertTrue( isinstance( res[0], single.edge ) ) cl = single.const_edge.from_edge( leaf ) res = list( cl.postorder_iteration() ) self.assertEqual( res, [ cl ] ) self.assertTrue( isinstance( res[0], single.const_edge ) ) def check_leaf_named(self, result, leafname): self.assertEqual( result[0], self.edge_named[ leafname ] ) result.pop( 0 ) def check_r_b2(self, result): action_for = { "r_b2_l1": lambda result: self.check_leaf_named( result, "r_b2_l1" ), "r_b2_l2": lambda result: self.check_leaf_named( result, "r_b2_l2" ), } for key in self.edge_named[ "r_b2" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b2" ] ) result.pop( 0 ) def check_r_b1_b1(self, result): action_for = { "r_b1_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_b1_l1" ), "r_b1_b1_l2": lambda result: self.check_leaf_named( result, "r_b1_b1_l2" ), } for key in self.edge_named[ "r_b1_b1" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b1_b1" ] ) result.pop( 0 ) def check_r_b1(self, result): action_for = { "r_b1_b1": self.check_r_b1_b1, "r_b1_l1": lambda result: self.check_leaf_named( result, "r_b1_l1" ), } for key in self.edge_named[ "r_b1" ].keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.edge_named[ "r_b1" ] ) result.pop( 0 ) def check_root(self, result): action_for = { "r_b1": self.check_r_b1, "r_b2": self.check_r_b2, "r_l1": lambda result: self.check_leaf_named( result, "r_l1" ), } for key in self.root.keys(): action_for[ key ]( result = result ) self.assertEqual( result[0], self.root ) result.pop( 0 ) def test_r_b2(self): result = list( self.edge_named[ "r_b2" ].postorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b2( result ) self.assertEqual( result, [] ) def test_r_b1_b1(self): result = list( self.edge_named[ "r_b1_b1" ].postorder_iteration() ) self.assertEqual( len( result ), 3 ) self.check_r_b1_b1( result ) self.assertEqual( result, [] ) def test_r_b1(self): result = list( self.edge_named[ "r_b1" ].postorder_iteration() ) self.assertEqual( len( result ), 5 ) self.check_r_b1( result ) self.assertEqual( result, [] ) def test_root(self): result = list( self.root.postorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) def test_const_root(self): cr = single.const_edge.from_edge( self.root ) result = list( cr.postorder_iteration() ) self.assertEqual( len( result ), 10 ) self.assertTrue( all( isinstance( e, single.const_edge ) for e in result ) ) self.check_root( result ) self.assertEqual( result, [] ) class TestTree(unittest.TestCase): def test_tree(self): tree = single.tree() self.assertEqual( tree.in_construction, False ) w = tree.word self.assertTrue( isinstance( w, single.word ) ) self.assertEqual( w.length_descriptor()(), 0 ) r = tree.root self.assertTrue( isinstance( r, single.const_edge ) ) self.assertEqual( r.keys(), [] ) def test_ukkonen1(self): tree = single.tree() self.assertEqual( tree.in_construction, False ) builder = single.ukkonen( tree ) self.assertTrue( tree.in_construction ) self.assertTrue( builder.is_attached ) self.assertTrue( builder.is_valid ) self.assertRaises( RuntimeError, single.ukkonen, tree ) builder.detach() self.assertFalse( builder.is_attached ) self.assertTrue( builder.is_valid ) self.assertFalse( tree.in_construction ) self.assertRaises( RuntimeError, builder.append, "a" ) def test_ukkonen2(self): tree = single.tree() builder = single.ukkonen( tree ) builder.append( glyph = "a" ) self.assertTrue( builder.is_valid ) builder.append( glyph = "n" ) self.assertTrue( builder.is_valid ) builder.detach() self.assertFalse( builder.is_attached ) self.assertFalse( tree.in_construction ) builder = single.ukkonen( tree ) self.assertTrue( builder.is_valid ) self.assertTrue( builder.is_attached ) self.assertTrue( tree.in_construction ) builder.append( glyph = "a" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "n" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "a" ) self.assertFalse( builder.is_valid ) self.assertRaises( builder.detach ) builder.append( glyph = "s" ) self.assertTrue( builder.is_valid ) builder.detach() self.assertFalse( builder.is_attached ) self.assertFalse( tree.in_construction ) builder = single.ukkonen( tree ) self.assertTrue( builder.is_valid ) self.assertTrue( builder.is_attached ) self.assertTrue( tree.in_construction ) builder.append( glyph = "$" ) self.assertTrue( builder.is_valid ) builder.detach() root = tree.root self.assertTrue( root.is_root() ) self.assertEqual( set( root.keys() ), set( [ "a", "n", "s", "$" ] ) ) b_a = root[ "a" ] self.assertFalse( b_a.is_root() ) self.assertFalse( b_a.is_leaf() ) self.assertEqual( b_a.start, 0 ) self.assertEqual( b_a.stop, 1 ) self.assertEqual( set( b_a.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_a.parent, root ) b_a_n = b_a[ "n" ] self.assertFalse( b_a_n.is_root() ) self.assertFalse( b_a_n.is_leaf() ) self.assertEqual( b_a_n.start, 1 ) self.assertEqual( b_a_n.stop, 3 ) self.assertEqual( set( b_a_n.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_a_n.parent, b_a ) b_a_n_n = b_a_n[ "n" ] self.assertTrue( b_a_n_n.is_leaf() ) self.assertEqual( b_a_n_n.start, 3 ) self.assertEqual( b_a_n_n.stop, 7 ) self.assertEqual( b_a_n_n.label, 0 ) self.assertEqual( b_a_n_n.parent, b_a_n ) b_a_n_s = b_a_n[ "s" ] self.assertTrue( b_a_n_s.is_leaf() ) self.assertEqual( b_a_n_s.start, 5 ) self.assertEqual( b_a_n_s.stop, 7 ) self.assertEqual( b_a_n_s.label, 2 ) self.assertEqual( b_a_n_s.parent, b_a_n ) b_a_s = b_a[ "s" ] self.assertTrue( b_a_s.is_leaf() ) self.assertEqual( b_a_s.start, 5 ) self.assertEqual( b_a_s.stop, 7 ) self.assertEqual( b_a_s.label, 4 ) self.assertEqual( b_a_s.parent, b_a ) b_n = root[ "n" ] self.assertFalse( b_n.is_root() ) self.assertFalse( b_n.is_leaf() ) self.assertEqual( b_n.start, 1 ) self.assertEqual( b_n.stop, 3 ) self.assertEqual( set( b_n.keys() ), set( [ "n", "s" ] ) ) self.assertEqual( b_n.parent, root ) b_n_n = b_n[ "n" ] self.assertTrue( b_n_n.is_leaf() ) self.assertEqual( b_n_n.start, 3 ) self.assertEqual( b_n_n.stop, 7 ) self.assertEqual( b_n_n.label, 1 ) self.assertEqual( b_n_n.parent, b_n ) b_n_s = b_n[ "s" ] self.assertTrue( b_n_s.is_leaf() ) self.assertEqual( b_n_s.start, 5 ) self.assertEqual( b_n_s.stop, 7 ) self.assertEqual( b_n_s.label, 3 ) self.assertEqual( b_n_s.parent, b_n ) b_s = root[ "s" ] self.assertTrue( b_s.is_leaf() ) self.assertEqual( b_s.start, 5 ) self.assertEqual( b_s.stop, 7 ) self.assertEqual( b_s.label, 5 ) self.assertEqual( b_s.parent, root ) b_dl = root[ "$" ] self.assertTrue( b_dl.is_leaf() ) self.assertEqual( b_dl.start, 6 ) self.assertEqual( b_dl.stop, 7 ) self.assertEqual( b_dl.label, 6 ) self.assertEqual( b_dl.parent, root ) self.assertEqual( b_a.suffix, root ) self.assertEqual( b_n.suffix, b_a ) self.assertEqual( b_a_n.suffix, b_n ) class TestMatchingStatistics(unittest.TestCase): def test(self): tree = single.tree() result = list( single.matching_statistics( tree, list( "ABC" ) ) ) self.assertEqual( result, [ ( 0, ( tree.root, 0 ) ) ] * 3 ) builder = single.ukkonen( tree = tree ) for c in "TTAGC$": builder.append( c ) self.assertRaises( RuntimeError, single.matching_statistics, tree, list() ); builder.detach() root = tree.root branch_t = root[ "T" ] leaf_0 = branch_t[ "T" ] leaf_1 = branch_t[ "A" ] leaf_2 = root[ "A" ] leaf_3 = root[ "G" ] leaf_4 = root[ "C" ] result = list( single.matching_statistics( tree, [] ) ) self.assertEqual( result, [] ) result = list( single.matching_statistics( tree, list( "QTTATTATTTAGCQWTTAGFK" ) ) ) self.assertEqual( result, [ ( 0, ( root, 0 ) ), ( 3, ( leaf_0, 3 ) ), ( 2, ( leaf_1, 3 ) ), ( 1, ( leaf_2, 3 ) ), ( 3, ( leaf_0, 3 ) ), ( 2, ( leaf_1, 3 ) ), ( 1, ( leaf_2, 3 ) ), ( 2, ( leaf_0, 2 ) ), ( 5, ( leaf_0, 5 ) ), ( 4, ( leaf_1, 5 ) ), ( 3, ( leaf_2, 5 ) ), ( 2, ( leaf_3, 5 ) ), ( 1, ( leaf_4, 5 ) ), ( 0, ( root, 0 ) ), ( 0, ( root, 0 ) ), ( 4, ( leaf_0, 4 ) ), ( 3, ( leaf_1, 4 ) ), ( 2, ( leaf_2, 4 ) ), ( 1, ( leaf_3, 4 ) ), ( 0, ( root, 0 ) ), ( 0, ( root, 0 ) ), ] ) class TestLeafIndices(unittest.TestCase): def test(self): tree = single.tree() result = list( single.matching_statistics( tree, list( "ABC" ) ) ) self.assertEqual( result, [ ( 0, ( tree.root, 0 ) ) ] * 3 ) builder = single.ukkonen( tree = tree ) for c in "TTAGC$": builder.append( c ) builder.detach() leaf_indices_below = suffixtree.calculate_leaf_indices( root = tree.root ) root = tree.root branch_t = root[ "T" ] leaf_0 = branch_t[ "T" ] leaf_1 = branch_t[ "A" ] leaf_2 = root[ "A" ] leaf_3 = root[ "G" ] leaf_4 = root[ "C" ] leaf_5 = root[ "$" ] self.assertEqual( leaf_indices_below[ leaf_0 ], [ 0 ] ) self.assertEqual( leaf_indices_below[ leaf_1 ], [ 1 ] ) self.assertEqual( leaf_indices_below[ leaf_2 ], [ 2 ] ) self.assertEqual( leaf_indices_below[ leaf_3 ], [ 3 ] ) self.assertEqual( leaf_indices_below[ leaf_4 ], [ 4 ] ) self.assertEqual( leaf_indices_below[ leaf_5 ], [ 5 ] ) self.assertEqual( sorted( leaf_indices_below[ branch_t ] ), [ 0, 1 ] ) self.assertEqual( sorted( leaf_indices_below[ root ] ), range( 6 ) ) suite_word = unittest.TestLoader().loadTestsFromTestCase( TestWord ) suite_edge = unittest.TestLoader().loadTestsFromTestCase( TestEdge ) suite_preorder = unittest.TestLoader().loadTestsFromTestCase( TestPreOrder ) suite_postorder = unittest.TestLoader().loadTestsFromTestCase( TestPostOrder ) suite_tree = unittest.TestLoader().loadTestsFromTestCase( TestTree ) suite_msi = unittest.TestLoader().loadTestsFromTestCase( TestMatchingStatistics ) suite_leaf_indices = unittest.TestLoader().loadTestsFromTestCase( TestLeafIndices ) alltests = unittest.TestSuite( [ suite_word, suite_edge, suite_preorder, suite_postorder, suite_tree, suite_msi, suite_leaf_indices, ] ) def load_tests(loader, tests, pattern): return alltests if __name__ == "__main__": unittest.TextTestRunner( verbosity = 2 ).run( alltests )
none
1
2.883435
3
tests/examples/test_integrations.py
fstroth/lightning-flash
1
6630477
# Copyright The PyTorch Lightning team. # # 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 pathlib import Path from unittest import mock import pytest from flash.core.utilities.imports import _FIFTYONE_AVAILABLE from tests.examples.utils import run_test root = Path(__file__).parent.parent.parent @mock.patch.dict(os.environ, {"FLASH_TESTING": "1"}) @pytest.mark.parametrize( "folder, file", [ pytest.param( "fiftyone", "image_classification.py", marks=pytest.mark.skipif(not _FIFTYONE_AVAILABLE, reason="fiftyone library isn't installed") ), ] ) def test_integrations(tmpdir, folder, file): run_test(str(root / "flash_examples" / "integrations" / folder / file))
# Copyright The PyTorch Lightning team. # # 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 pathlib import Path from unittest import mock import pytest from flash.core.utilities.imports import _FIFTYONE_AVAILABLE from tests.examples.utils import run_test root = Path(__file__).parent.parent.parent @mock.patch.dict(os.environ, {"FLASH_TESTING": "1"}) @pytest.mark.parametrize( "folder, file", [ pytest.param( "fiftyone", "image_classification.py", marks=pytest.mark.skipif(not _FIFTYONE_AVAILABLE, reason="fiftyone library isn't installed") ), ] ) def test_integrations(tmpdir, folder, file): run_test(str(root / "flash_examples" / "integrations" / folder / file))
en
0.856613
# Copyright The PyTorch Lightning team. # # 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.
1.945434
2
fedml_api/standalone/hierarchical_fl/trainer.py
xuwanwei/FedML
1,120
6630478
import logging import numpy as np from fedml_api.standalone.hierarchical_fl.group import Group from fedml_api.standalone.hierarchical_fl.client import Client from fedml_api.standalone.fedavg.fedavg_trainer import FedAvgTrainer class Trainer(FedAvgTrainer): def setup_clients(self, train_data_local_num_dict, train_data_local_dict, test_data_local_dict): logging.info("############setup_clients (START)#############") if self.args.group_method == 'random': self.group_indexes = np.random.randint(0, self.args.group_num, self.args.client_num_in_total) group_to_client_indexes = {} for client_idx, group_idx in enumerate(self.group_indexes): if not group_idx in group_to_client_indexes: group_to_client_indexes[group_idx] = [] group_to_client_indexes[group_idx].append(client_idx) else: raise Exception(self.args.group_method) self.group_dict = {} for group_idx, client_indexes in group_to_client_indexes.items(): self.group_dict[group_idx] = Group(group_idx, client_indexes, train_data_local_dict, test_data_local_dict, train_data_local_num_dict, self.args, self.device, self.model) # maintain a dummy client to be used in FedAvgTrainer::local_test_on_all_clients() self.client_list = [Client(client_idx, train_data_local_dict[0], test_data_local_dict[0], train_data_local_num_dict[0], self.args, self.device, self.model)] logging.info("############setup_clients (END)#############") def client_sampling(self, global_round_idx, client_num_in_total, client_num_per_round): sampled_client_indexes = super().client_sampling(global_round_idx, client_num_in_total, client_num_per_round) group_to_client_indexes = {} for client_idx in sampled_client_indexes: group_idx = self.group_indexes[client_idx] if not group_idx in group_to_client_indexes: group_to_client_indexes[group_idx] = [] group_to_client_indexes[group_idx].append(client_idx) logging.info("client_indexes of each group = {}".format(group_to_client_indexes)) return group_to_client_indexes def train(self): w_global = self.model.state_dict() for global_round_idx in range(self.args.global_comm_round): logging.info("################Global Communication Round : {}".format(global_round_idx)) group_to_client_indexes = self.client_sampling(global_round_idx, self.args.client_num_in_total, self.args.client_num_per_round) # train each group w_groups_dict = {} for group_idx in sorted(group_to_client_indexes.keys()): sampled_client_indexes = group_to_client_indexes[group_idx] group = self.group_dict[group_idx] w_group_list = group.train(global_round_idx, w_global, sampled_client_indexes) for global_epoch, w in w_group_list: if not global_epoch in w_groups_dict: w_groups_dict[global_epoch] = [] w_groups_dict[global_epoch].append((group.get_sample_number(sampled_client_indexes), w)) # aggregate group weights into the global weight for global_epoch in sorted(w_groups_dict.keys()): w_groups = w_groups_dict[global_epoch] w_global = self.aggregate(w_groups) # evaluate performance if global_epoch % self.args.frequency_of_the_test == 0 or \ global_epoch == self.args.global_comm_round*self.args.group_comm_round*self.args.epochs-1: self.model.load_state_dict(w_global) self.local_test_on_all_clients(self.model, global_epoch)
import logging import numpy as np from fedml_api.standalone.hierarchical_fl.group import Group from fedml_api.standalone.hierarchical_fl.client import Client from fedml_api.standalone.fedavg.fedavg_trainer import FedAvgTrainer class Trainer(FedAvgTrainer): def setup_clients(self, train_data_local_num_dict, train_data_local_dict, test_data_local_dict): logging.info("############setup_clients (START)#############") if self.args.group_method == 'random': self.group_indexes = np.random.randint(0, self.args.group_num, self.args.client_num_in_total) group_to_client_indexes = {} for client_idx, group_idx in enumerate(self.group_indexes): if not group_idx in group_to_client_indexes: group_to_client_indexes[group_idx] = [] group_to_client_indexes[group_idx].append(client_idx) else: raise Exception(self.args.group_method) self.group_dict = {} for group_idx, client_indexes in group_to_client_indexes.items(): self.group_dict[group_idx] = Group(group_idx, client_indexes, train_data_local_dict, test_data_local_dict, train_data_local_num_dict, self.args, self.device, self.model) # maintain a dummy client to be used in FedAvgTrainer::local_test_on_all_clients() self.client_list = [Client(client_idx, train_data_local_dict[0], test_data_local_dict[0], train_data_local_num_dict[0], self.args, self.device, self.model)] logging.info("############setup_clients (END)#############") def client_sampling(self, global_round_idx, client_num_in_total, client_num_per_round): sampled_client_indexes = super().client_sampling(global_round_idx, client_num_in_total, client_num_per_round) group_to_client_indexes = {} for client_idx in sampled_client_indexes: group_idx = self.group_indexes[client_idx] if not group_idx in group_to_client_indexes: group_to_client_indexes[group_idx] = [] group_to_client_indexes[group_idx].append(client_idx) logging.info("client_indexes of each group = {}".format(group_to_client_indexes)) return group_to_client_indexes def train(self): w_global = self.model.state_dict() for global_round_idx in range(self.args.global_comm_round): logging.info("################Global Communication Round : {}".format(global_round_idx)) group_to_client_indexes = self.client_sampling(global_round_idx, self.args.client_num_in_total, self.args.client_num_per_round) # train each group w_groups_dict = {} for group_idx in sorted(group_to_client_indexes.keys()): sampled_client_indexes = group_to_client_indexes[group_idx] group = self.group_dict[group_idx] w_group_list = group.train(global_round_idx, w_global, sampled_client_indexes) for global_epoch, w in w_group_list: if not global_epoch in w_groups_dict: w_groups_dict[global_epoch] = [] w_groups_dict[global_epoch].append((group.get_sample_number(sampled_client_indexes), w)) # aggregate group weights into the global weight for global_epoch in sorted(w_groups_dict.keys()): w_groups = w_groups_dict[global_epoch] w_global = self.aggregate(w_groups) # evaluate performance if global_epoch % self.args.frequency_of_the_test == 0 or \ global_epoch == self.args.global_comm_round*self.args.group_comm_round*self.args.epochs-1: self.model.load_state_dict(w_global) self.local_test_on_all_clients(self.model, global_epoch)
en
0.431468
###########setup_clients (START)#############") # maintain a dummy client to be used in FedAvgTrainer::local_test_on_all_clients() ###########setup_clients (END)#############") ###############Global Communication Round : {}".format(global_round_idx)) # train each group # aggregate group weights into the global weight # evaluate performance
2.156697
2
unreleased/azure-mgmt-machinelearning/azure/mgmt/machinelearning/models/column_specification.py
CharaD7/azure-sdk-for-python
0
6630479
<filename>unreleased/azure-mgmt-machinelearning/azure/mgmt/machinelearning/models/column_specification.py # 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 ColumnSpecification(Model): """Swagger 2.0 schema for a column within the data table representing a web service input or output. See Swagger specification: http://swagger.io/specification/. :param type: Data type of the column. Possible values include: 'Boolean', 'Integer', 'Number', 'String' :type type: str or :class:`ColumnType <azure.mgmt.machinelearning.models.ColumnType>` :param format: Additional format information for the data type. Possible values include: 'Byte', 'Char', 'Datetime', 'Double', 'Duration', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Uint8', 'Uint16', 'Uint32', 'Uint64' :type format: str or :class:`ColumnFormat <azure.mgmt.machinelearning.models.ColumnFormat>` :param enum: If the data type is categorical, this provides the list of accepted categories. :type enum: list of object :param x_ms_isnullable: Flag indicating if the type supports null values or not. :type x_ms_isnullable: bool :param x_ms_isordered: Flag indicating whether the categories are treated as an ordered set or not, if this is a categorical column. :type x_ms_isordered: bool """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'format': {'key': 'format', 'type': 'str'}, 'enum': {'key': 'enum', 'type': '[object]'}, 'x_ms_isnullable': {'key': 'x-ms-isnullable', 'type': 'bool'}, 'x_ms_isordered': {'key': 'x-ms-isordered', 'type': 'bool'}, } def __init__(self, type, format=None, enum=None, x_ms_isnullable=None, x_ms_isordered=None): self.type = type self.format = format self.enum = enum self.x_ms_isnullable = x_ms_isnullable self.x_ms_isordered = x_ms_isordered
<filename>unreleased/azure-mgmt-machinelearning/azure/mgmt/machinelearning/models/column_specification.py # 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 ColumnSpecification(Model): """Swagger 2.0 schema for a column within the data table representing a web service input or output. See Swagger specification: http://swagger.io/specification/. :param type: Data type of the column. Possible values include: 'Boolean', 'Integer', 'Number', 'String' :type type: str or :class:`ColumnType <azure.mgmt.machinelearning.models.ColumnType>` :param format: Additional format information for the data type. Possible values include: 'Byte', 'Char', 'Datetime', 'Double', 'Duration', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Uint8', 'Uint16', 'Uint32', 'Uint64' :type format: str or :class:`ColumnFormat <azure.mgmt.machinelearning.models.ColumnFormat>` :param enum: If the data type is categorical, this provides the list of accepted categories. :type enum: list of object :param x_ms_isnullable: Flag indicating if the type supports null values or not. :type x_ms_isnullable: bool :param x_ms_isordered: Flag indicating whether the categories are treated as an ordered set or not, if this is a categorical column. :type x_ms_isordered: bool """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'format': {'key': 'format', 'type': 'str'}, 'enum': {'key': 'enum', 'type': '[object]'}, 'x_ms_isnullable': {'key': 'x-ms-isnullable', 'type': 'bool'}, 'x_ms_isordered': {'key': 'x-ms-isordered', 'type': 'bool'}, } def __init__(self, type, format=None, enum=None, x_ms_isnullable=None, x_ms_isordered=None): self.type = type self.format = format self.enum = enum self.x_ms_isnullable = x_ms_isnullable self.x_ms_isordered = x_ms_isordered
en
0.498983
# 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. # -------------------------------------------------------------------------- Swagger 2.0 schema for a column within the data table representing a web service input or output. See Swagger specification: http://swagger.io/specification/. :param type: Data type of the column. Possible values include: 'Boolean', 'Integer', 'Number', 'String' :type type: str or :class:`ColumnType <azure.mgmt.machinelearning.models.ColumnType>` :param format: Additional format information for the data type. Possible values include: 'Byte', 'Char', 'Datetime', 'Double', 'Duration', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Uint8', 'Uint16', 'Uint32', 'Uint64' :type format: str or :class:`ColumnFormat <azure.mgmt.machinelearning.models.ColumnFormat>` :param enum: If the data type is categorical, this provides the list of accepted categories. :type enum: list of object :param x_ms_isnullable: Flag indicating if the type supports null values or not. :type x_ms_isnullable: bool :param x_ms_isordered: Flag indicating whether the categories are treated as an ordered set or not, if this is a categorical column. :type x_ms_isordered: bool
2.023124
2
HER2/Practice Testing/Dropout Experiment/3_get_model_D7.py
raktim-mondol/DeepLearningCamelyon
70
6630480
def get_model(): model = Sequential() model.add(Lambda(lambda x: x * 1./255., input_shape=(120, 160, 3), output_shape=(120, 160, 3))) model.add(Conv2D(32, (3, 3), input_shape=(120, 160, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.875)) model.add(Dense(1)) # model.add(Dense(2)) model.add(Activation('sigmoid')) # model.add(Activation('softmax')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # model.compile(loss='categorical_crossentropy', # optimizer='rmsprop', # metrics=['accuracy']) return model model = get_model() print(model.summary())
def get_model(): model = Sequential() model.add(Lambda(lambda x: x * 1./255., input_shape=(120, 160, 3), output_shape=(120, 160, 3))) model.add(Conv2D(32, (3, 3), input_shape=(120, 160, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.875)) model.add(Dense(1)) # model.add(Dense(2)) model.add(Activation('sigmoid')) # model.add(Activation('softmax')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # model.compile(loss='categorical_crossentropy', # optimizer='rmsprop', # metrics=['accuracy']) return model model = get_model() print(model.summary())
en
0.260105
# this converts our 3D feature maps to 1D feature vectors # model.add(Dense(2)) # model.add(Activation('softmax')) # model.compile(loss='categorical_crossentropy', # optimizer='rmsprop', # metrics=['accuracy'])
3.240985
3
items.py
legend-plus/LegendBot
4
6630481
<filename>items.py<gh_stars>1-10 class Item: def __init__(self, base: str = "item", sprite: str = None, item_type: str = None, name: str = None, description: str = None): self.base = base if sprite is not None: self.sprite: str = sprite if item_type is not None: self.item_type: str = item_type if name is not None: self.name: str = name if description is not None: self.description: str = description def get_sprite(self, base_items): if hasattr(self, "sprite"): return self.sprite else: return base_items[self.base]["sprite"] def get_item_type(self, base_items): if hasattr(self, "item_type"): return self.item_type else: return base_items[self.base]["item_type"] def get_name(self, base_items): if hasattr(self, "name"): return self.name else: return base_items[self.base]["name"] def get_description(self, base_items): if hasattr(self, "description"): return self.description else: return base_items[self.base]["description"] class Weapon(Item): def __init__(self, base: str = "item", sprite: str = None, item_type: str = None, name: str = None, description: str = None, weapon_class: str = None, damage: float = None, damage_type: str = None): super().__init__(base, sprite, item_type, name, description) if weapon_class is not None: self.weapon_class: str = weapon_class if damage is not None: self.damage: float = damage if damage_type is not None: self.damage_type: str = damage_type def get_damage(self, base_items): if hasattr(self, "damage"): return self.damage elif "damage" in base_items[self.base]: return base_items[self.base]["damage"] else: return 0.0 def get_damage_type(self, base_items): if hasattr(self, "damage_type"): return self.damage_type elif "damage_type" in base_items[self.base]: return base_items[self.base]["damage_type"] else: return "void" def get_weapon_class(self, base_items): if hasattr(self, "weapon_class"): return self.weapon_class elif "weapon_class" in base_items[self.base]: return base_items[self.base]["weapon_class"] else: return "unknown" def from_dict(item_dict: dict, item_bases: dict) -> Item: if ("item_type" in item_dict and item_dict["item_type"] == "weapon") or item_bases[item_dict["base"]]["item_type"] == "weapon": return Weapon( item_dict.get("base", "item"), item_dict.get("sprite", None), "weapon", item_dict.get("name", None), item_dict.get("description", None), item_dict.get("weapon_class", None), item_dict.get("damage", None), item_dict.get("damage_type", None) ) elif "item_type" in item_dict: return Item( item_dict.get("base", None), item_dict.get("sprite", None), item_dict["item_type"], item_dict.get("name", None), item_dict.get("description", None), ) elif "item_type" in item_bases[item_dict["base"]]: return Item( item_dict.get("base", None), item_dict.get("sprite", None), item_bases[item_dict["base"]]["item_type"], item_dict.get("name", None), item_dict.get("description", None), ) else: return Item( item_dict.get("base", None), item_dict.get("sprite", None), "misc", item_dict.get("name", None), item_dict.get("description", None), )
<filename>items.py<gh_stars>1-10 class Item: def __init__(self, base: str = "item", sprite: str = None, item_type: str = None, name: str = None, description: str = None): self.base = base if sprite is not None: self.sprite: str = sprite if item_type is not None: self.item_type: str = item_type if name is not None: self.name: str = name if description is not None: self.description: str = description def get_sprite(self, base_items): if hasattr(self, "sprite"): return self.sprite else: return base_items[self.base]["sprite"] def get_item_type(self, base_items): if hasattr(self, "item_type"): return self.item_type else: return base_items[self.base]["item_type"] def get_name(self, base_items): if hasattr(self, "name"): return self.name else: return base_items[self.base]["name"] def get_description(self, base_items): if hasattr(self, "description"): return self.description else: return base_items[self.base]["description"] class Weapon(Item): def __init__(self, base: str = "item", sprite: str = None, item_type: str = None, name: str = None, description: str = None, weapon_class: str = None, damage: float = None, damage_type: str = None): super().__init__(base, sprite, item_type, name, description) if weapon_class is not None: self.weapon_class: str = weapon_class if damage is not None: self.damage: float = damage if damage_type is not None: self.damage_type: str = damage_type def get_damage(self, base_items): if hasattr(self, "damage"): return self.damage elif "damage" in base_items[self.base]: return base_items[self.base]["damage"] else: return 0.0 def get_damage_type(self, base_items): if hasattr(self, "damage_type"): return self.damage_type elif "damage_type" in base_items[self.base]: return base_items[self.base]["damage_type"] else: return "void" def get_weapon_class(self, base_items): if hasattr(self, "weapon_class"): return self.weapon_class elif "weapon_class" in base_items[self.base]: return base_items[self.base]["weapon_class"] else: return "unknown" def from_dict(item_dict: dict, item_bases: dict) -> Item: if ("item_type" in item_dict and item_dict["item_type"] == "weapon") or item_bases[item_dict["base"]]["item_type"] == "weapon": return Weapon( item_dict.get("base", "item"), item_dict.get("sprite", None), "weapon", item_dict.get("name", None), item_dict.get("description", None), item_dict.get("weapon_class", None), item_dict.get("damage", None), item_dict.get("damage_type", None) ) elif "item_type" in item_dict: return Item( item_dict.get("base", None), item_dict.get("sprite", None), item_dict["item_type"], item_dict.get("name", None), item_dict.get("description", None), ) elif "item_type" in item_bases[item_dict["base"]]: return Item( item_dict.get("base", None), item_dict.get("sprite", None), item_bases[item_dict["base"]]["item_type"], item_dict.get("name", None), item_dict.get("description", None), ) else: return Item( item_dict.get("base", None), item_dict.get("sprite", None), "misc", item_dict.get("name", None), item_dict.get("description", None), )
none
1
3.058458
3
Final_project/PostBoard/Board/views.py
GregTMJ/django-files
1
6630482
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Post, Author, Category, Comments, User from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView from .forms import PostForm, EditForm, CommentForm, CommentEditForm from .filters import SearchFilter # Create your views here. class Post_list(LoginRequiredMixin, ListView): model = Post template_name = 'Post/list_of_posts.html' context_object_name = 'Posts' paginate_by = 5 queryset = Post.objects.order_by('-id') class Post_details(LoginRequiredMixin, DetailView): model = Post template_name = 'Post/post_details.html' context_object_name = 'Post' class Post_create(LoginRequiredMixin, CreateView): model = Post template_name = 'Post/post_create.html' form_class = PostForm class Post_update(LoginRequiredMixin, UpdateView): template_name = 'Post/post_update.html' form_class = EditForm context_object_name = 'Post' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Post.objects.get(pk=ID) class Post_delete(LoginRequiredMixin, DeleteView): template_name = 'Post/post_delete.html' queryset = Post.objects.all() context_object_name = 'Post' success_url = '/Posts' class Add_comment(LoginRequiredMixin, CreateView): model = Comments template_name = 'Post/add_comment.html' form_class = CommentForm success_url = '/Posts' def form_valid(self, form): form.instance.comment_id = self.kwargs['pk'] return super().form_valid(form) class List_of_Comments(LoginRequiredMixin, ListView): model = Comments template_name = 'Post/list_of_comments.html' context_object_name = 'comments' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) available_comments = Comments.objects.all() user = User.objects.get(id=self.request.user.id) context['filter'] = SearchFilter(self.request.GET, queryset=self.get_queryset()) context['available_comments'] = available_comments context['author_id'] = user return context class CommentEdit(LoginRequiredMixin, UpdateView): template_name = 'Post/edit_comment.html' form_class = CommentEditForm context_object_name = 'comments' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Comments.objects.get(pk=ID) class CommentDelete(LoginRequiredMixin, DeleteView): model = Comments template_name = 'Post/comment_delete.html' queryset = Comments.objects.all() context_object_name = 'comments' success_url = '/Posts' def AcceptedView(request, pk): comment = get_object_or_404(Comments, id=request.POST.get('comment.id')) if not comment.accepted: comment.accepted = True else: comment.accepted = False return HttpResponseRedirect(reverse('list_of_comments'))
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Post, Author, Category, Comments, User from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView from .forms import PostForm, EditForm, CommentForm, CommentEditForm from .filters import SearchFilter # Create your views here. class Post_list(LoginRequiredMixin, ListView): model = Post template_name = 'Post/list_of_posts.html' context_object_name = 'Posts' paginate_by = 5 queryset = Post.objects.order_by('-id') class Post_details(LoginRequiredMixin, DetailView): model = Post template_name = 'Post/post_details.html' context_object_name = 'Post' class Post_create(LoginRequiredMixin, CreateView): model = Post template_name = 'Post/post_create.html' form_class = PostForm class Post_update(LoginRequiredMixin, UpdateView): template_name = 'Post/post_update.html' form_class = EditForm context_object_name = 'Post' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Post.objects.get(pk=ID) class Post_delete(LoginRequiredMixin, DeleteView): template_name = 'Post/post_delete.html' queryset = Post.objects.all() context_object_name = 'Post' success_url = '/Posts' class Add_comment(LoginRequiredMixin, CreateView): model = Comments template_name = 'Post/add_comment.html' form_class = CommentForm success_url = '/Posts' def form_valid(self, form): form.instance.comment_id = self.kwargs['pk'] return super().form_valid(form) class List_of_Comments(LoginRequiredMixin, ListView): model = Comments template_name = 'Post/list_of_comments.html' context_object_name = 'comments' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) available_comments = Comments.objects.all() user = User.objects.get(id=self.request.user.id) context['filter'] = SearchFilter(self.request.GET, queryset=self.get_queryset()) context['available_comments'] = available_comments context['author_id'] = user return context class CommentEdit(LoginRequiredMixin, UpdateView): template_name = 'Post/edit_comment.html' form_class = CommentEditForm context_object_name = 'comments' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Comments.objects.get(pk=ID) class CommentDelete(LoginRequiredMixin, DeleteView): model = Comments template_name = 'Post/comment_delete.html' queryset = Comments.objects.all() context_object_name = 'comments' success_url = '/Posts' def AcceptedView(request, pk): comment = get_object_or_404(Comments, id=request.POST.get('comment.id')) if not comment.accepted: comment.accepted = True else: comment.accepted = False return HttpResponseRedirect(reverse('list_of_comments'))
en
0.956133
# Create your views here. # Here we are getting the id so Django could stalk the change # Here we are getting the id so Django could stalk the change
2.01855
2
src/hashable.py
josephnavarro/ascii-art-generator
0
6630483
<gh_stars>0 #! usr/bin/env python3 """ : : Container class for a PIL Image. Allows image data to be hashable. : : """ from PIL import Image import uuid class HashableImage: """ : : Hashable PIL Image container. Enables PIL image data to be used as dictionary keys. : : : Attrs: : Image image : Image object : UUID _hash : Uniquely hashable element : : """ __slots__ = [ "image", "_hash", ] def __init__(self, image: Image): self.image = image # type: Image self._hash = uuid.uuid4() # type: uuid.UUID @property def size(self) -> (int, int): """ : : Gets size (i.e. width and height) of the contained image object. : : """ return self.image.size def __hash__(self): """ : : Returns hash(self). : : """ return hash(self._hash) def convert(self, mode: str) -> Image: """ : : Implements Image.convert(). Note that this returns a PIL Image, not a HashableImage. : : """ return self.image.convert(mode) def crop(self, rect: (int, int, int, int)): """ : : Implements Image.crop(). Note that this returns another HashableImage, not a PIL Image. : : """ return HashableImage(self.image.crop(rect)) def load(self): """ : : Returns pixel access data for the contained image object. : : """ return self.image.load()
#! usr/bin/env python3 """ : : Container class for a PIL Image. Allows image data to be hashable. : : """ from PIL import Image import uuid class HashableImage: """ : : Hashable PIL Image container. Enables PIL image data to be used as dictionary keys. : : : Attrs: : Image image : Image object : UUID _hash : Uniquely hashable element : : """ __slots__ = [ "image", "_hash", ] def __init__(self, image: Image): self.image = image # type: Image self._hash = uuid.uuid4() # type: uuid.UUID @property def size(self) -> (int, int): """ : : Gets size (i.e. width and height) of the contained image object. : : """ return self.image.size def __hash__(self): """ : : Returns hash(self). : : """ return hash(self._hash) def convert(self, mode: str) -> Image: """ : : Implements Image.convert(). Note that this returns a PIL Image, not a HashableImage. : : """ return self.image.convert(mode) def crop(self, rect: (int, int, int, int)): """ : : Implements Image.crop(). Note that this returns another HashableImage, not a PIL Image. : : """ return HashableImage(self.image.crop(rect)) def load(self): """ : : Returns pixel access data for the contained image object. : : """ return self.image.load()
fr
0.318407
#! usr/bin/env python3 : : Container class for a PIL Image. Allows image data to be hashable. : : : : Hashable PIL Image container. Enables PIL image data to be used as dictionary keys. : : : Attrs: : Image image : Image object : UUID _hash : Uniquely hashable element : : # type: Image # type: uuid.UUID : : Gets size (i.e. width and height) of the contained image object. : : : : Returns hash(self). : : : : Implements Image.convert(). Note that this returns a PIL Image, not a HashableImage. : : : : Implements Image.crop(). Note that this returns another HashableImage, not a PIL Image. : : : : Returns pixel access data for the contained image object. : :
3.518299
4
HW1/q3.py
wzcwzcwzc/ML
0
6630484
# -*- coding: utf-8 -*- """Q3.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1nuVOMaV1Wr9RXpnbiyiNker8qGPQ86Nl """ import os import numpy as np import matplotlib.pyplot as plt import pandas as pd # get 2-nd norms def getNorms(arr): norm = [] for i in range(len(arr)): for j in range(i + 1, len(arr)): temp = np.linalg.norm(arr[i] - arr[j]) norm.append(temp) return norm # create and initialize covariance matrix def buildCovMatrix(d): cov = [[0] * d for i in range(d)] for i in range(0, d): cov[i][i] = 1 return cov """d = 3 and sample_size = 10000""" d = 3 mean = [0] * d cov = buildCovMatrix(d) # generate 10000 random samples, 10000 is too much, here use 1000 as an example sample_size = 1000 mul_normal = np.random.multivariate_normal(mean, cov, sample_size) # calculate the 2-nd norm of two data norm = getNorms(mul_normal) print(f'when d = 3, the norms are {norm}') # calculate average and standard deviation of norm norm = np.array(norm) average = np.mean(norm) standard = np.std(norm) print(f'when d = 3, the average of norms is {average}') print(f'when d = 3, the standard deviation of norms is {standard}') # plot the histogram of Euclidean norms plt.hist(norm, bins=100, density=0, facecolor="blue") """d = 3, 50, 100, 200, 500, 1000""" d = [3, 50, 100, 200, 500, 1000] # d = [3, 50] average_ans = [] standard_ans = [] for x in range(0, len(d)): mean = [0] * d[x] cov = buildCovMatrix(d[x]) # get norms of each d sample_size = 1000 arr = np.random.multivariate_normal(mean, cov, sample_size) norm = np.array(getNorms(arr)) print(norm) # calculate mean and standard deviation average_ans.append(np.mean(norm)) standard_ans.append(np.std(norm)) print(average_ans) print(standard_ans) ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) # plot the average and standard deviation plt.sca(ax1) plt.plot(d, average_ans) plt.xlabel('d', fontsize=10) plt.ylabel('average', fontsize=10) plt.sca(ax2) plt.plot(d, standard_ans) plt.xlabel('d', fontsize=10) plt.ylabel('standard deviation', fontsize=10) """what I find is that the average is going up but the standard deviation tends to be convergence"""
# -*- coding: utf-8 -*- """Q3.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1nuVOMaV1Wr9RXpnbiyiNker8qGPQ86Nl """ import os import numpy as np import matplotlib.pyplot as plt import pandas as pd # get 2-nd norms def getNorms(arr): norm = [] for i in range(len(arr)): for j in range(i + 1, len(arr)): temp = np.linalg.norm(arr[i] - arr[j]) norm.append(temp) return norm # create and initialize covariance matrix def buildCovMatrix(d): cov = [[0] * d for i in range(d)] for i in range(0, d): cov[i][i] = 1 return cov """d = 3 and sample_size = 10000""" d = 3 mean = [0] * d cov = buildCovMatrix(d) # generate 10000 random samples, 10000 is too much, here use 1000 as an example sample_size = 1000 mul_normal = np.random.multivariate_normal(mean, cov, sample_size) # calculate the 2-nd norm of two data norm = getNorms(mul_normal) print(f'when d = 3, the norms are {norm}') # calculate average and standard deviation of norm norm = np.array(norm) average = np.mean(norm) standard = np.std(norm) print(f'when d = 3, the average of norms is {average}') print(f'when d = 3, the standard deviation of norms is {standard}') # plot the histogram of Euclidean norms plt.hist(norm, bins=100, density=0, facecolor="blue") """d = 3, 50, 100, 200, 500, 1000""" d = [3, 50, 100, 200, 500, 1000] # d = [3, 50] average_ans = [] standard_ans = [] for x in range(0, len(d)): mean = [0] * d[x] cov = buildCovMatrix(d[x]) # get norms of each d sample_size = 1000 arr = np.random.multivariate_normal(mean, cov, sample_size) norm = np.array(getNorms(arr)) print(norm) # calculate mean and standard deviation average_ans.append(np.mean(norm)) standard_ans.append(np.std(norm)) print(average_ans) print(standard_ans) ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) # plot the average and standard deviation plt.sca(ax1) plt.plot(d, average_ans) plt.xlabel('d', fontsize=10) plt.ylabel('average', fontsize=10) plt.sca(ax2) plt.plot(d, standard_ans) plt.xlabel('d', fontsize=10) plt.ylabel('standard deviation', fontsize=10) """what I find is that the average is going up but the standard deviation tends to be convergence"""
en
0.865371
# -*- coding: utf-8 -*- Q3.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1nuVOMaV1Wr9RXpnbiyiNker8qGPQ86Nl # get 2-nd norms # create and initialize covariance matrix d = 3 and sample_size = 10000 # generate 10000 random samples, 10000 is too much, here use 1000 as an example # calculate the 2-nd norm of two data # calculate average and standard deviation of norm # plot the histogram of Euclidean norms d = 3, 50, 100, 200, 500, 1000 # d = [3, 50] # get norms of each d # calculate mean and standard deviation # plot the average and standard deviation what I find is that the average is going up but the standard deviation tends to be convergence
3.88354
4
stanCode_projects/my_drawing/my_drawing.py
shihjames/sc-projects
0
6630485
<gh_stars>0 """ File: my_drawing.py Name: <NAME> ---------------------- In this program, Karel the robot represents the students of stanCode, and the beepers are what we have learned, what we are learning, and what we will learn. When users click the mouse, Karel will move, this means we are one step forward in becoming a professional software engineer, data scientist, etc. Finally, Karel will walk through the path, meaning that we have graduated from all the courses, and we will feel very grateful and lucky to have the opportunity to receive such a good programming education. """ from campy.graphics.gobjects import GRect, GLine, GOval, GLabel, GPolygon from campy.graphics.gwindow import GWindow from campy.gui.events.mouse import onmouseclicked window = GWindow(500, 500, title='') head = GOval(60, 40) eye_l = GRect(10, 10) eye_r = GRect(10, 10) body = GRect(60, 50) neck = GRect(30, 4) arm_l = GRect(10, 30) arm_r = GRect(10, 30) leg_l = GOval(20, 15) leg_r = GOval(20, 15) word = GLabel('K') count = 0 def main(): """ The program will first create a canvas, a background, and lines. The first click will show four beepers at the lower part of the window. The second click will show a robot at the upper part of the window. For the next few clicks will move the robot from the upper part to the lower part of the window. The final click will show a speech bubble. """ background() draw_line() build_s() build_c() onmouseclicked(create_beeper) def background(): # Create a red background. global window back = GRect(window.width, window.height) window.add(back) def draw_line(): # Draw several vertical and horizontal lines. for i in range(1, 10): line_hor = GLine(0, i*50, window.width, i*50) line_ver = GLine(i*50, 0, i*50, window.height) window.add(line_hor) window.add(line_ver) def build_s(): # Create word: S. global window rect_l = 100 rect_s = 20 rect1 = GRect(rect_l, rect_s, x=100, y=150) rect2 = GRect(rect_s, rect_l, x=100, y=150) rect3 = GRect(rect_l, rect_s, x=100, y=230) rect4 = GRect(rect_s, rect_l, x=180, y=230) rect5 = GRect(rect_l, rect_s, x=100, y=310) rect1.filled = True rect1.fill_color = 'tomato' rect1.color = 'tomato' rect2.filled = True rect2.fill_color = 'tomato' rect2.color = 'tomato' rect3.filled = True rect3.fill_color = 'tomato' rect3.color = 'tomato' rect4.filled = True rect4.fill_color = 'tomato' rect4.color = 'tomato' rect5.filled = True rect5.fill_color = 'tomato' rect5.color = 'tomato' window.add(rect1) window.add(rect2) window.add(rect3) window.add(rect4) window.add(rect5) def build_c(): # Create word: C. global window rect_l = 100 rect_s = 20 rect1 = GRect(rect_l, rect_s, x=300, y=150) rect2 = GRect(rect_s, rect_l*2-rect_s, x=300, y=150) rect3 = GRect(rect_l, rect_s, x=300, y=310) rect1.filled = True rect1.fill_color = 'tomato' rect1.color = 'tomato' rect2.filled = True rect2.fill_color = 'tomato' rect2.color = 'tomato' rect3.filled = True rect3.fill_color = 'tomato' rect3.color = 'tomato' window.add(rect1) window.add(rect2) window.add(rect3) def build_karel(e): # Build up the robot, Karel. karel_head() karel_eye() karel_neck() karel_body() karel_limb() karel_label() onmouseclicked(move) def create_beeper(e): # create 4 beepers size = 50 for i in (1, 3, 7, 9): beeper = GOval(size, size, x=i*50-size/2, y=400-size/2) beeper.filled = True beeper.fill_color = 'blue' window.add(beeper) label1 = GLabel('001', x=50-size/2+9, y=400-size/2+37) label2 = GLabel('101', x=150-size/2+9, y=400-size/2+37) label3 = GLabel('201', x=350-size/2+9, y=400-size/2+37) label4 = GLabel('202', x=450-size/2+9, y=400-size/2+37) label1.font = '-15' label2.font = '-15' label3.font = '-15' label4.font = '-15' label1.color = 'white' label2.color = 'white' label3.color = 'white' label4.color = 'white' window.add(label1) window.add(label2) window.add(label3) window.add(label4) onmouseclicked(build_karel) def karel_head(): # Build Karel's head. global head head = GOval(60, 40, x=220, y=20) head.filled = True head.fill_color = 'gray' window.add(head) return head def karel_eye(): # Build Karel's eyes. global eye_l, eye_r eye_l = GRect(10, 10, x=235, y=35) eye_r = GRect(10, 10, x=255, y=35) eye_l.filled = True eye_r.filled = True eye_l.fill_color = 'blue' eye_r.fill_color = 'blue' window.add(eye_l) window.add(eye_r) def karel_neck(): # Build Karel's neck. global neck neck = GRect(30, 4, x=235, y=58) neck.filled = True neck.color = 'blue' window.add(neck) def karel_body(): # Build Karel's body. global body body = GRect(60, 50, x=220, y=62) body.filled = True body.fill_color = 'blue' window.add(body) def karel_limb(): # Build Karel's limbs. global arm_l, arm_r, leg_l, leg_r arm_l = GRect(10, 30, x=210, y=67) arm_r = GRect(10, 30, x=280, y=67) leg_l = GOval(20, 15, x=220, y=112) leg_r = GOval(20, 15, x=260, y=112) arm_l.filled = True arm_r.filled = True leg_l.filled = True leg_r.filled = True arm_l.fill_color = 'green' arm_r.fill_color = 'green' leg_l.fill_color = 'red' leg_r.fill_color = 'red' window.add(arm_l) window.add(arm_r) window.add(leg_l) window.add(leg_r) def karel_label(): # Show the word on Karel's body. global word word = GLabel('K', x=235, y=115) word.font = '-35' window.add(word) def move(e): # Move Karel down 100 units. global count if count < 6: head.move(0, 50) eye_l.move(0, 50) eye_r.move(0, 50) body.move(0, 50) neck.move(0, 50) arm_l.move(0, 50) arm_r.move(0, 50) leg_l.move(0, 50) leg_r.move(0, 50) word.move(0, 50) count += 1 if count == 6: speech_bub() def speech_bub(): # Show what Karel says. bub1 = GOval(10, 10, x=300, y=340) bub2 = GOval(15, 15, x=320, y=330) bub3 = GOval(150, 40, x=345, y=303) bub1.filled = True bub2.filled = True bub3.filled = True bub1.fill_color = 'white' bub2.fill_color = 'white' bub3.fill_color = 'white' word1 = GLabel('I love stanCode!', x=365, y=325) word2 = GLabel('I love Jerry !', x=375, y=338) word1.font = 'Courier-8-bold' word2.font = 'Courier-8-bold' window.add(bub1) window.add(bub2) window.add(bub3) window.add(word1) window.add(word2) if __name__ == '__main__': main()
""" File: my_drawing.py Name: <NAME> ---------------------- In this program, Karel the robot represents the students of stanCode, and the beepers are what we have learned, what we are learning, and what we will learn. When users click the mouse, Karel will move, this means we are one step forward in becoming a professional software engineer, data scientist, etc. Finally, Karel will walk through the path, meaning that we have graduated from all the courses, and we will feel very grateful and lucky to have the opportunity to receive such a good programming education. """ from campy.graphics.gobjects import GRect, GLine, GOval, GLabel, GPolygon from campy.graphics.gwindow import GWindow from campy.gui.events.mouse import onmouseclicked window = GWindow(500, 500, title='') head = GOval(60, 40) eye_l = GRect(10, 10) eye_r = GRect(10, 10) body = GRect(60, 50) neck = GRect(30, 4) arm_l = GRect(10, 30) arm_r = GRect(10, 30) leg_l = GOval(20, 15) leg_r = GOval(20, 15) word = GLabel('K') count = 0 def main(): """ The program will first create a canvas, a background, and lines. The first click will show four beepers at the lower part of the window. The second click will show a robot at the upper part of the window. For the next few clicks will move the robot from the upper part to the lower part of the window. The final click will show a speech bubble. """ background() draw_line() build_s() build_c() onmouseclicked(create_beeper) def background(): # Create a red background. global window back = GRect(window.width, window.height) window.add(back) def draw_line(): # Draw several vertical and horizontal lines. for i in range(1, 10): line_hor = GLine(0, i*50, window.width, i*50) line_ver = GLine(i*50, 0, i*50, window.height) window.add(line_hor) window.add(line_ver) def build_s(): # Create word: S. global window rect_l = 100 rect_s = 20 rect1 = GRect(rect_l, rect_s, x=100, y=150) rect2 = GRect(rect_s, rect_l, x=100, y=150) rect3 = GRect(rect_l, rect_s, x=100, y=230) rect4 = GRect(rect_s, rect_l, x=180, y=230) rect5 = GRect(rect_l, rect_s, x=100, y=310) rect1.filled = True rect1.fill_color = 'tomato' rect1.color = 'tomato' rect2.filled = True rect2.fill_color = 'tomato' rect2.color = 'tomato' rect3.filled = True rect3.fill_color = 'tomato' rect3.color = 'tomato' rect4.filled = True rect4.fill_color = 'tomato' rect4.color = 'tomato' rect5.filled = True rect5.fill_color = 'tomato' rect5.color = 'tomato' window.add(rect1) window.add(rect2) window.add(rect3) window.add(rect4) window.add(rect5) def build_c(): # Create word: C. global window rect_l = 100 rect_s = 20 rect1 = GRect(rect_l, rect_s, x=300, y=150) rect2 = GRect(rect_s, rect_l*2-rect_s, x=300, y=150) rect3 = GRect(rect_l, rect_s, x=300, y=310) rect1.filled = True rect1.fill_color = 'tomato' rect1.color = 'tomato' rect2.filled = True rect2.fill_color = 'tomato' rect2.color = 'tomato' rect3.filled = True rect3.fill_color = 'tomato' rect3.color = 'tomato' window.add(rect1) window.add(rect2) window.add(rect3) def build_karel(e): # Build up the robot, Karel. karel_head() karel_eye() karel_neck() karel_body() karel_limb() karel_label() onmouseclicked(move) def create_beeper(e): # create 4 beepers size = 50 for i in (1, 3, 7, 9): beeper = GOval(size, size, x=i*50-size/2, y=400-size/2) beeper.filled = True beeper.fill_color = 'blue' window.add(beeper) label1 = GLabel('001', x=50-size/2+9, y=400-size/2+37) label2 = GLabel('101', x=150-size/2+9, y=400-size/2+37) label3 = GLabel('201', x=350-size/2+9, y=400-size/2+37) label4 = GLabel('202', x=450-size/2+9, y=400-size/2+37) label1.font = '-15' label2.font = '-15' label3.font = '-15' label4.font = '-15' label1.color = 'white' label2.color = 'white' label3.color = 'white' label4.color = 'white' window.add(label1) window.add(label2) window.add(label3) window.add(label4) onmouseclicked(build_karel) def karel_head(): # Build Karel's head. global head head = GOval(60, 40, x=220, y=20) head.filled = True head.fill_color = 'gray' window.add(head) return head def karel_eye(): # Build Karel's eyes. global eye_l, eye_r eye_l = GRect(10, 10, x=235, y=35) eye_r = GRect(10, 10, x=255, y=35) eye_l.filled = True eye_r.filled = True eye_l.fill_color = 'blue' eye_r.fill_color = 'blue' window.add(eye_l) window.add(eye_r) def karel_neck(): # Build Karel's neck. global neck neck = GRect(30, 4, x=235, y=58) neck.filled = True neck.color = 'blue' window.add(neck) def karel_body(): # Build Karel's body. global body body = GRect(60, 50, x=220, y=62) body.filled = True body.fill_color = 'blue' window.add(body) def karel_limb(): # Build Karel's limbs. global arm_l, arm_r, leg_l, leg_r arm_l = GRect(10, 30, x=210, y=67) arm_r = GRect(10, 30, x=280, y=67) leg_l = GOval(20, 15, x=220, y=112) leg_r = GOval(20, 15, x=260, y=112) arm_l.filled = True arm_r.filled = True leg_l.filled = True leg_r.filled = True arm_l.fill_color = 'green' arm_r.fill_color = 'green' leg_l.fill_color = 'red' leg_r.fill_color = 'red' window.add(arm_l) window.add(arm_r) window.add(leg_l) window.add(leg_r) def karel_label(): # Show the word on Karel's body. global word word = GLabel('K', x=235, y=115) word.font = '-35' window.add(word) def move(e): # Move Karel down 100 units. global count if count < 6: head.move(0, 50) eye_l.move(0, 50) eye_r.move(0, 50) body.move(0, 50) neck.move(0, 50) arm_l.move(0, 50) arm_r.move(0, 50) leg_l.move(0, 50) leg_r.move(0, 50) word.move(0, 50) count += 1 if count == 6: speech_bub() def speech_bub(): # Show what Karel says. bub1 = GOval(10, 10, x=300, y=340) bub2 = GOval(15, 15, x=320, y=330) bub3 = GOval(150, 40, x=345, y=303) bub1.filled = True bub2.filled = True bub3.filled = True bub1.fill_color = 'white' bub2.fill_color = 'white' bub3.fill_color = 'white' word1 = GLabel('I love stanCode!', x=365, y=325) word2 = GLabel('I love Jerry !', x=375, y=338) word1.font = 'Courier-8-bold' word2.font = 'Courier-8-bold' window.add(bub1) window.add(bub2) window.add(bub3) window.add(word1) window.add(word2) if __name__ == '__main__': main()
en
0.909421
File: my_drawing.py Name: <NAME> ---------------------- In this program, Karel the robot represents the students of stanCode, and the beepers are what we have learned, what we are learning, and what we will learn. When users click the mouse, Karel will move, this means we are one step forward in becoming a professional software engineer, data scientist, etc. Finally, Karel will walk through the path, meaning that we have graduated from all the courses, and we will feel very grateful and lucky to have the opportunity to receive such a good programming education. The program will first create a canvas, a background, and lines. The first click will show four beepers at the lower part of the window. The second click will show a robot at the upper part of the window. For the next few clicks will move the robot from the upper part to the lower part of the window. The final click will show a speech bubble. # Create a red background. # Draw several vertical and horizontal lines. # Create word: S. # Create word: C. # Build up the robot, Karel. # create 4 beepers # Build Karel's head. # Build Karel's eyes. # Build Karel's neck. # Build Karel's body. # Build Karel's limbs. # Show the word on Karel's body. # Move Karel down 100 units. # Show what Karel says.
4.033796
4
setup.py
Naminwang/VBDiarization
0
6630486
<reponame>Naminwang/VBDiarization #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved import os import urllib import tarfile import logging import tempfile from distutils.core import setup from subprocess import check_call from setuptools import find_packages from setuptools.command.install import install from setuptools.command.develop import develop from vbdiar.utils import mkdir_p from vbdiar.kaldi import KALDI_ROOT_PATH CDIR = os.path.dirname(os.path.realpath(__file__)) XVEC_MODELS_DIR = os.path.join(CDIR, 'models', 'x-vectors') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def install_scripts(directory): """ Call cmd commands to install extra software/repositories. Args: directory (str): path """ if KALDI_ROOT_PATH is None or not os.path.isdir(KALDI_ROOT_PATH): raise ValueError('Please, set path to correct kaldi installation.') nnet_copy_binary = os.path.join(KALDI_ROOT_PATH, 'src', 'nnet3bin', 'nnet3-copy') if not os.path.isfile(nnet_copy_binary): raise ValueError('nnet3-copy binary not found in `{}`.'.format(os.path.dirname(nnet_copy_binary))) copy_matrix_binary = os.path.join(KALDI_ROOT_PATH, 'src', 'bin', 'copy-matrix') if not os.path.isfile(copy_matrix_binary): raise ValueError('copy-matrix binary not found in `{}`.'.format(os.path.dirname(copy_matrix_binary))) mkdir_p(XVEC_MODELS_DIR) with tempfile.NamedTemporaryFile() as f: urllib.urlretrieve( 'http://kaldi-asr.org/models/0003_sre16_v2_1a.tar.gz', f.name) tar = tarfile.open(os.path.join(f.name), 'r:gz') tar.extractall(XVEC_MODELS_DIR) tar.close() # replace input of the last layer, so we can easily extract xvectors nnet_raw_path = os.path.join(XVEC_MODELS_DIR, '0003_sre16_v2_1a', 'exp', 'xvector_nnet_1a', 'final.raw') old_line = 'output-node name=output input=output.log-softmax objective=linear' new_line = 'output-node name=output input=tdnn6.affine objective=linear' check_call(['sed', '-i', '-e', 's@{}@{}@g'.format(old_line, new_line), nnet_raw_path]) # convert LDA matrix to text format lda_path = os.path.join(os.path.dirname(nnet_raw_path), '..', 'xvectors_sre_combined', 'transform.mat') check_call([copy_matrix_binary, '--binary=false', lda_path, lda_path.replace('.mat', '.txt')]) class PostDevelopCommand(develop): """ Post-installation for development mode.""" def run(self): develop.run(self) self.execute(install_scripts, (self.egg_path,), msg='Running post install scripts') class PostInstallCommand(install): """ Post-installation for installation mode.""" def run(self): install.run(self) self.execute(install_scripts, (self.install_lib,), msg='Running post install scripts') setup( name='vbdiar', version='0.1', packages=find_packages(), url='', license='', author='profant', author_email='<EMAIL>', description='', cmdclass={'install': PostInstallCommand, 'develop': PostDevelopCommand} ) # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved import os import urllib import tarfile import logging import tempfile from distutils.core import setup from subprocess import check_call from setuptools import find_packages from setuptools.command.install import install from setuptools.command.develop import develop from vbdiar.utils import mkdir_p from vbdiar.kaldi import KALDI_ROOT_PATH CDIR = os.path.dirname(os.path.realpath(__file__)) XVEC_MODELS_DIR = os.path.join(CDIR, 'models', 'x-vectors') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def install_scripts(directory): """ Call cmd commands to install extra software/repositories. Args: directory (str): path """ if KALDI_ROOT_PATH is None or not os.path.isdir(KALDI_ROOT_PATH): raise ValueError('Please, set path to correct kaldi installation.') nnet_copy_binary = os.path.join(KALDI_ROOT_PATH, 'src', 'nnet3bin', 'nnet3-copy') if not os.path.isfile(nnet_copy_binary): raise ValueError('nnet3-copy binary not found in `{}`.'.format(os.path.dirname(nnet_copy_binary))) copy_matrix_binary = os.path.join(KALDI_ROOT_PATH, 'src', 'bin', 'copy-matrix') if not os.path.isfile(copy_matrix_binary): raise ValueError('copy-matrix binary not found in `{}`.'.format(os.path.dirname(copy_matrix_binary))) mkdir_p(XVEC_MODELS_DIR) with tempfile.NamedTemporaryFile() as f: urllib.urlretrieve( 'http://kaldi-asr.org/models/0003_sre16_v2_1a.tar.gz', f.name) tar = tarfile.open(os.path.join(f.name), 'r:gz') tar.extractall(XVEC_MODELS_DIR) tar.close() # replace input of the last layer, so we can easily extract xvectors nnet_raw_path = os.path.join(XVEC_MODELS_DIR, '0003_sre16_v2_1a', 'exp', 'xvector_nnet_1a', 'final.raw') old_line = 'output-node name=output input=output.log-softmax objective=linear' new_line = 'output-node name=output input=tdnn6.affine objective=linear' check_call(['sed', '-i', '-e', 's@{}@{}@g'.format(old_line, new_line), nnet_raw_path]) # convert LDA matrix to text format lda_path = os.path.join(os.path.dirname(nnet_raw_path), '..', 'xvectors_sre_combined', 'transform.mat') check_call([copy_matrix_binary, '--binary=false', lda_path, lda_path.replace('.mat', '.txt')]) class PostDevelopCommand(develop): """ Post-installation for development mode.""" def run(self): develop.run(self) self.execute(install_scripts, (self.egg_path,), msg='Running post install scripts') class PostInstallCommand(install): """ Post-installation for installation mode.""" def run(self): install.run(self) self.execute(install_scripts, (self.install_lib,), msg='Running post install scripts') setup( name='vbdiar', version='0.1', packages=find_packages(), url='', license='', author='profant', author_email='<EMAIL>', description='', cmdclass={'install': PostInstallCommand, 'develop': PostDevelopCommand} ) # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl
en
0.880046
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Brno University of Technology FIT # Author: <NAME> <<EMAIL>> # All Rights Reserved Call cmd commands to install extra software/repositories. Args: directory (str): path # replace input of the last layer, so we can easily extract xvectors # convert LDA matrix to text format Post-installation for development mode. Post-installation for installation mode. # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl # comment here, so github will not show, that this project is in perl
1.902782
2
old_versions/TCA_2_2/TCA_V_2_2_1/code/TCACore.py
OSADP/TCA
1
6630487
<reponame>OSADP/TCA #standard import math import sys import unittest import time import logging import os def set_logger(console_level = logging.INFO, file_level = logging.DEBUG, include_file = True, append_file = False): if not append_file: try: os.remove('tca2.log') except: pass logger = logging.getLogger('tca2') logger.setLevel(file_level) ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('%(message)s')) ch.setLevel(console_level) logger.addHandler(ch) if include_file: fh = logging.FileHandler('tca2.log') fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) fh.setLevel(file_level) logger.addHandler(fh) return logger logger = set_logger(include_file = True, file_level = logging.DEBUG) #------------------------------------------------------------------------- def Chk_Range(x1, y1, x2, y2): unitValue = 1 #1 = linear distance #2 - Spherical distance ran = None if unitValue ==1: ran = math.sqrt((float(y2) - float(y1)) ** 2 + (float(x2) - float(x1)) ** 2) elif unitValue==2: rad = 3958.76 #Earth radius in Miles #Convert to radians p1lat = float(x1) / 180 * math.pi p1long = float(y1) / 180 * math.pi p2lat = float(x2) / 180 * math.pi p2long = float(y2) / 180 * math.pi if (p1lat == p2lat) and (p1long == p2long): ran = float(0) else: ran = math.acos(math.sin(p1lat) * math.sin(p2lat) + math.cos(p1lat) * math.cos(p2lat) * math.cos(p2long - p1long)) * rad return ran #------------------------------------------------------------------------- # (x1,y1) : Top left of rectangle, (x2,y2) : Bottom right of rectangle, (x3,y3) : Point in question def Chk_Cellular_Range(x1, y1, x2, y2, x3, y3): if((x3>=x1) & (y3<=y1) & (x3<=x2) & (y3>=y2)): return True else: return False #------------------------------------------------------------------------- def Get_Heading(lat1, long1, lat2, long2): heading = 0 y = math.sin(long2-long1) * math.cos(lat2) x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(long2-long1) heading = (math.degrees(math.atan2(y,x)) + 360) % 360 return heading #------------------------------------------------------------------------- def report_errors(errors): if len(errors) > 0: for error in errors: print error sys.exit(0) class Timer: def __init__(self, enabled=False): self.timers = {} self.last_start = '' self.enabled = enabled def valid_title(self, title): if title in self.timers.keys() and isinstance(title, str): return True else: return False def __getitem__(self, title): if self.valid_title(title) : # print title return title + ',' + \ str(self.stats(title)) + ',' + \ str(self.stats(title, type='max')) + ',' + \ str(self.stats(title, type='avg')) + ',' + \ str(len(self.timers[title]['values'])) + ',' + \ str(self.timers[title]['values'][-1]) def current(self, title): if self.valid_title(title): return self.timers[title]['values'][-1] else: return 0 def stats(self, title, type='SUM'): if self.valid_title(title): if len(self.timers[title]['values']) > 0: if type.upper() == 'SUM': return sum(self.timers[title]['values']) elif type.upper() == 'MAX': return max(self.timers[title]['values']) elif type.upper() == 'AVG': return sum(self.timers[title]['values']) / len(self.timers[title]['values']) def start(self, title): if self.enabled: if title not in self.timers.keys(): self.timers[title] = {'st' : time.time(), 'values': []} else: self.timers[title]['st'] = time.time() self.last_start = title def stop(self, title=''): if self.enabled: if title == '': title = self.last_start if self.timers.has_key(title): end_time = time.time() self.timers[title]['values'].append(end_time - self.timers[title]['st']) def drop(self,title): if self.enabled: del self.timers[title] def header(self): return 'title,sum,max,avg,len,last\n' def write(self): if self.enabled: l = [] for title in self.timers: l.append(self.__getitem__(title)) return '\n'.join(l) else: return '' #************************************************************************* class TestTimer(unittest.TestCase): def test_timer(self): t1=Timer(enabled = True) t1.start('test1') time.sleep(2) t1.stop() assert (t1.current('test1') >= 2.0) and (t1.current('test1') < 2.1) t1.start('test2') time.sleep(3) t1.stop('test2') assert (t1.current('test2') >= 3.0) and (t1.current('test2') < 3.1) t1.start('test2') time.sleep(2) t1.stop() assert (t1.stats('test2') >= 5.0) and (t1.stats('test2') < 5.1) class CoreTests(unittest.TestCase): def test_range(self): assert 1 == int(Chk_Range(1,1,2,2)) assert 5.0 == Chk_Range(-2,1,1,5) assert 0.0 == Chk_Range(1,1,1,1) def test_errors(self): e = [] report_errors(e) def test_cellular_range(self): assert True == Chk_Cellular_Range(-2,1,0,0,-1,1) assert False == Chk_Cellular_Range(-2,1,0,0,1,0) def test_heading(self): assert 0 == Get_Heading(-1,0,0,0) assert 90 == Get_Heading(0,-1,0,0) assert 180 == Get_Heading(0,0,-1,0) assert 270 == Get_Heading(0,0,0,-1) if __name__ == '__main__': unittest.main()
#standard import math import sys import unittest import time import logging import os def set_logger(console_level = logging.INFO, file_level = logging.DEBUG, include_file = True, append_file = False): if not append_file: try: os.remove('tca2.log') except: pass logger = logging.getLogger('tca2') logger.setLevel(file_level) ch = logging.StreamHandler() ch.setFormatter(logging.Formatter('%(message)s')) ch.setLevel(console_level) logger.addHandler(ch) if include_file: fh = logging.FileHandler('tca2.log') fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) fh.setLevel(file_level) logger.addHandler(fh) return logger logger = set_logger(include_file = True, file_level = logging.DEBUG) #------------------------------------------------------------------------- def Chk_Range(x1, y1, x2, y2): unitValue = 1 #1 = linear distance #2 - Spherical distance ran = None if unitValue ==1: ran = math.sqrt((float(y2) - float(y1)) ** 2 + (float(x2) - float(x1)) ** 2) elif unitValue==2: rad = 3958.76 #Earth radius in Miles #Convert to radians p1lat = float(x1) / 180 * math.pi p1long = float(y1) / 180 * math.pi p2lat = float(x2) / 180 * math.pi p2long = float(y2) / 180 * math.pi if (p1lat == p2lat) and (p1long == p2long): ran = float(0) else: ran = math.acos(math.sin(p1lat) * math.sin(p2lat) + math.cos(p1lat) * math.cos(p2lat) * math.cos(p2long - p1long)) * rad return ran #------------------------------------------------------------------------- # (x1,y1) : Top left of rectangle, (x2,y2) : Bottom right of rectangle, (x3,y3) : Point in question def Chk_Cellular_Range(x1, y1, x2, y2, x3, y3): if((x3>=x1) & (y3<=y1) & (x3<=x2) & (y3>=y2)): return True else: return False #------------------------------------------------------------------------- def Get_Heading(lat1, long1, lat2, long2): heading = 0 y = math.sin(long2-long1) * math.cos(lat2) x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(long2-long1) heading = (math.degrees(math.atan2(y,x)) + 360) % 360 return heading #------------------------------------------------------------------------- def report_errors(errors): if len(errors) > 0: for error in errors: print error sys.exit(0) class Timer: def __init__(self, enabled=False): self.timers = {} self.last_start = '' self.enabled = enabled def valid_title(self, title): if title in self.timers.keys() and isinstance(title, str): return True else: return False def __getitem__(self, title): if self.valid_title(title) : # print title return title + ',' + \ str(self.stats(title)) + ',' + \ str(self.stats(title, type='max')) + ',' + \ str(self.stats(title, type='avg')) + ',' + \ str(len(self.timers[title]['values'])) + ',' + \ str(self.timers[title]['values'][-1]) def current(self, title): if self.valid_title(title): return self.timers[title]['values'][-1] else: return 0 def stats(self, title, type='SUM'): if self.valid_title(title): if len(self.timers[title]['values']) > 0: if type.upper() == 'SUM': return sum(self.timers[title]['values']) elif type.upper() == 'MAX': return max(self.timers[title]['values']) elif type.upper() == 'AVG': return sum(self.timers[title]['values']) / len(self.timers[title]['values']) def start(self, title): if self.enabled: if title not in self.timers.keys(): self.timers[title] = {'st' : time.time(), 'values': []} else: self.timers[title]['st'] = time.time() self.last_start = title def stop(self, title=''): if self.enabled: if title == '': title = self.last_start if self.timers.has_key(title): end_time = time.time() self.timers[title]['values'].append(end_time - self.timers[title]['st']) def drop(self,title): if self.enabled: del self.timers[title] def header(self): return 'title,sum,max,avg,len,last\n' def write(self): if self.enabled: l = [] for title in self.timers: l.append(self.__getitem__(title)) return '\n'.join(l) else: return '' #************************************************************************* class TestTimer(unittest.TestCase): def test_timer(self): t1=Timer(enabled = True) t1.start('test1') time.sleep(2) t1.stop() assert (t1.current('test1') >= 2.0) and (t1.current('test1') < 2.1) t1.start('test2') time.sleep(3) t1.stop('test2') assert (t1.current('test2') >= 3.0) and (t1.current('test2') < 3.1) t1.start('test2') time.sleep(2) t1.stop() assert (t1.stats('test2') >= 5.0) and (t1.stats('test2') < 5.1) class CoreTests(unittest.TestCase): def test_range(self): assert 1 == int(Chk_Range(1,1,2,2)) assert 5.0 == Chk_Range(-2,1,1,5) assert 0.0 == Chk_Range(1,1,1,1) def test_errors(self): e = [] report_errors(e) def test_cellular_range(self): assert True == Chk_Cellular_Range(-2,1,0,0,-1,1) assert False == Chk_Cellular_Range(-2,1,0,0,1,0) def test_heading(self): assert 0 == Get_Heading(-1,0,0,0) assert 90 == Get_Heading(0,-1,0,0) assert 180 == Get_Heading(0,0,-1,0) assert 270 == Get_Heading(0,0,0,-1) if __name__ == '__main__': unittest.main()
en
0.234517
#standard #------------------------------------------------------------------------- #1 = linear distance #2 - Spherical distance #Earth radius in Miles #Convert to radians #------------------------------------------------------------------------- # (x1,y1) : Top left of rectangle, (x2,y2) : Bottom right of rectangle, (x3,y3) : Point in question #------------------------------------------------------------------------- #------------------------------------------------------------------------- # print title #*************************************************************************
2.777546
3
tests/fixtures/internal/subpackage_a/subpackage_1/module_i.py
gitter-badger/dependenpy
10
6630488
<reponame>gitter-badger/dependenpy class ClassI(object): from ..module_1 import Class1 def function(): from ...module_a import ClassA def inner_function(): from ...subpackage_a.module_1 import Class1 class InnerClass(object): from external import module_a return inner_function
class ClassI(object): from ..module_1 import Class1 def function(): from ...module_a import ClassA def inner_function(): from ...subpackage_a.module_1 import Class1 class InnerClass(object): from external import module_a return inner_function
none
1
2.683448
3
tremendous/__init__.py
ryansb/tremendous
0
6630489
from tremendous.colors import __funcs # This is gross. Sorry. globals().update(__funcs)
from tremendous.colors import __funcs # This is gross. Sorry. globals().update(__funcs)
en
0.949875
# This is gross. Sorry.
1.082042
1
src/comments/views.py
LABETE/srvup_and_drf
0
6630490
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from django.views.generic.detail import DetailView from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from comments.models import Comment from notifications.signals import notify from videos.forms import CommentForm class CommentDetailView(LoginRequiredMixin, FormView, DetailView): model = Comment form_class = CommentForm def get_context_data(self, *args, **kwargs): context = super(CommentDetailView, self).get_context_data( *args, **kwargs) context["comments"] = self.get_object().get_children() context["form"] = self.form_class return context def post(self, *args, **kwargs): form = self.get_form() if form.is_valid(): clean_text = form.cleaned_data["text"] Comment.objects.create_comment( user=self.request.user, text=clean_text, path=self.get_object().get_path, video=self.get_object().video, parent=self.get_object()) affected_users = self.get_object().get_affected_users() #print(self.get_object().get) notify.send(self.request.user, recipient=self.get_object().user, action=self.get_object(), target=self.get_object().video, verb=u'commented', affected_users=affected_users, ) messages.success(self.request, "Thank you for your comment") return HttpResponseRedirect(self.get_object().get_absolute_url()) else: messages.error(self.request, "There was an error") return HttpResponseRedirect(self.get_object().get_absolute_url())
from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from django.views.generic.detail import DetailView from django.views.generic.edit import FormView from braces.views import LoginRequiredMixin from comments.models import Comment from notifications.signals import notify from videos.forms import CommentForm class CommentDetailView(LoginRequiredMixin, FormView, DetailView): model = Comment form_class = CommentForm def get_context_data(self, *args, **kwargs): context = super(CommentDetailView, self).get_context_data( *args, **kwargs) context["comments"] = self.get_object().get_children() context["form"] = self.form_class return context def post(self, *args, **kwargs): form = self.get_form() if form.is_valid(): clean_text = form.cleaned_data["text"] Comment.objects.create_comment( user=self.request.user, text=clean_text, path=self.get_object().get_path, video=self.get_object().video, parent=self.get_object()) affected_users = self.get_object().get_affected_users() #print(self.get_object().get) notify.send(self.request.user, recipient=self.get_object().user, action=self.get_object(), target=self.get_object().video, verb=u'commented', affected_users=affected_users, ) messages.success(self.request, "Thank you for your comment") return HttpResponseRedirect(self.get_object().get_absolute_url()) else: messages.error(self.request, "There was an error") return HttpResponseRedirect(self.get_object().get_absolute_url())
ru
0.145106
#print(self.get_object().get)
2.065968
2
setup.py
jakirkham/dask-distance
9
6630491
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import setuptools from setuptools import setup from setuptools.command.test import test as TestCommand import versioneer class PyTest(TestCommand): description = "Run test suite with pytest" def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest sys.exit(pytest.main(self.test_args)) with open("README.rst") as readme_file: readme = readme_file.read() requirements = [ "dask", "numpy", ] test_requirements = [ "pytest", "scipy", ] cmdclasses = { "test": PyTest, } cmdclasses.update(versioneer.get_cmdclass()) setup( name="dask-distance", version=versioneer.get_version(), description=( "Distance computations with Dask (akin to scipy.spatial.distance)" ), long_description=readme, author="<NAME>", author_email="<EMAIL>", url="https://github.com/jakirkham/dask-distance", cmdclass=cmdclasses, packages=setuptools.find_packages(exclude=["tests*"]), include_package_data=True, install_requires=requirements, license="BSD 3-Clause", zip_safe=False, keywords="dask-distance", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], tests_require=test_requirements )
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import setuptools from setuptools import setup from setuptools.command.test import test as TestCommand import versioneer class PyTest(TestCommand): description = "Run test suite with pytest" def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest sys.exit(pytest.main(self.test_args)) with open("README.rst") as readme_file: readme = readme_file.read() requirements = [ "dask", "numpy", ] test_requirements = [ "pytest", "scipy", ] cmdclasses = { "test": PyTest, } cmdclasses.update(versioneer.get_cmdclass()) setup( name="dask-distance", version=versioneer.get_version(), description=( "Distance computations with Dask (akin to scipy.spatial.distance)" ), long_description=readme, author="<NAME>", author_email="<EMAIL>", url="https://github.com/jakirkham/dask-distance", cmdclass=cmdclasses, packages=setuptools.find_packages(exclude=["tests*"]), include_package_data=True, install_requires=requirements, license="BSD 3-Clause", zip_safe=False, keywords="dask-distance", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], tests_require=test_requirements )
en
0.352855
#!/usr/bin/env python # -*- coding: utf-8 -*-
1.719538
2
setup.py
Breakend/cule
0
6630492
<reponame>Breakend/cule import argparse import os import sys from Cython.Distutils import build_ext from distutils.cmd import Command from setuptools import find_packages, setup, Extension from examples.utils.runtime import Runtime try: from examples.utils.runtime import get_device_props codes = sorted(set([str(p.major) + str(p.minor) for p in get_device_props()])) arch_gencode = ['-arch=sm_' + codes[0]] + ['-gencode=arch=compute_{0},code=sm_{0}'.format(code) for code in codes] except: print('Warning: Could not find nvcc in path. Compiling with default support for all architectures.' 'This may result in exceedingly long startup times during initialization on the GPU.') arch_gencode = [] base_dir = os.path.dirname(os.path.realpath(__file__)) runtime = Runtime() CUDA = runtime._locate() sources = [os.path.join('torchcule', f) for f in ['frontend.cpp', 'backend.cu']] third_party_dir = os.path.join(base_dir, 'third_party') include_dirs = [base_dir, os.path.join(third_party_dir, 'agency'), os.path.join(third_party_dir, 'pybind11', 'include'), CUDA['include']] libraries = ['gomp', 'z'] cxx_flags = ['-std=c++11'] nvcc_flags = arch_gencode + ['-O3', '-Xptxas=-v', '-Xcompiler=-Wall,-Wextra,-fPIC', '-std=c++11'] parser = argparse.ArgumentParser('CuLE', add_help=False) parser.add_argument('--fastbuild', action='store_true', default=False, help='Build CuLE supporting only 2K roms') parser.add_argument('--compiler', type=str, default='gcc', help='Host compiler (default: gcc)') args, remaining_argv = parser.parse_known_args() sys.argv = ['setup.py'] + remaining_argv if args.fastbuild: nvcc_flags += ['-DCULE_FAST_COMPILE'] nvcc_flags += ['-ccbin={}'.format(args.compiler)] def customize_compiler_for_nvcc(self): """Inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on. """ # Tell the compiler it can processes .cu self.src_extensions.append('.cu') # Save references to the default compiler_so and _comple methods default_compiler_so = self.compiler_so super = self._compile # Now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if os.path.splitext(src)[1] == '.cu': # use the cuda for .cu files self.set_executable('compiler_so', CUDA['nvcc']) # use only a subset of the extra_postargs, which are 1-1 # translated from the extra_compile_args in the Extension class postargs = extra_postargs['nvcc'] else: postargs = extra_postargs['gcc'] super(obj, src, ext, cc_args, postargs, pp_opts) # Reset the default compiler_so, which we might have changed for cuda self.compiler_so = default_compiler_so # Inject our redefined _compile method into the class self._compile = _compile # Run the customize_compiler class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self) setup(name='torchcule', version='0.1.0', description='A GPU RL environment package for PyTorch', url='https://github.com/NVlabs/cule', author='<NAME>', author_email='<EMAIL>', install_requires=['gym>=0.9.5'], ext_modules=[ Extension('torchcule_atari', sources=sources, include_dirs=include_dirs, libraries=libraries, extra_compile_args={'gcc': cxx_flags, 'nvcc': nvcc_flags} ) ], # Exclude the build files. packages=find_packages(exclude=['build']), cmdclass={ 'build_ext': custom_build_ext, } )
import argparse import os import sys from Cython.Distutils import build_ext from distutils.cmd import Command from setuptools import find_packages, setup, Extension from examples.utils.runtime import Runtime try: from examples.utils.runtime import get_device_props codes = sorted(set([str(p.major) + str(p.minor) for p in get_device_props()])) arch_gencode = ['-arch=sm_' + codes[0]] + ['-gencode=arch=compute_{0},code=sm_{0}'.format(code) for code in codes] except: print('Warning: Could not find nvcc in path. Compiling with default support for all architectures.' 'This may result in exceedingly long startup times during initialization on the GPU.') arch_gencode = [] base_dir = os.path.dirname(os.path.realpath(__file__)) runtime = Runtime() CUDA = runtime._locate() sources = [os.path.join('torchcule', f) for f in ['frontend.cpp', 'backend.cu']] third_party_dir = os.path.join(base_dir, 'third_party') include_dirs = [base_dir, os.path.join(third_party_dir, 'agency'), os.path.join(third_party_dir, 'pybind11', 'include'), CUDA['include']] libraries = ['gomp', 'z'] cxx_flags = ['-std=c++11'] nvcc_flags = arch_gencode + ['-O3', '-Xptxas=-v', '-Xcompiler=-Wall,-Wextra,-fPIC', '-std=c++11'] parser = argparse.ArgumentParser('CuLE', add_help=False) parser.add_argument('--fastbuild', action='store_true', default=False, help='Build CuLE supporting only 2K roms') parser.add_argument('--compiler', type=str, default='gcc', help='Host compiler (default: gcc)') args, remaining_argv = parser.parse_known_args() sys.argv = ['setup.py'] + remaining_argv if args.fastbuild: nvcc_flags += ['-DCULE_FAST_COMPILE'] nvcc_flags += ['-ccbin={}'.format(args.compiler)] def customize_compiler_for_nvcc(self): """Inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on. """ # Tell the compiler it can processes .cu self.src_extensions.append('.cu') # Save references to the default compiler_so and _comple methods default_compiler_so = self.compiler_so super = self._compile # Now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if os.path.splitext(src)[1] == '.cu': # use the cuda for .cu files self.set_executable('compiler_so', CUDA['nvcc']) # use only a subset of the extra_postargs, which are 1-1 # translated from the extra_compile_args in the Extension class postargs = extra_postargs['nvcc'] else: postargs = extra_postargs['gcc'] super(obj, src, ext, cc_args, postargs, pp_opts) # Reset the default compiler_so, which we might have changed for cuda self.compiler_so = default_compiler_so # Inject our redefined _compile method into the class self._compile = _compile # Run the customize_compiler class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self) setup(name='torchcule', version='0.1.0', description='A GPU RL environment package for PyTorch', url='https://github.com/NVlabs/cule', author='<NAME>', author_email='<EMAIL>', install_requires=['gym>=0.9.5'], ext_modules=[ Extension('torchcule_atari', sources=sources, include_dirs=include_dirs, libraries=libraries, extra_compile_args={'gcc': cxx_flags, 'nvcc': nvcc_flags} ) ], # Exclude the build files. packages=find_packages(exclude=['build']), cmdclass={ 'build_ext': custom_build_ext, } )
en
0.832827
Inject deep into distutils to customize how the dispatch to gcc/nvcc works. If you subclass UnixCCompiler, it's not trivial to get your subclass injected in, and still have the right customizations (i.e. distutils.sysconfig.customize_compiler) run on it. So instead of going the OO route, I have this. Note, it's kindof like a wierd functional subclassing going on. # Tell the compiler it can processes .cu # Save references to the default compiler_so and _comple methods # Now redefine the _compile method. This gets executed for each # object but distutils doesn't have the ability to change compilers # based on source extension: we add it. # use the cuda for .cu files # use only a subset of the extra_postargs, which are 1-1 # translated from the extra_compile_args in the Extension class # Reset the default compiler_so, which we might have changed for cuda # Inject our redefined _compile method into the class # Run the customize_compiler # Exclude the build files.
1.755793
2
loglib/change_detect.py
alanmitchell/mini-monitor
7
6630493
<reponame>alanmitchell/mini-monitor """Functions related to detecting and posting changes in a set of sensor readings. """ def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None): """Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'change_pct' is used to determine a threshold change by multiplying 'change_pct' by the difference between the minimum and maximum value. If 'max_interval' is provided, it will be the maximum allowed separation between returned index values. This forces some some points to be returned even if no signficant change has occurred. Index 0, pointing at the first value is always returned. """ # special case of no values passed if len(vals) == 0: return [] if threshold is None: # compute the threshold difference that constitutes a change # from the change_pct parameter threshold = (max(vals) - min(vals)) * change_pct if threshold == 0.0: threshold = 0.01 # keep it from showing every point # Start with the first value final_ixs = [0] last_val = vals[0] last_ix = 0 for ix in range(1, len(vals)): v = vals[ix] include_this_index = False if abs(v - last_val) >= threshold: # if the prior value was not included, include it if last_ix != ix - 1: final_ixs.append(ix - 1) include_this_index = True elif max_interval is not None and ix - last_ix >= max_interval: include_this_index = True if include_this_index: final_ixs.append(ix) last_val = v last_ix = ix return final_ixs def make_post_lines(sensor_id, time_stamps, values, change_threshold, max_interval): """Returns an array of lines to post to the MQTT broker. Only posts changes in values. 'sensor_id': sensor ID to use for each line 'time_stamps': numpy array of time stamps associated with the values 'values': numpy array of values to scan for changes and post accordingly 'change_threshold': amount of change that needs to occur before inclusion 'max_interval': maximum number of points to separate posts. Will post w/o a change to meet this. """ # find the indexes to include in the post lines ixs = find_changes(values, change_threshold, max_interval=max_interval) ts_incl = time_stamps[ixs] val_incl = values[ixs] return ['%s\t%s\t%s' % (ts, sensor_id, val) for ts, val in zip(ts_incl, val_incl)]
"""Functions related to detecting and posting changes in a set of sensor readings. """ def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None): """Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'change_pct' is used to determine a threshold change by multiplying 'change_pct' by the difference between the minimum and maximum value. If 'max_interval' is provided, it will be the maximum allowed separation between returned index values. This forces some some points to be returned even if no signficant change has occurred. Index 0, pointing at the first value is always returned. """ # special case of no values passed if len(vals) == 0: return [] if threshold is None: # compute the threshold difference that constitutes a change # from the change_pct parameter threshold = (max(vals) - min(vals)) * change_pct if threshold == 0.0: threshold = 0.01 # keep it from showing every point # Start with the first value final_ixs = [0] last_val = vals[0] last_ix = 0 for ix in range(1, len(vals)): v = vals[ix] include_this_index = False if abs(v - last_val) >= threshold: # if the prior value was not included, include it if last_ix != ix - 1: final_ixs.append(ix - 1) include_this_index = True elif max_interval is not None and ix - last_ix >= max_interval: include_this_index = True if include_this_index: final_ixs.append(ix) last_val = v last_ix = ix return final_ixs def make_post_lines(sensor_id, time_stamps, values, change_threshold, max_interval): """Returns an array of lines to post to the MQTT broker. Only posts changes in values. 'sensor_id': sensor ID to use for each line 'time_stamps': numpy array of time stamps associated with the values 'values': numpy array of values to scan for changes and post accordingly 'change_threshold': amount of change that needs to occur before inclusion 'max_interval': maximum number of points to separate posts. Will post w/o a change to meet this. """ # find the indexes to include in the post lines ixs = find_changes(values, change_threshold, max_interval=max_interval) ts_incl = time_stamps[ixs] val_incl = values[ixs] return ['%s\t%s\t%s' % (ts, sensor_id, val) for ts, val in zip(ts_incl, val_incl)]
en
0.87073
Functions related to detecting and posting changes in a set of sensor readings. Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'change_pct' is used to determine a threshold change by multiplying 'change_pct' by the difference between the minimum and maximum value. If 'max_interval' is provided, it will be the maximum allowed separation between returned index values. This forces some some points to be returned even if no signficant change has occurred. Index 0, pointing at the first value is always returned. # special case of no values passed # compute the threshold difference that constitutes a change # from the change_pct parameter # keep it from showing every point # Start with the first value # if the prior value was not included, include it Returns an array of lines to post to the MQTT broker. Only posts changes in values. 'sensor_id': sensor ID to use for each line 'time_stamps': numpy array of time stamps associated with the values 'values': numpy array of values to scan for changes and post accordingly 'change_threshold': amount of change that needs to occur before inclusion 'max_interval': maximum number of points to separate posts. Will post w/o a change to meet this. # find the indexes to include in the post lines
3.50892
4
zoo/vgg/vgg_c.py
sujeet-ap/keras-idiomatic-programmer
3
6630494
<reponame>sujeet-ap/keras-idiomatic-programmer<gh_stars>1-10 # Copyright 2019 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 # # 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. # VGG (16 and 19 & Composable) (2014) # Trainable params: 138,357,544 # Paper: https://arxiv.org/pdf/1409.1556.pdf import tensorflow as tf from tensorflow.keras import Input, Model from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation from tensorflow.keras.regularizers import l2 import sys sys.path.append('../') from models_c import Composable class VGG(Composable): """ VGG (composable) """ # Meta-parameter: list of groups: number of layers and filter size groups = { 16 : [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 3, 'n_filters': 256 }, { 'n_layers': 3, 'n_filters': 512 }, { 'n_layers': 3, 'n_filters': 512 } ], # VGG16 19 : [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 4, 'n_filters': 256 }, { 'n_layers': 4, 'n_filters': 512 }, { 'n_layers': 4, 'n_filters': 512 } ] } # VGG19 def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True): """ Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shape : input shape to the model n_classes: : number of output classes include_top : whether to include classifier reg : kernel regularizer init_weights: kernel initializer relu : max value for ReLU bias : whether to use bias """ # Configure the base (super) class super().__init__(init_weights=init_weights, reg=reg, relu=relu, bias=bias) # predefined if isinstance(n_layers, int): if n_layers not in [16, 19]: raise Exception("VGG: Invalid value for n_layers") blocks = list(self.groups[n_layers]) # user defined else: blocks = n_layers # The input vector inputs = Input(input_shape) # The stem group x = self.stem(inputs) # The learner outputs = self.learner(x, blocks=blocks) # The classifier if include_top: outputs = self.classifier(outputs, n_classes) # Instantiate the Model self._model = Model(inputs, outputs) def stem(self, inputs): """ Construct the Stem Convolutional Group inputs : the input vector """ x = self.Conv2D(inputs, 64, (3, 3), strides=(1, 1), padding="same") x = self.ReLU(x) return x def learner(self, x, **metaparameters): """ Construct the (Feature) Learner x : input to the learner blocks : list of groups: filter size and number of conv layers """ blocks = metaparameters['blocks'] # The convolutional groups for block in blocks: x = self.group(x, **block, **metaparameters) return x def group(self, x, **metaparameters): """ Construct a Convolutional Group x : input to the group n_layers : number of convolutional layers n_filters: number of filters """ n_filters = metaparameters['n_filters'] n_layers = metaparameters['n_layers'] del metaparameters['n_filters'] # Block of convolutional layers for n in range(n_layers): x = self.Conv2D(x, n_filters, (3, 3), strides=(1, 1), padding="same", activation=self.ReLU, **metaparameters) # Max pooling at the end of the block x = MaxPooling2D(2, strides=(2, 2))(x) return x def classifier(self, x, n_classes): """ Construct the Classifier x : input to the classifier n_classes : number of output classes """ # Save the encoding layer self.encoding = x # Flatten the feature maps x = Flatten()(x) # Save the embedding layer self.embedding = x # Two fully connected dense layers x = self.Dense(x, 4096, activation=self.ReLU) x = self.Dense(x, 4096, activation=self.ReLU) outputs = super().classifier(x, n_classes, pooling=None) return outputs # Example stock VGG16 # vgg = VGG(16) def example(): ''' Example for constructing/training a VGG model on CIFAR-10 ''' # Example of constructing a mini-VGG groups = [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 2, 'n_filters': 256 } ] vgg = VGG(groups, input_shape=(32, 32, 3), n_classes=10) vgg.model.summary() # train on CIFAR-10 vgg.cifar10() # example()
# Copyright 2019 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 # # 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. # VGG (16 and 19 & Composable) (2014) # Trainable params: 138,357,544 # Paper: https://arxiv.org/pdf/1409.1556.pdf import tensorflow as tf from tensorflow.keras import Input, Model from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Activation from tensorflow.keras.regularizers import l2 import sys sys.path.append('../') from models_c import Composable class VGG(Composable): """ VGG (composable) """ # Meta-parameter: list of groups: number of layers and filter size groups = { 16 : [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 3, 'n_filters': 256 }, { 'n_layers': 3, 'n_filters': 512 }, { 'n_layers': 3, 'n_filters': 512 } ], # VGG16 19 : [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 4, 'n_filters': 256 }, { 'n_layers': 4, 'n_filters': 512 }, { 'n_layers': 4, 'n_filters': 512 } ] } # VGG19 def __init__(self, n_layers, input_shape=(224, 224, 3), n_classes=1000, include_top=True, reg=None, init_weights='glorot_uniform', relu=None, bias=True): """ Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shape : input shape to the model n_classes: : number of output classes include_top : whether to include classifier reg : kernel regularizer init_weights: kernel initializer relu : max value for ReLU bias : whether to use bias """ # Configure the base (super) class super().__init__(init_weights=init_weights, reg=reg, relu=relu, bias=bias) # predefined if isinstance(n_layers, int): if n_layers not in [16, 19]: raise Exception("VGG: Invalid value for n_layers") blocks = list(self.groups[n_layers]) # user defined else: blocks = n_layers # The input vector inputs = Input(input_shape) # The stem group x = self.stem(inputs) # The learner outputs = self.learner(x, blocks=blocks) # The classifier if include_top: outputs = self.classifier(outputs, n_classes) # Instantiate the Model self._model = Model(inputs, outputs) def stem(self, inputs): """ Construct the Stem Convolutional Group inputs : the input vector """ x = self.Conv2D(inputs, 64, (3, 3), strides=(1, 1), padding="same") x = self.ReLU(x) return x def learner(self, x, **metaparameters): """ Construct the (Feature) Learner x : input to the learner blocks : list of groups: filter size and number of conv layers """ blocks = metaparameters['blocks'] # The convolutional groups for block in blocks: x = self.group(x, **block, **metaparameters) return x def group(self, x, **metaparameters): """ Construct a Convolutional Group x : input to the group n_layers : number of convolutional layers n_filters: number of filters """ n_filters = metaparameters['n_filters'] n_layers = metaparameters['n_layers'] del metaparameters['n_filters'] # Block of convolutional layers for n in range(n_layers): x = self.Conv2D(x, n_filters, (3, 3), strides=(1, 1), padding="same", activation=self.ReLU, **metaparameters) # Max pooling at the end of the block x = MaxPooling2D(2, strides=(2, 2))(x) return x def classifier(self, x, n_classes): """ Construct the Classifier x : input to the classifier n_classes : number of output classes """ # Save the encoding layer self.encoding = x # Flatten the feature maps x = Flatten()(x) # Save the embedding layer self.embedding = x # Two fully connected dense layers x = self.Dense(x, 4096, activation=self.ReLU) x = self.Dense(x, 4096, activation=self.ReLU) outputs = super().classifier(x, n_classes, pooling=None) return outputs # Example stock VGG16 # vgg = VGG(16) def example(): ''' Example for constructing/training a VGG model on CIFAR-10 ''' # Example of constructing a mini-VGG groups = [ { 'n_layers': 1, 'n_filters': 64 }, { 'n_layers': 2, 'n_filters': 128 }, { 'n_layers': 2, 'n_filters': 256 } ] vgg = VGG(groups, input_shape=(32, 32, 3), n_classes=10) vgg.model.summary() # train on CIFAR-10 vgg.cifar10() # example()
en
0.691981
# Copyright 2019 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 # # 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. # VGG (16 and 19 & Composable) (2014) # Trainable params: 138,357,544 # Paper: https://arxiv.org/pdf/1409.1556.pdf VGG (composable) # Meta-parameter: list of groups: number of layers and filter size # VGG16 # VGG19 Construct a VGG model n_layers : number of layers (16 or 19) or metaparameter for blocks input_shape : input shape to the model n_classes: : number of output classes include_top : whether to include classifier reg : kernel regularizer init_weights: kernel initializer relu : max value for ReLU bias : whether to use bias # Configure the base (super) class # predefined # user defined # The input vector # The stem group # The learner # The classifier # Instantiate the Model Construct the Stem Convolutional Group inputs : the input vector Construct the (Feature) Learner x : input to the learner blocks : list of groups: filter size and number of conv layers # The convolutional groups Construct a Convolutional Group x : input to the group n_layers : number of convolutional layers n_filters: number of filters # Block of convolutional layers # Max pooling at the end of the block Construct the Classifier x : input to the classifier n_classes : number of output classes # Save the encoding layer # Flatten the feature maps # Save the embedding layer # Two fully connected dense layers # Example stock VGG16 # vgg = VGG(16) Example for constructing/training a VGG model on CIFAR-10 # Example of constructing a mini-VGG # train on CIFAR-10 # example()
1.860335
2
Python3/789.escape-the-ghosts.py
610yilingliu/leetcode
0
6630495
# # @lc app=leetcode id=789 lang=python3 # # [789] Escape The Ghosts # # @lc code=start class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]): my_dist = abs(target[0]) + abs(target[1]) for ghost in ghosts: curdist = abs(ghost[0] - target[0]) + abs(ghost[1] - target[1]) if curdist < my_dist: return False return True # @lc code=end
# # @lc app=leetcode id=789 lang=python3 # # [789] Escape The Ghosts # # @lc code=start class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]): my_dist = abs(target[0]) + abs(target[1]) for ghost in ghosts: curdist = abs(ghost[0] - target[0]) + abs(ghost[1] - target[1]) if curdist < my_dist: return False return True # @lc code=end
en
0.478972
# # @lc app=leetcode id=789 lang=python3 # # [789] Escape The Ghosts # # @lc code=start # @lc code=end
2.97045
3
test/discovery/test_stub.py
ezh/cloudselect
4
6630496
<gh_stars>1-10 # Copyright 2019 <NAME> and individual contributors # See the LICENSE.txt file at the top-level directory of this distribution. # # Licensed under the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT> # This file may not be copied, modified, or distributed # except according to those terms. """This module is used for testing Stub discovery plugin.""" from cloudselect import Container from cloudselect.cloudselect import CloudSelect from cloudselect.discovery import DiscoveryServiceProvider from cloudselect.discovery.stub import Stub def test_stub_discovery(cfgdir): """ Testing Stub initializaion. Is fabric creating Stub by default? Does Stub return []? Is Stub singleton? """ cloud = CloudSelect(cfgdir) # Read shared part profile = cloud.configuration_read() args = cloud.parse_args([]) cloud.fabric(profile, args) assert Container.discovery().__class__.__name__ == "Stub" assert Container.discovery().run() == [] assert Container.discovery() == Container.discovery() def test_stub_behaviour(mocker, cfgdir): """Assert calling run() for "cloudselect.discovery.stub" plugin.""" cloud = CloudSelect(cfgdir) service_provider = cloud.plugin( "cloudselect.discovery.stub", DiscoveryServiceProvider, ) stub = service_provider() mocker.patch.object(Stub, "run") stub.run() Stub.run.assert_called_once_with()
# Copyright 2019 <NAME> and individual contributors # See the LICENSE.txt file at the top-level directory of this distribution. # # Licensed under the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT> # This file may not be copied, modified, or distributed # except according to those terms. """This module is used for testing Stub discovery plugin.""" from cloudselect import Container from cloudselect.cloudselect import CloudSelect from cloudselect.discovery import DiscoveryServiceProvider from cloudselect.discovery.stub import Stub def test_stub_discovery(cfgdir): """ Testing Stub initializaion. Is fabric creating Stub by default? Does Stub return []? Is Stub singleton? """ cloud = CloudSelect(cfgdir) # Read shared part profile = cloud.configuration_read() args = cloud.parse_args([]) cloud.fabric(profile, args) assert Container.discovery().__class__.__name__ == "Stub" assert Container.discovery().run() == [] assert Container.discovery() == Container.discovery() def test_stub_behaviour(mocker, cfgdir): """Assert calling run() for "cloudselect.discovery.stub" plugin.""" cloud = CloudSelect(cfgdir) service_provider = cloud.plugin( "cloudselect.discovery.stub", DiscoveryServiceProvider, ) stub = service_provider() mocker.patch.object(Stub, "run") stub.run() Stub.run.assert_called_once_with()
en
0.719138
# Copyright 2019 <NAME> and individual contributors # See the LICENSE.txt file at the top-level directory of this distribution. # # Licensed under the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT> # This file may not be copied, modified, or distributed # except according to those terms. This module is used for testing Stub discovery plugin. Testing Stub initializaion. Is fabric creating Stub by default? Does Stub return []? Is Stub singleton? # Read shared part Assert calling run() for "cloudselect.discovery.stub" plugin.
1.92073
2
EngVer/UpdateGoogleDrive.py
0xf3cd/Chinese-Resume
0
6630497
import os from pydrive import auth, drive def UpdateFile(file_id, src_path): f = drive.CreateFile({'id': file_id}) f.SetContentFile(src_path) f.Upload() def CreateFile(parent_folder_id, file_name, src_path): f = drive.CreateFile({ 'title': file_name, 'parents': [{'id': parent_folder_id}], }) f.SetContentFile(src_path) f.Upload() FOLDER_ID = '10CgNO2GlpE6MgC4B-WWOFdWxPMBMfeIp' RESUME_PATH = './EngVer.pdf' DEST_FILE_NAME = 'Resume-NingqiWang.pdf' g_auth = auth.GoogleAuth() g_auth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. drive = drive.GoogleDrive(g_auth) # Create or update the resume file_list = drive.ListFile({ 'q': f"'{FOLDER_ID}' in parents and trashed=false" }).GetList() for f_data in file_list: f_name = f_data['title'] if f_name == DEST_FILE_NAME: UpdateFile(f_data['id'], RESUME_PATH) os._exit(0) # At this point, we can make sure that the .pdf file has not been uploaded yet CreateFile(FOLDER_ID, DEST_FILE_NAME, RESUME_PATH)
import os from pydrive import auth, drive def UpdateFile(file_id, src_path): f = drive.CreateFile({'id': file_id}) f.SetContentFile(src_path) f.Upload() def CreateFile(parent_folder_id, file_name, src_path): f = drive.CreateFile({ 'title': file_name, 'parents': [{'id': parent_folder_id}], }) f.SetContentFile(src_path) f.Upload() FOLDER_ID = '10CgNO2GlpE6MgC4B-WWOFdWxPMBMfeIp' RESUME_PATH = './EngVer.pdf' DEST_FILE_NAME = 'Resume-NingqiWang.pdf' g_auth = auth.GoogleAuth() g_auth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. drive = drive.GoogleDrive(g_auth) # Create or update the resume file_list = drive.ListFile({ 'q': f"'{FOLDER_ID}' in parents and trashed=false" }).GetList() for f_data in file_list: f_name = f_data['title'] if f_name == DEST_FILE_NAME: UpdateFile(f_data['id'], RESUME_PATH) os._exit(0) # At this point, we can make sure that the .pdf file has not been uploaded yet CreateFile(FOLDER_ID, DEST_FILE_NAME, RESUME_PATH)
en
0.937672
# Creates local webserver and auto handles authentication. # Create or update the resume # At this point, we can make sure that the .pdf file has not been uploaded yet
2.761962
3
projects/VISOLO/visolo/visolo.py
SuHoHan95/VISOLO
0
6630498
<filename>projects/VISOLO/visolo/visolo.py<gh_stars>0 import math import numpy as np import torch import torch.nn.functional as F from torch import nn import copy import cv2 from scipy.ndimage.morphology import binary_dilation from PIL import Image, ImageDraw, ImageFont import os from detectron2.modeling import META_ARCH_REGISTRY, build_backbone from detectron2.structures import Boxes, ImageList, Instances from .models.visolo_model import VISOLO, SetCriterion, DataUtils __all__ = ["Visolo"] @META_ARCH_REGISTRY.register() class Visolo(nn.Module): def __init__(self, cfg): super().__init__() self.num_frames = cfg.INPUT.SAMPLING_FRAME_NUM self.data_eps = cfg.INPUT.SAMPLING_EPS self.device = torch.device(cfg.MODEL.DEVICE) self.num_class = cfg.MODEL.VISOLO.NUM_CLASSES self.mask_weight = cfg.MODEL.VISOLO.MASK_WEIGHT self.FL_alpha = cfg.MODEL.VISOLO.FOCAL_LOSS_ALPHA self.FL_gamma = cfg.MODEL.VISOLO.FOCAL_LOSS_GAMMA self.DL_eps = cfg.MODEL.VISOLO.DICE_LOSS_EPS self.S = cfg.MODEL.VISOLO.GRID_NUM self.indim = cfg.MODEL.VISOLO.INDIM self.outdim = cfg.MODEL.VISOLO.OUTDIM self.norm = cfg.MODEL.VISOLO.NORM self.tracking_thr = cfg.MODEL.VISOLO.TRACKING_THR self.score_thr = cfg.MODEL.VISOLO.SCORE_THR self.mask_thr = cfg.MODEL.VISOLO.MASK_THR self.update_thr = cfg.MODEL.VISOLO.UPDATE_THR self.kernel = cfg.MODEL.VISOLO.KERNEL self.sigma = cfg.MODEL.VISOLO.SIGMA self.nms_pre = cfg.MODEL.VISOLO.NMS_PRE backbone = build_backbone(cfg) backbone_features = cfg.MODEL.RESNETS.OUT_FEATURES self.model = VISOLO(backbone, backbone_features, self.S, self.num_class, self.indim, self.outdim, self.norm) self.criterion = SetCriterion(self.FL_alpha, self.FL_gamma, self.DL_eps, self.mask_weight) self.data_utils = DataUtils(self.device, self.num_class, self.S, self.data_eps) self.tracking_module = self.model.Tracking_branch pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(3, 1, 1) pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(3, 1, 1) self.normalizer = lambda x: (x - pixel_mean) / pixel_std self.to(self.device) def preprocess_image(self, batched_inputs, is_eval=False): B = len(batched_inputs) N = len(batched_inputs[0]['image']) dim, H, W = batched_inputs[0]['image'][0].size() frames = torch.zeros((B, dim, N, H, W), dtype=torch.float32, device=self.device) for b in range(B): for n in range(N): frames[b,:,n,:,:] = self.normalizer(batched_inputs[b]['image'][n].to(self.device)) if is_eval: return frames, batched_inputs[0]['height'], batched_inputs[0]['width'], batched_inputs[0]['video_id'] else: return frames def getCandidateDict(self, f_idx, valid_idx, tra_feature, idx_to_inst): candidate = {} candidate['f_idx'] = f_idx candidate['valid_idx'] = valid_idx candidate['tra_feature'] = tra_feature candidate['idx_mapping'] = idx_to_inst return candidate def forward(self, batched_inputs): if self.training: frames = self.preprocess_image(batched_inputs) pred_masks, pred_kernels, pred_cats, pred_tracking = self.model(frames) GT_masks, GT_classes, GT_tracking = self.data_utils.getGridGT(batched_inputs) loss_dict = self.criterion(pred_cats, pred_masks, pred_kernels, pred_tracking, GT_classes, GT_masks, GT_tracking) return loss_dict else: frames, v_h, v_w, v_id = self.preprocess_image(batched_inputs, is_eval=True) N = frames.size()[2] tra_candidates = [] pred_masks_0, pred_kernel_0, pred_cats_0, frame_f, cat_f, kernel_f = self.model(frames[:, :, 0, :, :], None, None, None) m_frame_f = frame_f.unsqueeze(2) m_cat_f = cat_f.unsqueeze(2) m_kernel_f = kernel_f.unsqueeze(2) pred_masks_1, pred_kernel_1, pred_cats_1, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, 1, :, :], frame_f, cat_f, kernel_f) grid_weight = None inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ _, _, tra_candidates, f0_valid_ind \ = self.getTestResultV4(pred_masks_0[0], pred_kernel_0[0], pred_cats_0[0], pred_tracking[0], None, m_frame_f[:, :, -1, :, :], N, 0, [], [], [], [], None, None, [], tra_candidates) m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) pred_masks_2, pred_kernel_2, pred_cats_2, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, 2, :, :], m_frame_f, m_cat_f, m_kernel_f) grid_weight = self.model(m_frame_f[:, :, -2, :, :], m_frame_f[:, :, -1, :, :], None) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], pred_tracking[0], grid_weight, m_frame_f[:, :, -1, :, :], N, 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) if pre_inst_tra_check is not None and (pre_inst_tra_check == 0).sum() > 0: pre_valid_ind = f0_valid_ind[pre_inst_tra_check == 0] tra_candidates.append(self.getCandidateDict(0, pre_valid_ind, m_frame_f[:, :, -2, :, :], pre_ind_map_inst)) m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) pred_masks_1 = pred_masks_2.clone() pred_kernel_1 = pred_kernel_2.clone() pred_cats_1 = pred_cats_2.clone() if f1_valid_ind is not None: f0_valid_ind = f1_valid_ind.clone() else: f0_valid_ind = f1_valid_ind for n in range(3, N + 1): if n == N: grid_weight = self.model(m_frame_f[:,:,-2,:,:], m_frame_f[:,:,-1,:,:], m_frame_f[:,:,-3,:,:]) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], None, grid_weight, m_frame_f[:,:,-1,:,:], N, n - 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) continue pred_masks_2, pred_kernel_2, pred_cats_2, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, n, :, :], m_frame_f, m_cat_f, m_kernel_f) # B,S**2,1,H,W / B,C,1,S,S / B,1,S**2,S**2 grid_weight = self.model(m_frame_f[:,:,-2,:,:], m_frame_f[:,:,-1,:,:], m_frame_f[:,:,-3,:,:]) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], pred_tracking[0], grid_weight, m_frame_f[:,:,-1,:,:], N, n - 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) if pre_inst_tra_check is not None and (pre_inst_tra_check == 0).sum() > 0: pre_valid_ind = f0_valid_ind[pre_inst_tra_check == 0] tra_candidates.append(self.getCandidateDict(n - 2, pre_valid_ind, m_frame_f[:,:,-2,:,:], pre_ind_map_inst)) if n % 5 == 2: m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) else: m_frame_f = torch.cat((m_frame_f[:, :, :-2], m_frame_f[:, :, -1:], frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f[:, :, :-2], m_cat_f[:, :, -1:], cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f[:, :, :-2], m_kernel_f[:, :, -1:], kernel_f.unsqueeze(2)), dim=2) pred_masks_1 = pred_masks_2.clone() pred_kernel_1 = pred_kernel_2.clone() pred_cats_1 = pred_cats_2.clone() if f1_valid_ind is not None: f0_valid_ind = f1_valid_ind.clone() else: f0_valid_ind = f1_valid_ind if isinstance(inst_masks, list): return None inst_masks = F.interpolate(inst_masks, (v_h, v_w), mode='bilinear', align_corners=False) inst_masks = (inst_masks >= self.mask_thr).float() new_inst_cat_scores, new_inst_cats = self.getAverageCat(inst_cat_scores_ori) video_output = { "pred_scores": new_inst_cat_scores, "pred_labels": new_inst_cats, "pred_masks": inst_masks, } return video_output def getAverageCat(self, cat_scores_ori): # cat_scores_ori: K, v_l, 40 K, L, _ = cat_scores_ori.size() valid_frame_num = torch.count_nonzero(torch.sum(cat_scores_ori, dim=2), dim=1).view(K, 1) avg_scores = torch.div(torch.sum(cat_scores_ori, dim=1), valid_frame_num.expand(K, self.num_class)) cat_scores, cats = torch.max(avg_scores, dim=1) return cat_scores, cats def getTestResultV4(self, N_pred_masks, N_pred_kernels, N_pred_cats, N_pred_tra, grid_weight, tra_feature, N, f_idx, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result=None, valid_tra=None, valid_ind_map_to_inst=None, tra_candidates=None): # N_pred_masks : dim, 1, H/4, W/4 # N_pred_kernels : dim, 1, S1, S2 # N_pred_cats : C, 1, S1, S2 # N_pred_tra : 1, S1*S2, S1*S2 inst_masks = inst_masks # K, N, H, W inst_cats = inst_cats # K, N inst_cat_scores = inst_cat_scores # K, N inst_cat_scores_ori = inst_cat_scores_ori # K, N, 40 f0_result = f0_result valid_tra = valid_tra valid_ind_map_to_inst = valid_ind_map_to_inst N = N f_idx = f_idx pre_inst_tra_check = None pre_ind_map_inst = None f0_valid_ind = None if grid_weight is not None: grid_weight = grid_weight[0,0] if f0_result is None: f0_result = self.getSegMaskV5(N_pred_masks[:,0,:,:], N_pred_kernels[:,0,:,:], N_pred_cats[:,0,:,:], grid_weight) if f0_result is not None: f0_seg_masks, f0_cat_labels, f0_cat_scores, f0_cat_scores_ori, f0_valid_ind = f0_result k0, _, _ = f0_seg_masks.size() if f_idx != N - 1: valid_tra = N_pred_tra[0, f0_valid_ind, :] # k0, S**2 inst_num = len(inst_masks) no_match_ind = [x for x in range(k0)] inst_idx, tra_candidates = self.getTrackInfo(tra_candidates, tra_feature, no_match_ind, valid_ind=f0_valid_ind) map_num = 0 for i in range(k0): if inst_idx[i] != -1: if inst_masks[inst_idx[i]][f_idx].sum() != 0: print('Error and mask in inst track!!!') exit() else: inst_masks[inst_idx[i]][f_idx] = f0_seg_masks[i, :, :] inst_cats[inst_idx[i]][f_idx] = f0_cat_labels[i] inst_cat_scores[inst_idx[i]][f_idx] = f0_cat_scores[i] inst_cat_scores_ori[inst_idx[i]][f_idx] = f0_cat_scores_ori[i] valid_ind_map_to_inst.append(inst_idx[i]) else: _, H, W = f0_seg_masks.size() masks = torch.zeros((1, N, H, W), device=self.device) cats = torch.full((1, N), -1, device=self.device) cat_scores = torch.zeros((1, N), device=self.device) cat_scores_ori = torch.zeros((1, N, self.num_class), device=self.device) masks[0, f_idx] = f0_seg_masks[i, :, :] cats[0, f_idx] = f0_cat_labels[i] cat_scores[0, f_idx] = f0_cat_scores[i] cat_scores_ori[0, f_idx] = f0_cat_scores_ori[i] if isinstance(inst_masks, list): inst_masks = masks inst_cats = cats inst_cat_scores = cat_scores inst_cat_scores_ori = cat_scores_ori else: inst_masks = torch.cat((inst_masks, masks), dim=0) inst_cats = torch.cat((inst_cats, cats), dim=0) inst_cat_scores = torch.cat((inst_cat_scores, cat_scores), dim=0) inst_cat_scores_ori = torch.cat((inst_cat_scores_ori, cat_scores_ori), dim=0) valid_ind_map_to_inst.append(inst_num + map_num) map_num+=1 else: f0_result = self.getSegMaskV5(N_pred_masks[:,0,:,:], N_pred_kernels[:,0,:,:], N_pred_cats[:,0,:,:], grid_weight) if f0_result is not None: f0_seg_masks, f0_cat_labels, f0_cat_scores, f0_cat_scores_ori, f0_valid_ind = f0_result k1, _, _ = f0_seg_masks.size() no_match_ind = [] temp_map_ind = [0 for _ in range(k1)] pre_inst_tra_check = torch.zeros((valid_tra.size()[0])) inst_num = len(inst_masks) valid_tra = valid_tra[:, f0_valid_ind] # k0, k1 for i in range(k1): tra_sort_ind = torch.argsort(valid_tra[:, i], descending=True) check_match = 0 for ind in tra_sort_ind: inst_map_ind = valid_ind_map_to_inst[int(ind)] if inst_masks[inst_map_ind][f_idx].sum() == 0 and valid_tra[int(ind), i] >= self.tracking_thr: inst_masks[inst_map_ind][f_idx] = f0_seg_masks[i, :, :] inst_cats[inst_map_ind][f_idx] = f0_cat_labels[i] inst_cat_scores[inst_map_ind][f_idx] = f0_cat_scores[i] inst_cat_scores_ori[inst_map_ind][f_idx] = f0_cat_scores_ori[i] check_match = 1 temp_map_ind[i] = inst_map_ind pre_inst_tra_check[int(ind)] = 1 break if check_match == 0: no_match_ind.append(i) valid_ind = f0_valid_ind[no_match_ind] inst_idx, tra_candidates = self.getTrackInfo(tra_candidates, tra_feature, no_match_ind, valid_ind=valid_ind) map_num = 0 for i in range(len(no_match_ind)): ind = no_match_ind[i] if inst_idx[i] != -1: if inst_masks[inst_idx[i]][f_idx].sum() != 0: print('Error add mask in inst track!!!') exit() else: inst_masks[inst_idx[i]][f_idx] = f0_seg_masks[ind, :, :] inst_cats[inst_idx[i]][f_idx] = f0_cat_labels[ind] inst_cat_scores[inst_idx[i]][f_idx] = f0_cat_scores[ind] inst_cat_scores_ori[inst_idx[i]][f_idx] = f0_cat_scores_ori[ind] temp_map_ind[ind] = inst_idx[i] else: _, H, W = f0_seg_masks.size() masks = torch.zeros((1, N, H, W), device=self.device) cats = torch.full((1, N), -1, device=self.device) cat_scores = torch.zeros((1, N), device=self.device) cat_scores_ori = torch.zeros((1, N, self.num_class), device=self.device) masks[0, f_idx] = f0_seg_masks[ind, :, :] cats[0, f_idx] = f0_cat_labels[ind] cat_scores[0, f_idx] = f0_cat_scores[ind] cat_scores_ori[0, f_idx] = f0_cat_scores_ori[ind] inst_masks = torch.cat((inst_masks, masks), dim=0) inst_cats = torch.cat((inst_cats, cats), dim=0) inst_cat_scores = torch.cat((inst_cat_scores, cat_scores), dim=0) inst_cat_scores_ori = torch.cat((inst_cat_scores_ori, cat_scores_ori), dim=0) temp_map_ind[ind] = inst_num + map_num map_num += 1 pre_ind_map_inst = [k for idx, k in enumerate(valid_ind_map_to_inst) if pre_inst_tra_check[idx] == 0] valid_ind_map_to_inst = temp_map_ind if f_idx != N - 1: valid_tra = N_pred_tra[0, f0_valid_ind, :] # k1, S**2 else: pre_inst_tra_check = torch.zeros((valid_tra.size()[0])) pre_ind_map_inst = copy.deepcopy(valid_ind_map_to_inst) valid_tra = None valid_ind_map_to_inst = [] return inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori,\ f0_result, valid_tra, valid_ind_map_to_inst,\ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f0_valid_ind def getSegMaskV5(self, pred_masks, pred_kernels, pred_cats, grid_weight): # pred_masks : dim, H/4, W/4 # pred_kernels : dim, S1, S2 # pred_cats : C, S1, S2 # grid_weight : S1*S2 _, H, W = pred_masks.size() C, S1, S2 = pred_cats.size() cat_scores = pred_cats.reshape(-1, S1 * S2).transpose(1, 0) # S**2, C cat_scores_ori = cat_scores.clone() cat_scores, cat_labels = cat_scores.max(1) # S**2 if grid_weight is not None: cat_scores *= grid_weight cat_scores[cat_scores < self.score_thr] = 0. valid_ind = cat_scores.nonzero()[:, 0] if valid_ind.sum() == 0: return None kernels = pred_kernels.reshape(-1, S1*S2).transpose(1, 0) # S1*S2, dim kernels = kernels[valid_ind] seg_preds = self.getMaskMap(pred_masks, kernels) seg_masks = (seg_preds > self.mask_thr).float() cat_scores = cat_scores[valid_ind] cat_labels = cat_labels[valid_ind] sum_masks = seg_masks.sum((1, 2)).float() seg_scores = (seg_preds * seg_masks.float()).sum((1, 2)) / sum_masks cat_scores *= seg_scores sort_ind = torch.argsort(cat_scores, descending=True) if sort_ind.size()[0] > self.nms_pre: sort_ind = sort_ind[:self.nms_pre] seg_masks = seg_masks[sort_ind, :, :] cat_scores = cat_scores[sort_ind] cat_labels = cat_labels[sort_ind] valid_ind = valid_ind[sort_ind] cat_scores = self.matrix_nms(seg_masks, cat_labels, cat_scores) keep = cat_scores >= self.update_thr if keep.sum() == 0: return None seg_masks = seg_masks[keep, :, :] cat_scores = cat_scores[keep] cat_labels = cat_labels[keep] valid_ind = valid_ind[keep] sort_ind = torch.argsort(cat_scores, descending=True) if sort_ind.size()[0] > 100: sort_ind = sort_ind[:100] seg_masks = seg_masks[sort_ind, :, :] cat_scores = cat_scores[sort_ind] cat_labels = cat_labels[sort_ind] valid_ind = valid_ind[sort_ind] cat_scores_ori = cat_scores_ori[valid_ind, :] for i in range(len(valid_ind) - 1): if seg_masks[i].sum() == 0: continue for j in range(i + 1, len(valid_ind)): inter_region = (seg_masks[i] * seg_masks[j]).sum() mask_region = seg_masks[j].sum() if inter_region / mask_region > 0.5: seg_masks[j] = 0 final_valid_ind = (seg_masks.sum((1, 2)) > 0) seg_masks = seg_masks[final_valid_ind, :, :] cat_scores = cat_scores[final_valid_ind] cat_labels = cat_labels[final_valid_ind] cat_scores_ori = cat_scores_ori[final_valid_ind, :] valid_ind = valid_ind[final_valid_ind] return seg_masks, cat_labels, cat_scores, cat_scores_ori, valid_ind def matrix_nms(self, seg_masks, cate_labels, cate_scores, sum_masks=None): """Matrix NMS for multi-class masks. Args: seg_masks (Tensor): shape (n, h, w) cate_labels (Tensor): shape (n), mask labels in descending order cate_scores (Tensor): shape (n), mask scores in descending order self.kernel (str): 'linear' or 'gauss' self.sigma (float): std in gaussian method sum_masks (Tensor): The sum of seg_masks Returns: Tensor: cate_scores_update, tensors of shape (n) """ n_samples = len(cate_labels) if n_samples == 0: return [] if sum_masks is None: sum_masks = seg_masks.sum((1, 2)).float() seg_masks = seg_masks.reshape(n_samples, -1).float() # inter. inter_matrix = torch.mm(seg_masks, seg_masks.transpose(1, 0)) # union. sum_masks_x = sum_masks.expand(n_samples, n_samples) # iou. iou_matrix = (inter_matrix / (sum_masks_x + sum_masks_x.transpose(1, 0) - inter_matrix)).triu(diagonal=1) # label_specific matrix. cate_labels_x = cate_labels.expand(n_samples, n_samples) label_matrix = (cate_labels_x == cate_labels_x.transpose(1, 0)) label_matrix = label_matrix.float().triu(diagonal=1) # IoU compensation compensate_iou, _ = (iou_matrix * label_matrix).max(0) compensate_iou = compensate_iou.expand(n_samples, n_samples).transpose(1, 0) # IoU decay decay_iou = iou_matrix * label_matrix # matrix nms if self.kernel == 'gaussian': decay_matrix = torch.exp(-1 * self.sigma * (decay_iou ** 2)) compensate_matrix = torch.exp(-1 * self.sigma * (compensate_iou ** 2)) decay_coefficient, _ = (decay_matrix / compensate_matrix).min(0) elif self.kernel == 'linear': decay_matrix = (1 - decay_iou) / (1 - compensate_iou) decay_coefficient, _ = decay_matrix.min(0) else: raise NotImplementedError # update the score. cate_scores_update = cate_scores * decay_coefficient return cate_scores_update def getTrackInfo(self, tra_candidates, tra_feature, idxs, valid_ind=None): can_num = len(tra_candidates) inst_idx = [-1 for _ in range(len(idxs))] if can_num == 0: return inst_idx, tra_candidates [k1] = valid_ind.size() tra_candidate_check = [] for c in range(can_num-1, -1, -1): tra_check = [] tra_candidate = tra_candidates[c] [k0] = tra_candidate['valid_idx'].size() pred_tra = torch.sigmoid(self.tracking_module(tra_candidate['tra_feature'], tra_feature)) pred_tra = pred_tra[0,0] valid_tra = pred_tra[tra_candidate['valid_idx'],:] valid_tra = valid_tra[:, valid_ind] for i in range(k1): if inst_idx[i] == -1: tra_sort_ind = torch.argsort(valid_tra[:, i], descending=True) for ind in tra_sort_ind: if valid_tra[int(ind), i] >= self.tracking_thr and int(ind) not in tra_check: inst_idx[i] = tra_candidate['idx_mapping'][int(ind)] tra_check.append(int(ind)) break valid_masks_idx = [x for x in range(k0) if x not in tra_check] tra_candidate['valid_idx'] = tra_candidate['valid_idx'][valid_masks_idx] tra_candidate['idx_mapping'] = [k for idx, k in enumerate(tra_candidate['idx_mapping']) if idx not in tra_check] if len(tra_candidate['idx_mapping']) == 0: tra_candidate_check.append(c) if -1 not in inst_idx: break tra_candidates = [k for idx, k in enumerate(tra_candidates) if idx not in tra_candidate_check] return inst_idx, tra_candidates def getMaskMap(self, mask, kernel): # mask: dim, H/4, W/4 # kernel: valid_idxs, dim # out_device = mask.device if not mask.is_cuda: mask = mask.to('cuda') kernel = kernel.to('cuda') num_kernel, _ = kernel.size() dim, H, W = mask.size() mask = mask.unsqueeze(0) # 1, dim, H/4, W/4 mask_map = F.conv2d(mask, kernel.view(num_kernel, dim, 1, 1)) mask_map = F.interpolate(mask_map, scale_factor=4, mode='bilinear', align_corners=False).squeeze(0) mask_map = torch.sigmoid(mask_map) return mask_map
<filename>projects/VISOLO/visolo/visolo.py<gh_stars>0 import math import numpy as np import torch import torch.nn.functional as F from torch import nn import copy import cv2 from scipy.ndimage.morphology import binary_dilation from PIL import Image, ImageDraw, ImageFont import os from detectron2.modeling import META_ARCH_REGISTRY, build_backbone from detectron2.structures import Boxes, ImageList, Instances from .models.visolo_model import VISOLO, SetCriterion, DataUtils __all__ = ["Visolo"] @META_ARCH_REGISTRY.register() class Visolo(nn.Module): def __init__(self, cfg): super().__init__() self.num_frames = cfg.INPUT.SAMPLING_FRAME_NUM self.data_eps = cfg.INPUT.SAMPLING_EPS self.device = torch.device(cfg.MODEL.DEVICE) self.num_class = cfg.MODEL.VISOLO.NUM_CLASSES self.mask_weight = cfg.MODEL.VISOLO.MASK_WEIGHT self.FL_alpha = cfg.MODEL.VISOLO.FOCAL_LOSS_ALPHA self.FL_gamma = cfg.MODEL.VISOLO.FOCAL_LOSS_GAMMA self.DL_eps = cfg.MODEL.VISOLO.DICE_LOSS_EPS self.S = cfg.MODEL.VISOLO.GRID_NUM self.indim = cfg.MODEL.VISOLO.INDIM self.outdim = cfg.MODEL.VISOLO.OUTDIM self.norm = cfg.MODEL.VISOLO.NORM self.tracking_thr = cfg.MODEL.VISOLO.TRACKING_THR self.score_thr = cfg.MODEL.VISOLO.SCORE_THR self.mask_thr = cfg.MODEL.VISOLO.MASK_THR self.update_thr = cfg.MODEL.VISOLO.UPDATE_THR self.kernel = cfg.MODEL.VISOLO.KERNEL self.sigma = cfg.MODEL.VISOLO.SIGMA self.nms_pre = cfg.MODEL.VISOLO.NMS_PRE backbone = build_backbone(cfg) backbone_features = cfg.MODEL.RESNETS.OUT_FEATURES self.model = VISOLO(backbone, backbone_features, self.S, self.num_class, self.indim, self.outdim, self.norm) self.criterion = SetCriterion(self.FL_alpha, self.FL_gamma, self.DL_eps, self.mask_weight) self.data_utils = DataUtils(self.device, self.num_class, self.S, self.data_eps) self.tracking_module = self.model.Tracking_branch pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(3, 1, 1) pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(3, 1, 1) self.normalizer = lambda x: (x - pixel_mean) / pixel_std self.to(self.device) def preprocess_image(self, batched_inputs, is_eval=False): B = len(batched_inputs) N = len(batched_inputs[0]['image']) dim, H, W = batched_inputs[0]['image'][0].size() frames = torch.zeros((B, dim, N, H, W), dtype=torch.float32, device=self.device) for b in range(B): for n in range(N): frames[b,:,n,:,:] = self.normalizer(batched_inputs[b]['image'][n].to(self.device)) if is_eval: return frames, batched_inputs[0]['height'], batched_inputs[0]['width'], batched_inputs[0]['video_id'] else: return frames def getCandidateDict(self, f_idx, valid_idx, tra_feature, idx_to_inst): candidate = {} candidate['f_idx'] = f_idx candidate['valid_idx'] = valid_idx candidate['tra_feature'] = tra_feature candidate['idx_mapping'] = idx_to_inst return candidate def forward(self, batched_inputs): if self.training: frames = self.preprocess_image(batched_inputs) pred_masks, pred_kernels, pred_cats, pred_tracking = self.model(frames) GT_masks, GT_classes, GT_tracking = self.data_utils.getGridGT(batched_inputs) loss_dict = self.criterion(pred_cats, pred_masks, pred_kernels, pred_tracking, GT_classes, GT_masks, GT_tracking) return loss_dict else: frames, v_h, v_w, v_id = self.preprocess_image(batched_inputs, is_eval=True) N = frames.size()[2] tra_candidates = [] pred_masks_0, pred_kernel_0, pred_cats_0, frame_f, cat_f, kernel_f = self.model(frames[:, :, 0, :, :], None, None, None) m_frame_f = frame_f.unsqueeze(2) m_cat_f = cat_f.unsqueeze(2) m_kernel_f = kernel_f.unsqueeze(2) pred_masks_1, pred_kernel_1, pred_cats_1, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, 1, :, :], frame_f, cat_f, kernel_f) grid_weight = None inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ _, _, tra_candidates, f0_valid_ind \ = self.getTestResultV4(pred_masks_0[0], pred_kernel_0[0], pred_cats_0[0], pred_tracking[0], None, m_frame_f[:, :, -1, :, :], N, 0, [], [], [], [], None, None, [], tra_candidates) m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) pred_masks_2, pred_kernel_2, pred_cats_2, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, 2, :, :], m_frame_f, m_cat_f, m_kernel_f) grid_weight = self.model(m_frame_f[:, :, -2, :, :], m_frame_f[:, :, -1, :, :], None) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], pred_tracking[0], grid_weight, m_frame_f[:, :, -1, :, :], N, 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) if pre_inst_tra_check is not None and (pre_inst_tra_check == 0).sum() > 0: pre_valid_ind = f0_valid_ind[pre_inst_tra_check == 0] tra_candidates.append(self.getCandidateDict(0, pre_valid_ind, m_frame_f[:, :, -2, :, :], pre_ind_map_inst)) m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) pred_masks_1 = pred_masks_2.clone() pred_kernel_1 = pred_kernel_2.clone() pred_cats_1 = pred_cats_2.clone() if f1_valid_ind is not None: f0_valid_ind = f1_valid_ind.clone() else: f0_valid_ind = f1_valid_ind for n in range(3, N + 1): if n == N: grid_weight = self.model(m_frame_f[:,:,-2,:,:], m_frame_f[:,:,-1,:,:], m_frame_f[:,:,-3,:,:]) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], None, grid_weight, m_frame_f[:,:,-1,:,:], N, n - 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) continue pred_masks_2, pred_kernel_2, pred_cats_2, pred_tracking, frame_f, cat_f, kernel_f = self.model(frames[:, :, n, :, :], m_frame_f, m_cat_f, m_kernel_f) # B,S**2,1,H,W / B,C,1,S,S / B,1,S**2,S**2 grid_weight = self.model(m_frame_f[:,:,-2,:,:], m_frame_f[:,:,-1,:,:], m_frame_f[:,:,-3,:,:]) inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, \ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f1_valid_ind \ = self.getTestResultV4(pred_masks_1[0], pred_kernel_1[0], pred_cats_1[0], pred_tracking[0], grid_weight, m_frame_f[:,:,-1,:,:], N, n - 1, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result, valid_tra, valid_ind_map_to_inst, tra_candidates) if pre_inst_tra_check is not None and (pre_inst_tra_check == 0).sum() > 0: pre_valid_ind = f0_valid_ind[pre_inst_tra_check == 0] tra_candidates.append(self.getCandidateDict(n - 2, pre_valid_ind, m_frame_f[:,:,-2,:,:], pre_ind_map_inst)) if n % 5 == 2: m_frame_f = torch.cat((m_frame_f, frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f, cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f, kernel_f.unsqueeze(2)), dim=2) else: m_frame_f = torch.cat((m_frame_f[:, :, :-2], m_frame_f[:, :, -1:], frame_f.unsqueeze(2)), dim=2) m_cat_f = torch.cat((m_cat_f[:, :, :-2], m_cat_f[:, :, -1:], cat_f.unsqueeze(2)), dim=2) m_kernel_f = torch.cat((m_kernel_f[:, :, :-2], m_kernel_f[:, :, -1:], kernel_f.unsqueeze(2)), dim=2) pred_masks_1 = pred_masks_2.clone() pred_kernel_1 = pred_kernel_2.clone() pred_cats_1 = pred_cats_2.clone() if f1_valid_ind is not None: f0_valid_ind = f1_valid_ind.clone() else: f0_valid_ind = f1_valid_ind if isinstance(inst_masks, list): return None inst_masks = F.interpolate(inst_masks, (v_h, v_w), mode='bilinear', align_corners=False) inst_masks = (inst_masks >= self.mask_thr).float() new_inst_cat_scores, new_inst_cats = self.getAverageCat(inst_cat_scores_ori) video_output = { "pred_scores": new_inst_cat_scores, "pred_labels": new_inst_cats, "pred_masks": inst_masks, } return video_output def getAverageCat(self, cat_scores_ori): # cat_scores_ori: K, v_l, 40 K, L, _ = cat_scores_ori.size() valid_frame_num = torch.count_nonzero(torch.sum(cat_scores_ori, dim=2), dim=1).view(K, 1) avg_scores = torch.div(torch.sum(cat_scores_ori, dim=1), valid_frame_num.expand(K, self.num_class)) cat_scores, cats = torch.max(avg_scores, dim=1) return cat_scores, cats def getTestResultV4(self, N_pred_masks, N_pred_kernels, N_pred_cats, N_pred_tra, grid_weight, tra_feature, N, f_idx, inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori, f0_result=None, valid_tra=None, valid_ind_map_to_inst=None, tra_candidates=None): # N_pred_masks : dim, 1, H/4, W/4 # N_pred_kernels : dim, 1, S1, S2 # N_pred_cats : C, 1, S1, S2 # N_pred_tra : 1, S1*S2, S1*S2 inst_masks = inst_masks # K, N, H, W inst_cats = inst_cats # K, N inst_cat_scores = inst_cat_scores # K, N inst_cat_scores_ori = inst_cat_scores_ori # K, N, 40 f0_result = f0_result valid_tra = valid_tra valid_ind_map_to_inst = valid_ind_map_to_inst N = N f_idx = f_idx pre_inst_tra_check = None pre_ind_map_inst = None f0_valid_ind = None if grid_weight is not None: grid_weight = grid_weight[0,0] if f0_result is None: f0_result = self.getSegMaskV5(N_pred_masks[:,0,:,:], N_pred_kernels[:,0,:,:], N_pred_cats[:,0,:,:], grid_weight) if f0_result is not None: f0_seg_masks, f0_cat_labels, f0_cat_scores, f0_cat_scores_ori, f0_valid_ind = f0_result k0, _, _ = f0_seg_masks.size() if f_idx != N - 1: valid_tra = N_pred_tra[0, f0_valid_ind, :] # k0, S**2 inst_num = len(inst_masks) no_match_ind = [x for x in range(k0)] inst_idx, tra_candidates = self.getTrackInfo(tra_candidates, tra_feature, no_match_ind, valid_ind=f0_valid_ind) map_num = 0 for i in range(k0): if inst_idx[i] != -1: if inst_masks[inst_idx[i]][f_idx].sum() != 0: print('Error and mask in inst track!!!') exit() else: inst_masks[inst_idx[i]][f_idx] = f0_seg_masks[i, :, :] inst_cats[inst_idx[i]][f_idx] = f0_cat_labels[i] inst_cat_scores[inst_idx[i]][f_idx] = f0_cat_scores[i] inst_cat_scores_ori[inst_idx[i]][f_idx] = f0_cat_scores_ori[i] valid_ind_map_to_inst.append(inst_idx[i]) else: _, H, W = f0_seg_masks.size() masks = torch.zeros((1, N, H, W), device=self.device) cats = torch.full((1, N), -1, device=self.device) cat_scores = torch.zeros((1, N), device=self.device) cat_scores_ori = torch.zeros((1, N, self.num_class), device=self.device) masks[0, f_idx] = f0_seg_masks[i, :, :] cats[0, f_idx] = f0_cat_labels[i] cat_scores[0, f_idx] = f0_cat_scores[i] cat_scores_ori[0, f_idx] = f0_cat_scores_ori[i] if isinstance(inst_masks, list): inst_masks = masks inst_cats = cats inst_cat_scores = cat_scores inst_cat_scores_ori = cat_scores_ori else: inst_masks = torch.cat((inst_masks, masks), dim=0) inst_cats = torch.cat((inst_cats, cats), dim=0) inst_cat_scores = torch.cat((inst_cat_scores, cat_scores), dim=0) inst_cat_scores_ori = torch.cat((inst_cat_scores_ori, cat_scores_ori), dim=0) valid_ind_map_to_inst.append(inst_num + map_num) map_num+=1 else: f0_result = self.getSegMaskV5(N_pred_masks[:,0,:,:], N_pred_kernels[:,0,:,:], N_pred_cats[:,0,:,:], grid_weight) if f0_result is not None: f0_seg_masks, f0_cat_labels, f0_cat_scores, f0_cat_scores_ori, f0_valid_ind = f0_result k1, _, _ = f0_seg_masks.size() no_match_ind = [] temp_map_ind = [0 for _ in range(k1)] pre_inst_tra_check = torch.zeros((valid_tra.size()[0])) inst_num = len(inst_masks) valid_tra = valid_tra[:, f0_valid_ind] # k0, k1 for i in range(k1): tra_sort_ind = torch.argsort(valid_tra[:, i], descending=True) check_match = 0 for ind in tra_sort_ind: inst_map_ind = valid_ind_map_to_inst[int(ind)] if inst_masks[inst_map_ind][f_idx].sum() == 0 and valid_tra[int(ind), i] >= self.tracking_thr: inst_masks[inst_map_ind][f_idx] = f0_seg_masks[i, :, :] inst_cats[inst_map_ind][f_idx] = f0_cat_labels[i] inst_cat_scores[inst_map_ind][f_idx] = f0_cat_scores[i] inst_cat_scores_ori[inst_map_ind][f_idx] = f0_cat_scores_ori[i] check_match = 1 temp_map_ind[i] = inst_map_ind pre_inst_tra_check[int(ind)] = 1 break if check_match == 0: no_match_ind.append(i) valid_ind = f0_valid_ind[no_match_ind] inst_idx, tra_candidates = self.getTrackInfo(tra_candidates, tra_feature, no_match_ind, valid_ind=valid_ind) map_num = 0 for i in range(len(no_match_ind)): ind = no_match_ind[i] if inst_idx[i] != -1: if inst_masks[inst_idx[i]][f_idx].sum() != 0: print('Error add mask in inst track!!!') exit() else: inst_masks[inst_idx[i]][f_idx] = f0_seg_masks[ind, :, :] inst_cats[inst_idx[i]][f_idx] = f0_cat_labels[ind] inst_cat_scores[inst_idx[i]][f_idx] = f0_cat_scores[ind] inst_cat_scores_ori[inst_idx[i]][f_idx] = f0_cat_scores_ori[ind] temp_map_ind[ind] = inst_idx[i] else: _, H, W = f0_seg_masks.size() masks = torch.zeros((1, N, H, W), device=self.device) cats = torch.full((1, N), -1, device=self.device) cat_scores = torch.zeros((1, N), device=self.device) cat_scores_ori = torch.zeros((1, N, self.num_class), device=self.device) masks[0, f_idx] = f0_seg_masks[ind, :, :] cats[0, f_idx] = f0_cat_labels[ind] cat_scores[0, f_idx] = f0_cat_scores[ind] cat_scores_ori[0, f_idx] = f0_cat_scores_ori[ind] inst_masks = torch.cat((inst_masks, masks), dim=0) inst_cats = torch.cat((inst_cats, cats), dim=0) inst_cat_scores = torch.cat((inst_cat_scores, cat_scores), dim=0) inst_cat_scores_ori = torch.cat((inst_cat_scores_ori, cat_scores_ori), dim=0) temp_map_ind[ind] = inst_num + map_num map_num += 1 pre_ind_map_inst = [k for idx, k in enumerate(valid_ind_map_to_inst) if pre_inst_tra_check[idx] == 0] valid_ind_map_to_inst = temp_map_ind if f_idx != N - 1: valid_tra = N_pred_tra[0, f0_valid_ind, :] # k1, S**2 else: pre_inst_tra_check = torch.zeros((valid_tra.size()[0])) pre_ind_map_inst = copy.deepcopy(valid_ind_map_to_inst) valid_tra = None valid_ind_map_to_inst = [] return inst_masks, inst_cats, inst_cat_scores, inst_cat_scores_ori,\ f0_result, valid_tra, valid_ind_map_to_inst,\ pre_inst_tra_check, pre_ind_map_inst, tra_candidates, f0_valid_ind def getSegMaskV5(self, pred_masks, pred_kernels, pred_cats, grid_weight): # pred_masks : dim, H/4, W/4 # pred_kernels : dim, S1, S2 # pred_cats : C, S1, S2 # grid_weight : S1*S2 _, H, W = pred_masks.size() C, S1, S2 = pred_cats.size() cat_scores = pred_cats.reshape(-1, S1 * S2).transpose(1, 0) # S**2, C cat_scores_ori = cat_scores.clone() cat_scores, cat_labels = cat_scores.max(1) # S**2 if grid_weight is not None: cat_scores *= grid_weight cat_scores[cat_scores < self.score_thr] = 0. valid_ind = cat_scores.nonzero()[:, 0] if valid_ind.sum() == 0: return None kernels = pred_kernels.reshape(-1, S1*S2).transpose(1, 0) # S1*S2, dim kernels = kernels[valid_ind] seg_preds = self.getMaskMap(pred_masks, kernels) seg_masks = (seg_preds > self.mask_thr).float() cat_scores = cat_scores[valid_ind] cat_labels = cat_labels[valid_ind] sum_masks = seg_masks.sum((1, 2)).float() seg_scores = (seg_preds * seg_masks.float()).sum((1, 2)) / sum_masks cat_scores *= seg_scores sort_ind = torch.argsort(cat_scores, descending=True) if sort_ind.size()[0] > self.nms_pre: sort_ind = sort_ind[:self.nms_pre] seg_masks = seg_masks[sort_ind, :, :] cat_scores = cat_scores[sort_ind] cat_labels = cat_labels[sort_ind] valid_ind = valid_ind[sort_ind] cat_scores = self.matrix_nms(seg_masks, cat_labels, cat_scores) keep = cat_scores >= self.update_thr if keep.sum() == 0: return None seg_masks = seg_masks[keep, :, :] cat_scores = cat_scores[keep] cat_labels = cat_labels[keep] valid_ind = valid_ind[keep] sort_ind = torch.argsort(cat_scores, descending=True) if sort_ind.size()[0] > 100: sort_ind = sort_ind[:100] seg_masks = seg_masks[sort_ind, :, :] cat_scores = cat_scores[sort_ind] cat_labels = cat_labels[sort_ind] valid_ind = valid_ind[sort_ind] cat_scores_ori = cat_scores_ori[valid_ind, :] for i in range(len(valid_ind) - 1): if seg_masks[i].sum() == 0: continue for j in range(i + 1, len(valid_ind)): inter_region = (seg_masks[i] * seg_masks[j]).sum() mask_region = seg_masks[j].sum() if inter_region / mask_region > 0.5: seg_masks[j] = 0 final_valid_ind = (seg_masks.sum((1, 2)) > 0) seg_masks = seg_masks[final_valid_ind, :, :] cat_scores = cat_scores[final_valid_ind] cat_labels = cat_labels[final_valid_ind] cat_scores_ori = cat_scores_ori[final_valid_ind, :] valid_ind = valid_ind[final_valid_ind] return seg_masks, cat_labels, cat_scores, cat_scores_ori, valid_ind def matrix_nms(self, seg_masks, cate_labels, cate_scores, sum_masks=None): """Matrix NMS for multi-class masks. Args: seg_masks (Tensor): shape (n, h, w) cate_labels (Tensor): shape (n), mask labels in descending order cate_scores (Tensor): shape (n), mask scores in descending order self.kernel (str): 'linear' or 'gauss' self.sigma (float): std in gaussian method sum_masks (Tensor): The sum of seg_masks Returns: Tensor: cate_scores_update, tensors of shape (n) """ n_samples = len(cate_labels) if n_samples == 0: return [] if sum_masks is None: sum_masks = seg_masks.sum((1, 2)).float() seg_masks = seg_masks.reshape(n_samples, -1).float() # inter. inter_matrix = torch.mm(seg_masks, seg_masks.transpose(1, 0)) # union. sum_masks_x = sum_masks.expand(n_samples, n_samples) # iou. iou_matrix = (inter_matrix / (sum_masks_x + sum_masks_x.transpose(1, 0) - inter_matrix)).triu(diagonal=1) # label_specific matrix. cate_labels_x = cate_labels.expand(n_samples, n_samples) label_matrix = (cate_labels_x == cate_labels_x.transpose(1, 0)) label_matrix = label_matrix.float().triu(diagonal=1) # IoU compensation compensate_iou, _ = (iou_matrix * label_matrix).max(0) compensate_iou = compensate_iou.expand(n_samples, n_samples).transpose(1, 0) # IoU decay decay_iou = iou_matrix * label_matrix # matrix nms if self.kernel == 'gaussian': decay_matrix = torch.exp(-1 * self.sigma * (decay_iou ** 2)) compensate_matrix = torch.exp(-1 * self.sigma * (compensate_iou ** 2)) decay_coefficient, _ = (decay_matrix / compensate_matrix).min(0) elif self.kernel == 'linear': decay_matrix = (1 - decay_iou) / (1 - compensate_iou) decay_coefficient, _ = decay_matrix.min(0) else: raise NotImplementedError # update the score. cate_scores_update = cate_scores * decay_coefficient return cate_scores_update def getTrackInfo(self, tra_candidates, tra_feature, idxs, valid_ind=None): can_num = len(tra_candidates) inst_idx = [-1 for _ in range(len(idxs))] if can_num == 0: return inst_idx, tra_candidates [k1] = valid_ind.size() tra_candidate_check = [] for c in range(can_num-1, -1, -1): tra_check = [] tra_candidate = tra_candidates[c] [k0] = tra_candidate['valid_idx'].size() pred_tra = torch.sigmoid(self.tracking_module(tra_candidate['tra_feature'], tra_feature)) pred_tra = pred_tra[0,0] valid_tra = pred_tra[tra_candidate['valid_idx'],:] valid_tra = valid_tra[:, valid_ind] for i in range(k1): if inst_idx[i] == -1: tra_sort_ind = torch.argsort(valid_tra[:, i], descending=True) for ind in tra_sort_ind: if valid_tra[int(ind), i] >= self.tracking_thr and int(ind) not in tra_check: inst_idx[i] = tra_candidate['idx_mapping'][int(ind)] tra_check.append(int(ind)) break valid_masks_idx = [x for x in range(k0) if x not in tra_check] tra_candidate['valid_idx'] = tra_candidate['valid_idx'][valid_masks_idx] tra_candidate['idx_mapping'] = [k for idx, k in enumerate(tra_candidate['idx_mapping']) if idx not in tra_check] if len(tra_candidate['idx_mapping']) == 0: tra_candidate_check.append(c) if -1 not in inst_idx: break tra_candidates = [k for idx, k in enumerate(tra_candidates) if idx not in tra_candidate_check] return inst_idx, tra_candidates def getMaskMap(self, mask, kernel): # mask: dim, H/4, W/4 # kernel: valid_idxs, dim # out_device = mask.device if not mask.is_cuda: mask = mask.to('cuda') kernel = kernel.to('cuda') num_kernel, _ = kernel.size() dim, H, W = mask.size() mask = mask.unsqueeze(0) # 1, dim, H/4, W/4 mask_map = F.conv2d(mask, kernel.view(num_kernel, dim, 1, 1)) mask_map = F.interpolate(mask_map, scale_factor=4, mode='bilinear', align_corners=False).squeeze(0) mask_map = torch.sigmoid(mask_map) return mask_map
en
0.427679
# B,S**2,1,H,W / B,C,1,S,S / B,1,S**2,S**2 # cat_scores_ori: K, v_l, 40 # N_pred_masks : dim, 1, H/4, W/4 # N_pred_kernels : dim, 1, S1, S2 # N_pred_cats : C, 1, S1, S2 # N_pred_tra : 1, S1*S2, S1*S2 # K, N, H, W # K, N # K, N # K, N, 40 # k0, S**2 # k0, k1 # k1, S**2 # pred_masks : dim, H/4, W/4 # pred_kernels : dim, S1, S2 # pred_cats : C, S1, S2 # grid_weight : S1*S2 # S**2, C # S**2 # S1*S2, dim Matrix NMS for multi-class masks. Args: seg_masks (Tensor): shape (n, h, w) cate_labels (Tensor): shape (n), mask labels in descending order cate_scores (Tensor): shape (n), mask scores in descending order self.kernel (str): 'linear' or 'gauss' self.sigma (float): std in gaussian method sum_masks (Tensor): The sum of seg_masks Returns: Tensor: cate_scores_update, tensors of shape (n) # inter. # union. # iou. # label_specific matrix. # IoU compensation # IoU decay # matrix nms # update the score. # mask: dim, H/4, W/4 # kernel: valid_idxs, dim # out_device = mask.device # 1, dim, H/4, W/4
1.903676
2
zlogging/enum/Tunnel.py
JarryShaw/zlogging
0
6630499
<gh_stars>0 # -*- coding: utf-8 -*- # pylint: disable=line-too-long,import-error """Namespace: ``Tunnel``.""" from zlogging._compat import enum @enum.unique class Type(enum.IntFlag): """Enum: ``Tunnel::Type``. See Also: `base/bif/types.bif.zeek <https://docs.zeek.org/en/stable/scripts/base/bif/types.bif.zeek.html#type-Tunnel::Type>`__ """ _ignore_ = 'Type _' Type = vars() Type['NONE'] = enum.auto() Type['IP'] = enum.auto() Type['AYIYA'] = enum.auto() Type['TEREDO'] = enum.auto() Type['SOCKS'] = enum.auto() Type['GTPv1'] = enum.auto() Type['HTTP'] = enum.auto() Type['GRE'] = enum.auto() Type['VXLAN'] = enum.auto() @enum.unique class Action(enum.IntFlag): """Enum: ``Tunnel::Action``. Types of interesting activity that can occur with a tunnel. See Also: `base/frameworks/tunnels/main.zeek <https://docs.zeek.org/en/stable/scripts/base/frameworks/tunnels/main.zeek.html#type-Tunnel::Action>`__ """ _ignore_ = 'Action _' Action = vars() #: A new tunnel (encapsulating “connection”) has been seen. Action['DISCOVER'] = enum.auto() #: A tunnel connection has closed. Action['CLOSE'] = enum.auto() #: No new connections over a tunnel happened in the amount of #: time indicated by Tunnel::expiration\_interval. Action['EXPIRE'] = enum.auto()
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,import-error """Namespace: ``Tunnel``.""" from zlogging._compat import enum @enum.unique class Type(enum.IntFlag): """Enum: ``Tunnel::Type``. See Also: `base/bif/types.bif.zeek <https://docs.zeek.org/en/stable/scripts/base/bif/types.bif.zeek.html#type-Tunnel::Type>`__ """ _ignore_ = 'Type _' Type = vars() Type['NONE'] = enum.auto() Type['IP'] = enum.auto() Type['AYIYA'] = enum.auto() Type['TEREDO'] = enum.auto() Type['SOCKS'] = enum.auto() Type['GTPv1'] = enum.auto() Type['HTTP'] = enum.auto() Type['GRE'] = enum.auto() Type['VXLAN'] = enum.auto() @enum.unique class Action(enum.IntFlag): """Enum: ``Tunnel::Action``. Types of interesting activity that can occur with a tunnel. See Also: `base/frameworks/tunnels/main.zeek <https://docs.zeek.org/en/stable/scripts/base/frameworks/tunnels/main.zeek.html#type-Tunnel::Action>`__ """ _ignore_ = 'Action _' Action = vars() #: A new tunnel (encapsulating “connection”) has been seen. Action['DISCOVER'] = enum.auto() #: A tunnel connection has closed. Action['CLOSE'] = enum.auto() #: No new connections over a tunnel happened in the amount of #: time indicated by Tunnel::expiration\_interval. Action['EXPIRE'] = enum.auto()
en
0.72016
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,import-error Namespace: ``Tunnel``. Enum: ``Tunnel::Type``. See Also: `base/bif/types.bif.zeek <https://docs.zeek.org/en/stable/scripts/base/bif/types.bif.zeek.html#type-Tunnel::Type>`__ Enum: ``Tunnel::Action``. Types of interesting activity that can occur with a tunnel. See Also: `base/frameworks/tunnels/main.zeek <https://docs.zeek.org/en/stable/scripts/base/frameworks/tunnels/main.zeek.html#type-Tunnel::Action>`__ #: A new tunnel (encapsulating “connection”) has been seen. #: A tunnel connection has closed. #: No new connections over a tunnel happened in the amount of #: time indicated by Tunnel::expiration\_interval.
2.003443
2
examples/hello.py
concurrence/concurrence
27
6630500
<filename>examples/hello.py from concurrence import dispatch def hello(): print "Hello World!" if __name__ == '__main__': dispatch(hello)
<filename>examples/hello.py from concurrence import dispatch def hello(): print "Hello World!" if __name__ == '__main__': dispatch(hello)
none
1
1.556847
2
testing/example_scripts/dataclasses/test_compare_dataclasses.py
tinkerlin/pytest
5,079
6630501
<reponame>tinkerlin/pytest # -*- coding: utf-8 -*- from dataclasses import dataclass from dataclasses import field def test_dataclasses(): @dataclass class SimpleDataObject(object): field_a: int = field() field_b: int = field() left = SimpleDataObject(1, "b") right = SimpleDataObject(1, "c") assert left == right
# -*- coding: utf-8 -*- from dataclasses import dataclass from dataclasses import field def test_dataclasses(): @dataclass class SimpleDataObject(object): field_a: int = field() field_b: int = field() left = SimpleDataObject(1, "b") right = SimpleDataObject(1, "c") assert left == right
en
0.769321
# -*- coding: utf-8 -*-
3.067268
3
src/run_scripts/repro/dvc.py
prhuppertz/Burned_Area_Detection
5
6630502
<filename>src/run_scripts/repro/dvc.py """Usage: dvc.py [--cache=<cache_path>] [--link=None] [--link2=None] @ <NAME> & <NAME> 2020, Cervest Creates symlinks/DVC structure Options: -h --help Show help. --version Show version. --cache=<cache_path> Inference mode. 'roi' or 'wsi'. [default: data/] --link=<link> Source path for symlink to points towards, if using remote storage """ import os import subprocess from docopt import docopt def set_cache(cache_dir): """ Sets dvc cache given config file :param cache_dir: path to cache directory :return: """ p = subprocess.Popen("dvc cache dir {} --local".format(cache_dir), shell=True) p.communicate() def set_symlink(): p = subprocess.Popen("dvc config cache.type symlink --local", shell=True) p.communicate() p = subprocess.Popen("dvc config cache.protected true --local", shell=True) p.communicate() def main(cache_path, link_path): """ Sets up dvc for large data :return: """ set_symlink() if cache_path: os.makedirs(cache_path, exist_ok=True) set_cache(cache_path) # Get directory of current project cur_project_dir = os.getcwd() # Make a path where raw_data is stored, if data is stored externally if link_path: to_folder = os.path.join(cur_project_dir, "data/raw_data/tiles") from_folder = link_path os.makedirs(from_folder, exist_ok=True) os.makedirs(to_folder, exist_ok=True) #Create a symlink os.symlink(from_folder, to_folder) if __name__ == "__main__": arguments = docopt(__doc__) cache_path = arguments["--cache"] link_path = arguments["--link"] main(cache_path, link_path)
<filename>src/run_scripts/repro/dvc.py """Usage: dvc.py [--cache=<cache_path>] [--link=None] [--link2=None] @ <NAME> & <NAME> 2020, Cervest Creates symlinks/DVC structure Options: -h --help Show help. --version Show version. --cache=<cache_path> Inference mode. 'roi' or 'wsi'. [default: data/] --link=<link> Source path for symlink to points towards, if using remote storage """ import os import subprocess from docopt import docopt def set_cache(cache_dir): """ Sets dvc cache given config file :param cache_dir: path to cache directory :return: """ p = subprocess.Popen("dvc cache dir {} --local".format(cache_dir), shell=True) p.communicate() def set_symlink(): p = subprocess.Popen("dvc config cache.type symlink --local", shell=True) p.communicate() p = subprocess.Popen("dvc config cache.protected true --local", shell=True) p.communicate() def main(cache_path, link_path): """ Sets up dvc for large data :return: """ set_symlink() if cache_path: os.makedirs(cache_path, exist_ok=True) set_cache(cache_path) # Get directory of current project cur_project_dir = os.getcwd() # Make a path where raw_data is stored, if data is stored externally if link_path: to_folder = os.path.join(cur_project_dir, "data/raw_data/tiles") from_folder = link_path os.makedirs(from_folder, exist_ok=True) os.makedirs(to_folder, exist_ok=True) #Create a symlink os.symlink(from_folder, to_folder) if __name__ == "__main__": arguments = docopt(__doc__) cache_path = arguments["--cache"] link_path = arguments["--link"] main(cache_path, link_path)
en
0.506802
Usage: dvc.py [--cache=<cache_path>] [--link=None] [--link2=None] @ <NAME> & <NAME> 2020, Cervest Creates symlinks/DVC structure Options: -h --help Show help. --version Show version. --cache=<cache_path> Inference mode. 'roi' or 'wsi'. [default: data/] --link=<link> Source path for symlink to points towards, if using remote storage Sets dvc cache given config file :param cache_dir: path to cache directory :return: Sets up dvc for large data :return: # Get directory of current project # Make a path where raw_data is stored, if data is stored externally #Create a symlink
2.490375
2
utils/host_info.py
wanjun-group-seu/AQUARIUM
0
6630503
<gh_stars>0 # !/usr/bin/env python # -*- coding:utf-8 -*- # author : zerodel # Readme: # import argparse import os import os.path import sys upper_root = os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) sys.path.append(upper_root) import pysrc.sub_module.summary_quant as sq parser = argparse.ArgumentParser() parser.add_argument("anno", help="""path to annotation file or quantification result directory with each sample has a final.gtf in its sub-dir""", default="", nargs="+") parser.add_argument("-o", help="output file location", default="") __doc__ = ''' summarize the host gene information from ''' __author__ = 'zerodel' if __name__ == "__main__": args = parser.parse_args() if args.o and args.anno: isoform_ownership = sq.TranscriptOwnership() for entry_annotation in args.anno: if os.path.isfile(entry_annotation): isoform_ownership.parse_gtf(entry_annotation) elif os.path.isdir(entry_annotation): # print(entry_annotation) gtf_under_this_folder = [os.path.join(entry_annotation, x, "final.gtf") for x in os.listdir(entry_annotation) if os.path.isdir(os.path.join(entry_annotation, x)) and not x.startswith(".")] # for x in os.listdir(entry_annotation): # print(x) # if os.path.isdir(os.path.join(entry_annotation, x)) and not x.startswith("."): # print(os.path.join(entry_annotation, x, "final.gtf")) # print(gtf_under_this_folder) for path_gtf in gtf_under_this_folder: if os.path.exists(path_gtf) and os.path.isfile(path_gtf): isoform_ownership.parse_gtf(path_gtf) else: print("a wrong path is given : {}".format(entry_annotation)) continue with open(args.o, "w") as dump_it: for line in isoform_ownership.to_text_table_lines(): dump_it.write("{}\n".format(line.strip())) else: print("wrong arguments given , please check usage by using '-h' option") exit(-1)
# !/usr/bin/env python # -*- coding:utf-8 -*- # author : zerodel # Readme: # import argparse import os import os.path import sys upper_root = os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) sys.path.append(upper_root) import pysrc.sub_module.summary_quant as sq parser = argparse.ArgumentParser() parser.add_argument("anno", help="""path to annotation file or quantification result directory with each sample has a final.gtf in its sub-dir""", default="", nargs="+") parser.add_argument("-o", help="output file location", default="") __doc__ = ''' summarize the host gene information from ''' __author__ = 'zerodel' if __name__ == "__main__": args = parser.parse_args() if args.o and args.anno: isoform_ownership = sq.TranscriptOwnership() for entry_annotation in args.anno: if os.path.isfile(entry_annotation): isoform_ownership.parse_gtf(entry_annotation) elif os.path.isdir(entry_annotation): # print(entry_annotation) gtf_under_this_folder = [os.path.join(entry_annotation, x, "final.gtf") for x in os.listdir(entry_annotation) if os.path.isdir(os.path.join(entry_annotation, x)) and not x.startswith(".")] # for x in os.listdir(entry_annotation): # print(x) # if os.path.isdir(os.path.join(entry_annotation, x)) and not x.startswith("."): # print(os.path.join(entry_annotation, x, "final.gtf")) # print(gtf_under_this_folder) for path_gtf in gtf_under_this_folder: if os.path.exists(path_gtf) and os.path.isfile(path_gtf): isoform_ownership.parse_gtf(path_gtf) else: print("a wrong path is given : {}".format(entry_annotation)) continue with open(args.o, "w") as dump_it: for line in isoform_ownership.to_text_table_lines(): dump_it.write("{}\n".format(line.strip())) else: print("wrong arguments given , please check usage by using '-h' option") exit(-1)
en
0.549246
# !/usr/bin/env python # -*- coding:utf-8 -*- # author : zerodel # Readme: # path to annotation file or quantification result directory with each sample has a final.gtf in its sub-dir summarize the host gene information from # print(entry_annotation) # for x in os.listdir(entry_annotation): # print(x) # if os.path.isdir(os.path.join(entry_annotation, x)) and not x.startswith("."): # print(os.path.join(entry_annotation, x, "final.gtf")) # print(gtf_under_this_folder)
2.239162
2
subir/query.py
xyla-io/subir
0
6630504
from data_layer import Redshift as SQL from typing import Optional, Dict, List class ColumnTypeQuery(SQL.GeneratedQuery, SQL.ResultQuery[Dict[str, str]]): database: str schema: str table: str def __init__(self, database: str, schema: str, table: str): self.database = database self.schema = schema self.table = table super().__init__() def generate_query(self): self.query = ''' select column_name, data_type, character_maximum_length from information_schema.columns where table_catalog = %s and table_schema = %s and table_name = %s; ''' self.substitution_parameters=( self.database, self.schema, self.table, ) def cursor_to_result(self, cursor: any) -> Optional[Dict[str, str]]: result = cursor.fetchall() return { r[0]: f'{r[1]}({r[2]})' if r[1] == 'character varying' else r[1] for r in result } class CreateTableQuery(SQL.GeneratedQuery): schema: str table: str column_types: Dict[str, str] read_only_groups: List[str] def __init__(self, schema: str, table: str, column_types: Dict[str, str], read_only_groups: List[str]=[]): self.schema = schema self.table = table self.column_types = column_types self.read_only_groups = read_only_groups super().__init__() def generate_query(self): columns_definition = ',\n'.join(f' "{c}" {t}' for c, t in self.column_types.items()) self.query = f''' create table {self.schema}.{self.table} ( {columns_definition} ); ''' for group in self.read_only_groups: self.query += f'\ngrant select on table {self.schema}.{self.table} to group {group};' class DropTableQuery(SQL.GeneratedQuery): schema: str table: str def __init__(self, schema: str, table: str): self.schema = schema self.table = table super().__init__() def generate_query(self): self.query = f'drop table {self.schema}.{self.table}' class UploadQuery(SQL.GeneratedQuery): schema: str table: str def __init__(self, schema: str, table: str): self.schema = schema self.table = table super().__init__() @property def upload_table(self) -> str: return f'flx_upload_{self.table}' class PrepareUploadTableQuery(UploadQuery): schema: str table: str def generate_query(self): self.query = f''' create temporary table {self.upload_table} (like {self.schema}.{self.table} including defaults); ''' class AppendUploadQuery(UploadQuery): def generate_query(self): self.query = f'insert into {self.schema}.{self.table} select * from {self.upload_table};' class ReplaceUploadQuery(UploadQuery): def generate_query(self): append_query = AppendUploadQuery(schema=self.schema, table=self.table) self.query = f''' truncate table {self.schema}.{self.table}; {append_query.query} ''' self.substitution_parameters = append_query.substitution_parameters class MergeUploadQuery(SQL.MergeQuery): schema: str table: str def __init__(self, join_columns: List[str], update_columns: List[str], schema: str, table: str): self.schema = schema self.table = table super().__init__( join_columns=join_columns, update_columns=update_columns, source_table=self.upload_table, target_table=table, source_schema=None, target_schema=schema ) @property def upload_table(self) -> str: return f'flx_upload_{self.table}' class MergeReplaceUploadQuery(SQL.MergeReplaceQuery): schema: str table: str def __init__(self, join_columns: List[str], schema: str, table: str): self.schema = schema self.table = table super().__init__( join_columns=join_columns, source_table=self.upload_table, target_table=table, source_schema=None, target_schema=schema ) @property def upload_table(self) -> str: return f'flx_upload_{self.table}'
from data_layer import Redshift as SQL from typing import Optional, Dict, List class ColumnTypeQuery(SQL.GeneratedQuery, SQL.ResultQuery[Dict[str, str]]): database: str schema: str table: str def __init__(self, database: str, schema: str, table: str): self.database = database self.schema = schema self.table = table super().__init__() def generate_query(self): self.query = ''' select column_name, data_type, character_maximum_length from information_schema.columns where table_catalog = %s and table_schema = %s and table_name = %s; ''' self.substitution_parameters=( self.database, self.schema, self.table, ) def cursor_to_result(self, cursor: any) -> Optional[Dict[str, str]]: result = cursor.fetchall() return { r[0]: f'{r[1]}({r[2]})' if r[1] == 'character varying' else r[1] for r in result } class CreateTableQuery(SQL.GeneratedQuery): schema: str table: str column_types: Dict[str, str] read_only_groups: List[str] def __init__(self, schema: str, table: str, column_types: Dict[str, str], read_only_groups: List[str]=[]): self.schema = schema self.table = table self.column_types = column_types self.read_only_groups = read_only_groups super().__init__() def generate_query(self): columns_definition = ',\n'.join(f' "{c}" {t}' for c, t in self.column_types.items()) self.query = f''' create table {self.schema}.{self.table} ( {columns_definition} ); ''' for group in self.read_only_groups: self.query += f'\ngrant select on table {self.schema}.{self.table} to group {group};' class DropTableQuery(SQL.GeneratedQuery): schema: str table: str def __init__(self, schema: str, table: str): self.schema = schema self.table = table super().__init__() def generate_query(self): self.query = f'drop table {self.schema}.{self.table}' class UploadQuery(SQL.GeneratedQuery): schema: str table: str def __init__(self, schema: str, table: str): self.schema = schema self.table = table super().__init__() @property def upload_table(self) -> str: return f'flx_upload_{self.table}' class PrepareUploadTableQuery(UploadQuery): schema: str table: str def generate_query(self): self.query = f''' create temporary table {self.upload_table} (like {self.schema}.{self.table} including defaults); ''' class AppendUploadQuery(UploadQuery): def generate_query(self): self.query = f'insert into {self.schema}.{self.table} select * from {self.upload_table};' class ReplaceUploadQuery(UploadQuery): def generate_query(self): append_query = AppendUploadQuery(schema=self.schema, table=self.table) self.query = f''' truncate table {self.schema}.{self.table}; {append_query.query} ''' self.substitution_parameters = append_query.substitution_parameters class MergeUploadQuery(SQL.MergeQuery): schema: str table: str def __init__(self, join_columns: List[str], update_columns: List[str], schema: str, table: str): self.schema = schema self.table = table super().__init__( join_columns=join_columns, update_columns=update_columns, source_table=self.upload_table, target_table=table, source_schema=None, target_schema=schema ) @property def upload_table(self) -> str: return f'flx_upload_{self.table}' class MergeReplaceUploadQuery(SQL.MergeReplaceQuery): schema: str table: str def __init__(self, join_columns: List[str], schema: str, table: str): self.schema = schema self.table = table super().__init__( join_columns=join_columns, source_table=self.upload_table, target_table=table, source_schema=None, target_schema=schema ) @property def upload_table(self) -> str: return f'flx_upload_{self.table}'
en
0.290867
select column_name, data_type, character_maximum_length from information_schema.columns where table_catalog = %s and table_schema = %s and table_name = %s; create table {self.schema}.{self.table} ( {columns_definition} ); create temporary table {self.upload_table} (like {self.schema}.{self.table} including defaults); truncate table {self.schema}.{self.table}; {append_query.query}
2.638931
3
Hotel_Management_System_python/Registration.py
Mastermind-sap/HotelManagementSystem-python
1
6630505
<filename>Hotel_Management_System_python/Registration.py import Hotel_Management_Software class Registration: def main(self): print("") print("\t\t\t\t\t\t\t\t\tRegistration") print("\t\t\t\t\t\t\t\t\t************") print("") ob=Hotel_Management_Software() g=0 n1=0 while g==0: #Input for number of guests to be registered try: n1 = int(input("enter number of guests")) except ValueError: print("Invalid input") else: g = 1 break finally: if (n1==0) or (n1<1): g=0 print("Invalid input") if n1<=ob.remaining_rooms: i = (ob.no_rooms - ob.remaining_rooms) for d in range(0,n1): ob.remaining_rooms=ob.remaining_rooms-1 ob.name[i]=input("enter name of the guest") #input for the name of the guest to be registered f=0 #input for the gender of the guest to be registered while f==0: choice=input("enter 'M' if guest is a male\n 'F' if guest is a female")[0].upper() if choice=='M': ob.gender[i]="male" break elif choice=='F': ob.gender[i]="female" break else: print("Invalid input") #input for the age of the guest to be registered g1=0 while g1==0: try: ob.age[i]=int(input("enter age of the guest in years")) except ValueError: print("Invalid age") print("Try Again!") else: if(ob.age[i]==0) or (ob.age[i]<1) or (ob.age[i]>110): print("Invalid age") print("enter age of the guest again") else: g1=1 break #input for the address of the guest to be registered ob.address[i]=input("enter address of the guest") print("enter PAN number of the guest") #input for the PAN number of the guest to be registered int p=0 do { ob.pan[i]=sc.next() ob.pan[i]+=sc.nextLine() ob.pan[i]=ob.pan[i].toUpperCase() if((ob.pan[i].length()==10)&&(Character.isLetter(ob.pan[i].charAt(0)))&&(Character.isLetter(ob.pan[i].charAt(1))) &&(Character.isLetter(ob.pan[i].charAt(2)))&&(Character.isLetter(ob.pan[i].charAt(3))) &&(Character.isLetter(ob.pan[i].charAt(4)))&&(Character.isDigit(ob.pan[i].charAt(5))) &&(Character.isDigit(ob.pan[i].charAt(6)))&&(Character.isDigit(ob.pan[i].charAt(7))) &&(Character.isDigit(ob.pan[i].charAt(8)))&&(Character.isLetter(ob.pan[i].charAt(9)))) p=0 else {print("invalid PAN number") print("PAN structure is as follows: AAAPL1234C") print("please enter the PAN number again") p=1 } }while(p==1) DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss") #Take the system date and time as the check in date and time Date dateobj = new Date() ob.checkin_date_time[i]=df.format(dateobj) int w=0 #Input for the type of suit the guest wishes to live in while(w==0) { print("Enter 1 for Deluxe suit-- Rs.2000/day \n 2 for Super Deluxe suit-- Rs.4000/day \n 3 for Executive suit-- Rs.6000/day \n 4 for Presidential suite-- Rs.8000/day ") String s1=sc.next() s1+=sc.nextLine() int s=0 try { s=Integer.parseInt(s1) }catch(Exception e) { } switch(s) { case 1: ob.suite[i]="Deluxe" w=1 break case 2: ob.suite[i]="Super Deluxe" w=1 break case 3: ob.suite[i]="Executive" w=1 break case 4: ob.suite[i]="Presidential" w=1 break default: print("Wrong choice") } } } print("") print("\t\t\t\t\t\t\t\tRegistration is complete!") print("\t\t\t\t\t\t\t\t*************************") print("") } else { print("Sorry ,we are out of rooms") #inavailibity of rooms in the hotel print("We have only "+ob.remaining_rooms+" rooms at the moment") } } }
<filename>Hotel_Management_System_python/Registration.py import Hotel_Management_Software class Registration: def main(self): print("") print("\t\t\t\t\t\t\t\t\tRegistration") print("\t\t\t\t\t\t\t\t\t************") print("") ob=Hotel_Management_Software() g=0 n1=0 while g==0: #Input for number of guests to be registered try: n1 = int(input("enter number of guests")) except ValueError: print("Invalid input") else: g = 1 break finally: if (n1==0) or (n1<1): g=0 print("Invalid input") if n1<=ob.remaining_rooms: i = (ob.no_rooms - ob.remaining_rooms) for d in range(0,n1): ob.remaining_rooms=ob.remaining_rooms-1 ob.name[i]=input("enter name of the guest") #input for the name of the guest to be registered f=0 #input for the gender of the guest to be registered while f==0: choice=input("enter 'M' if guest is a male\n 'F' if guest is a female")[0].upper() if choice=='M': ob.gender[i]="male" break elif choice=='F': ob.gender[i]="female" break else: print("Invalid input") #input for the age of the guest to be registered g1=0 while g1==0: try: ob.age[i]=int(input("enter age of the guest in years")) except ValueError: print("Invalid age") print("Try Again!") else: if(ob.age[i]==0) or (ob.age[i]<1) or (ob.age[i]>110): print("Invalid age") print("enter age of the guest again") else: g1=1 break #input for the address of the guest to be registered ob.address[i]=input("enter address of the guest") print("enter PAN number of the guest") #input for the PAN number of the guest to be registered int p=0 do { ob.pan[i]=sc.next() ob.pan[i]+=sc.nextLine() ob.pan[i]=ob.pan[i].toUpperCase() if((ob.pan[i].length()==10)&&(Character.isLetter(ob.pan[i].charAt(0)))&&(Character.isLetter(ob.pan[i].charAt(1))) &&(Character.isLetter(ob.pan[i].charAt(2)))&&(Character.isLetter(ob.pan[i].charAt(3))) &&(Character.isLetter(ob.pan[i].charAt(4)))&&(Character.isDigit(ob.pan[i].charAt(5))) &&(Character.isDigit(ob.pan[i].charAt(6)))&&(Character.isDigit(ob.pan[i].charAt(7))) &&(Character.isDigit(ob.pan[i].charAt(8)))&&(Character.isLetter(ob.pan[i].charAt(9)))) p=0 else {print("invalid PAN number") print("PAN structure is as follows: AAAPL1234C") print("please enter the PAN number again") p=1 } }while(p==1) DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss") #Take the system date and time as the check in date and time Date dateobj = new Date() ob.checkin_date_time[i]=df.format(dateobj) int w=0 #Input for the type of suit the guest wishes to live in while(w==0) { print("Enter 1 for Deluxe suit-- Rs.2000/day \n 2 for Super Deluxe suit-- Rs.4000/day \n 3 for Executive suit-- Rs.6000/day \n 4 for Presidential suite-- Rs.8000/day ") String s1=sc.next() s1+=sc.nextLine() int s=0 try { s=Integer.parseInt(s1) }catch(Exception e) { } switch(s) { case 1: ob.suite[i]="Deluxe" w=1 break case 2: ob.suite[i]="Super Deluxe" w=1 break case 3: ob.suite[i]="Executive" w=1 break case 4: ob.suite[i]="Presidential" w=1 break default: print("Wrong choice") } } } print("") print("\t\t\t\t\t\t\t\tRegistration is complete!") print("\t\t\t\t\t\t\t\t*************************") print("") } else { print("Sorry ,we are out of rooms") #inavailibity of rooms in the hotel print("We have only "+ob.remaining_rooms+" rooms at the moment") } } }
en
0.804681
#Input for number of guests to be registered #input for the name of the guest to be registered #input for the gender of the guest to be registered #input for the age of the guest to be registered #input for the address of the guest to be registered #input for the PAN number of the guest to be registered #Take the system date and time as the check in date and time #Input for the type of suit the guest wishes to live in #inavailibity of rooms in the hotel
3.896387
4
server/products/models.py
tanvirtin/tinmart
2
6630506
<filename>server/products/models.py from mongoengine import Document, StringField, IntField, DictField, FloatField, ListField # model responsible for interacting with crawler_documents collection in walmartcrawler database in mongodb class CrawlerDocument(Document): docId = IntField() url = StringField() title = StringField() price = FloatField() category = StringField() productImgUrl = StringField() date = StringField() metadata = DictField() meta = {'db_alias': 'fillmyfridge'} # model responsible for interacting with transaction collection in class Transaction(Document): transactionId = StringField() products = ListField() meta = {'db_alias': 'tinmart'}
<filename>server/products/models.py from mongoengine import Document, StringField, IntField, DictField, FloatField, ListField # model responsible for interacting with crawler_documents collection in walmartcrawler database in mongodb class CrawlerDocument(Document): docId = IntField() url = StringField() title = StringField() price = FloatField() category = StringField() productImgUrl = StringField() date = StringField() metadata = DictField() meta = {'db_alias': 'fillmyfridge'} # model responsible for interacting with transaction collection in class Transaction(Document): transactionId = StringField() products = ListField() meta = {'db_alias': 'tinmart'}
en
0.84403
# model responsible for interacting with crawler_documents collection in walmartcrawler database in mongodb # model responsible for interacting with transaction collection in
2.213203
2
http-bench/python_test.py
vieyahn2017/go-test
0
6630507
import pytest import testutil @pytest.mark.parametrize("variant", ["httplib", "requests"]) @pytest.mark.parametrize("blocksize", [ 8, 32, 64, 128, 256, 512, 1024, 2048, 4096 ]) def test_python(server, variant, blocksize): print(testutil.upload(variant, testutil.SIZE_MB, blocksize)) @pytest.mark.parametrize("variant", ["httplib", "requests"]) @pytest.mark.parametrize("blocksize", [32, 64, 128, 256, 512]) def test_python_parallel(server, variant, blocksize): print(testutil.upload_parallel(variant, testutil.SIZE_MB, blocksize))
import pytest import testutil @pytest.mark.parametrize("variant", ["httplib", "requests"]) @pytest.mark.parametrize("blocksize", [ 8, 32, 64, 128, 256, 512, 1024, 2048, 4096 ]) def test_python(server, variant, blocksize): print(testutil.upload(variant, testutil.SIZE_MB, blocksize)) @pytest.mark.parametrize("variant", ["httplib", "requests"]) @pytest.mark.parametrize("blocksize", [32, 64, 128, 256, 512]) def test_python_parallel(server, variant, blocksize): print(testutil.upload_parallel(variant, testutil.SIZE_MB, blocksize))
none
1
2.001779
2
psctb/utils/model_comparing.py
PySCeS/PyscesToolbox
3
6630508
import copy import warnings from os import path import numpy as np import pandas as pd from pysces import Scanner, ParScanner from pysces import model as pysces_model from matplotlib import pyplot as plt from .misc import scanner_range_setup, DotDict, cc_dict, rc_dict, ec_dict, prc_dict, is_parameter, is_species, \ is_mca_coef, silence_print __all__ = ['compare_models', 'SteadyStateComparer', 'SimulationComparer', 'ParameterScanComparer', 'ClosedOpenComparer'] def compare_models(model_list, model_mapping = None, augment_mapping=True, comparison_type = 'ss'): """ Returns a specified model comparer for a list of models. The returned model comparer object considers the first model in `model_list` as the "base model" to which the other models are compared. Since models may have a different naming scheme for reactions, species, etc. `model_mapping` allows the user to specify the names of attributes of other models as they relate to the base model's attribute names. Parameters ---------- model_list : list of PysMod A list of PysMod (Pysces model) objects to be compared. model_mapping : array, optional (Default : None) An array that maps the names attributes of the base model to others. Each column relates to a different model in `model_list` in order. The first column contains the names of attributes of the base model, whereas each other column contains the name as it appears in the other models. Only species, reactions and parameters are needed as other attributes (e.g. control coefficients) are derived from these three categories. If None is supplied, all attributes are assumed to be named in the same way. augment_mapping : boolean, optional (Default : True) This parameter specifies if `model_mapping` should be used to augment a model_mapping which assumes all attributes are named in the same way. This is useful if only a few model attributes differ in their naming. If set to false, `model_mapping` must specify the relationships between all species, reaction and parameter names. comparison_type : str, optional (Default : "ss") A string that specifies which type of comparison should be made. Options are 'ss' for SteadyStateComparer, "parscan" for ParameterScanComparer, 'sim' for SimulationComparer, and 'closed_open' for 'ClosedOpenComparer'. Returns ------- values: ModelComparer A model comparer object instantiated with the arguments supplied above. """ if comparison_type == 'ss': comparer = SteadyStateComparer elif comparison_type == 'parscan': comparer = ParameterScanComparer elif comparison_type == 'sim': comparer = SimulationComparer elif comparison_type == 'closed_open': comparer = ClosedOpenComparer else: raise AssertionError('Incorrect comparison_type') return comparer(model_list, model_mapping, augment_mapping) class ModelMapper(object): @staticmethod def map_models(model_list, model_mapping=None, augment_mapping=True): # Replace duplicate models with clones model_list = ModelMapper.replace_with_clones(model_list) base_model = model_list[0] # Generate unique model names model_names = ModelMapper.generate_unique_model_names(model_list) if augment_mapping and model_mapping is not None: augment_map_dict_list = ModelMapper.make_map_dict_list(model_mapping) model_mapping = None else: augment_map_dict_list = None # Generate model mapping if needed if model_mapping is None: model_mapping = ModelMapper.auto_map_models(model_list) # Ensure that supplied (or generated) model mapping # at least has the correct shape assert model_mapping.shape[1] == len(model_list) # Make list of model_dicts map_dict_list = ModelMapper.make_map_dict_list(model_mapping) if augment_map_dict_list: for map_dict, augment_map_dict in zip(map_dict_list, augment_map_dict_list): map_dict.update(augment_map_dict) # Get newly fixed parameters for other models fixed_param_list = [None] for i, map_dict in enumerate(map_dict_list[1:]): i = 1 + i fixed_params = ModelMapper.get_now_fixed(base_model, model_list[i], map_dict) fixed_param_list.append(fixed_params) # Add mca coefficients to model_dicts base_mca_dict = ModelMapper.make_mca_dict(base_model) for map_dict in map_dict_list: mca_map_dict = ModelMapper.get_mca_dict_mapping(base_mca_dict, map_dict) map_dict.update(mca_map_dict) model_map_params = list(zip(model_list, model_names, map_dict_list, fixed_param_list)) model_maps = [] for model, model_name, map_dict, fixed_params in model_map_params: model_maps.append(ModelMap(model, model_name, map_dict, fixed_params)) return model_maps @staticmethod def make_map_dict_list(mapping_array): """ For a model mapping array, returns a list of dictionaries where the keys correspond to the fist column and the values correspond to each column (including the first). A 4 column array will thus produce a list of dicts of len 4 with the first having the same keys as values. """ base_vals = mapping_array[:, 0] comp_vals = mapping_array[:, 1:] dict_mapping = [dict(list(zip(base_vals, base_vals)))] for col in comp_vals.T: dict_mapping.append(dict(list(zip(base_vals, col)))) return dict_mapping @staticmethod def replace_with_clones(model_list): """ For a list of models potentially containing duplicate PySMod instantiations, returns a list of unique objects. """ new_model_list = [] for model in model_list: if model in new_model_list: new_model_list.append(ModelMapper.clone_model(model)) else: new_model_list.append(model) return new_model_list @staticmethod def generate_unique_model_names(model_list): """ Returns a list of unique model names for a list of models. """ model_names = [path.split(model.ModelFile)[-1][:-4] \ for model in model_list] for i, model_name in enumerate(model_names): indices = [j for j, v in enumerate(model_names) \ if v == model_name] if len(indices) > 1: for j, index in enumerate(indices): model_names[index] = model_name + '_' + str(j) return model_names @staticmethod def auto_map_models(model_list): """ For a list of models returns an array where each column maps contains the names of model attributes as they appear in each model. Missing species, parameters, and reactions are replaced with None. """ base_model = model_list[0] comparison_models = model_list[1:] base_attributes = list(base_model.species) + \ list(base_model.reactions) + \ list(base_model.parameters) mapping_array = [base_attributes] for model in comparison_models: match_attributes = [attr if hasattr(model, attr) \ else None \ for attr in base_attributes] mapping_array.append(match_attributes) return np.array(mapping_array).T @staticmethod def clone_model(model): """ Given a model this method returns a new instantiation of the same model. See also: replace_with_clones """ new_model_path = path.join(model.ModelDir, model.ModelFile) new_model = pysces_model(new_model_path) return new_model @staticmethod def get_mca_dict_mapping(mca_dict, map_dict): """ Given an mca dictionary of the base model and a map dictionary of any comparison model, this returns a dictionary that maps the names of mca coefficients in the base model to those in the comparison. See also: get_equiv_coeff """ return {k: ModelMapper.get_equiv_coeff(k, mca_dict, map_dict) for k in mca_dict.keys()} @staticmethod def get_equiv_coeff(coeff, mca_dict, map_dict): """ Given an mca coefficient, an mca dictionary of the base model and a map dictionary of any comparison model, this returns the name of the equivalent mca coefficient in the comparison model. See also: get_mca_dict_mapping """ coeff_type = ModelMapper.get_coeff_type(coeff) coeff_components = mca_dict[coeff] equiv_components = [map_dict[component] for component \ in coeff_components] if None in equiv_components: return None else: if coeff_type in ['cc', 'prc', 'rc']: prefix = coeff_type + 'J' else: prefix = coeff_type if coeff_type == 'prc': return prefix + '{}_{}_{}'.format(*equiv_components) else: return prefix + '{}_{}'.format(*equiv_components) @staticmethod def make_mca_dict(model): """ Returns a dictionary with the mca coefficients of a model as keys and a tuple of the components that make up each coefficient as values. """ full_dict = {} full_dict.update(ec_dict(model)) full_dict.update(cc_dict(model)) full_dict.update(rc_dict(model)) full_dict.update(prc_dict(model)) return full_dict @staticmethod def get_coeff_type(coefficient): """ Returns the coefficient type. """ if coefficient.startswith('prc'): return 'prc' elif coefficient.startswith('rc'): return 'rc' elif coefficient.startswith('ec'): return 'ec' elif coefficient.startswith('cc'): return 'cc' @staticmethod def get_now_fixed(base_model, comparison_model, map_dict): now_fixed_list = [] for k, v in map_dict.items(): if is_species(k, base_model) and is_parameter(v, comparison_model): now_fixed_list.append(k) return now_fixed_list class ModelMap(object): def __init__(self, model, model_name, attr_dict, is_now_fixed=None): self.model = model self.model_name = model_name self.attr_dict = attr_dict self._rev_attr_dict = ModelMap._reverse_dict(self.attr_dict) if not is_now_fixed: is_now_fixed = [] self.is_now_fixed = is_now_fixed @staticmethod def _reverse_dict(dict_): return {v: k for k, v in dict_.items()} def getattrname(self, key): prefix, suffix, key = ModelMap._prefix_suffix_getter(key) attr = self.attr_dict[key] if attr is None: return None elif key in self.is_now_fixed: return attr else: return prefix + attr + suffix def hasattr(self, item): _, _, item = ModelMap._prefix_suffix_getter(item) if item in list(self.attr_dict.keys()): return True else: return False def setattr(self, key, value): if self.hasattr(key): true_key = self.getattrname(key) if true_key is not None and hasattr(self.model, true_key): setattr(self.model, true_key, value) def getattr(self, item): true_key = self.getattrname(item) if true_key is None: return np.NaN else: return getattr(self.model, true_key) def attr_names_from_base_names(self, key_list, include_nones=False): converted_attrs = [] for key in key_list: true_attr = self.getattrname(key) if true_attr is None: if include_nones: converted_attrs.append(true_attr) else: converted_attrs.append(true_attr) return converted_attrs def base_names_from_attr_names(self, attr_list, add_ss = False): new_attr_list = [ModelMap._prefix_suffix_getter(attr) for \ attr in attr_list] for i, p_s_a in enumerate(new_attr_list): prefix, suffix, attr = p_s_a base_attr = self._rev_attr_dict[attr] if base_attr in self.is_now_fixed and add_ss: suffix = '_ss' new_attr_list[i] = (prefix, suffix, attr) converted_attrs = [prefix + self._rev_attr_dict[attr] + suffix for \ prefix, suffix, attr in new_attr_list] return converted_attrs def setattrs_from_dict(self, attr_dict): for key, value in attr_dict.items(): self.setattr(key, value) def getattrs_from_list(self, attr_list): return [self.getattr(key) for key in attr_list] @staticmethod def _prefix_suffix_getter(key): prefix = '' suffix = '' flux_prefix = 'J_' ssconc_suffix = '_ss' init_prefix = '_init' if key.startswith(flux_prefix): key = key[2:] prefix = flux_prefix elif key.endswith(ssconc_suffix): key = key[:-3] suffix = ssconc_suffix elif key.endswith(init_prefix): key = key[:-5] suffix = init_prefix return prefix, suffix, key class ResultsGenerator(object): @staticmethod def percentage_change(a, b, abs_values = False): with warnings.catch_warnings(): warnings.simplefilter("ignore") if abs_values: return np.divide(np.abs(np.subtract(b, a)), np.abs(a)) * 100 else: return np.divide(np.subtract(b, a), a) * 100 @staticmethod def do_par_scan(model, scan_in, scan_out, start, end, points, is_log_range, par_scan, par_engine): if par_scan: scanner = ParScanner(model, engine=par_engine) else: scanner = Scanner(model) scan_out = [str(each) for each in scan_out] scanner.addScanParameter(scan_in, start=start, end=end, points=points, log=is_log_range) scanner.addUserOutput(*scan_out) scanner.Run() result = scanner.getResultMatrix() return result @staticmethod def do_simulation(model, time_range, sim_out): model.sim_time = time_range model.Simulate(userinit=1) results, labels = model.data_sim.getAllSimData(lbls=True) sim_out = ['Time'] + sim_out sim_out_index = [labels.index(out_label) for out_label in sim_out] results_to_keep = results[:,sim_out_index] return results_to_keep class BaseModelComparer(object): def __init__(self, model_list, model_mapping=None, augment_mapping=True): super(BaseModelComparer, self).__init__() assert len(model_list) > 1, 'Two or more models are needed to make a comparison' self.mmap_list = ModelMapper.map_models(model_list=model_list, model_mapping=model_mapping, augment_mapping=augment_mapping) self.raw_data = None self.comparison = None @silence_print def do_compare(self, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list) self._compare_raw_data() @silence_print def _get_default_outputs(self): base_model = self.mmap_list[0].model return list(base_model.species) + list(base_model.reactions) @silence_print def _custom_init(self, custom_init): if custom_init: if type(custom_init) is dict: for mmap in self.mmap_list: mmap.setattrs_from_dict(custom_init) elif type(custom_init) is list: num_of_models = len(self.mmap_list) all_dicts = all([type(each) is dict for each in custom_init]) correct_num_of_dicts = len(custom_init) == num_of_models assert all_dicts and correct_num_of_dicts, \ "list of custom inits must contain {} dictionaries".format(num_of_models) for custom_init_dict, mmap in zip(custom_init, self.mmap_list): mmap.setattrs_from_dict(custom_init_dict) else: raise AssertionError("custom_inits must be a dictionary or a list of dictionaries") @silence_print def _uniform_init(self, uniform_init): if uniform_init: base_model = self.mmap_list[0].model base_parameter_dict = {k:getattr(base_model, k) for k in base_model.parameters} base_species_dict = {k:getattr(base_model, k) for k in base_model.species} base_attribute_dict = {} base_attribute_dict.update(base_parameter_dict) base_attribute_dict.update(base_species_dict) for mmap in self.mmap_list[1:]: mmap.setattrs_from_dict(base_attribute_dict) def _compare_raw_data(self): raise NotImplementedError def _generate_raw_data(self, output_list): raise NotImplementedError @silence_print def _output_to_ss(self, output_list): base_model = self.mmap_list[0].model new_out_list = [] for each in output_list: if each in base_model.species: new_out_list.append(each + '_ss') elif each in base_model.reactions: new_out_list.append('J_' + each) else: new_out_list.append(each) return new_out_list class SteadyStateComparer(BaseModelComparer): @silence_print def _generate_raw_data(self, output_list): output_list = self._output_to_ss(output_list) all_results = [] base_model = self.mmap_list[0].model state_method = 'mca' if any([is_mca_coef(attr, base_model) for attr in output_list]) else 'ss' for mmap in self.mmap_list: if state_method == 'mca': mmap.model.doMca() else: mmap.model.doState() model_results = [mmap.getattr(attr) for attr in output_list] all_results.append(model_results) all_results = np.array(all_results).T self.raw_data = pd.DataFrame(data=all_results, columns=[mmap.model_name for mmap in self.mmap_list], index=output_list) @silence_print def _compare_raw_data(self): raw_data = self.raw_data data_matrix = raw_data.as_matrix() reference_values = data_matrix[:,0] change_values = data_matrix[:,1:] comparison_names = [] all_results = [] for i, change_col in enumerate(change_values.T): comparison_name = '{}_{}'.format(self.mmap_list[0].model_name, self.mmap_list[i+1].model_name) comparison_names.append(comparison_name) comparison_result = ResultsGenerator.percentage_change(reference_values, change_col) all_results.append(comparison_result) all_results = np.array(all_results).T self.comparison = pd.DataFrame(data=all_results, columns=comparison_names, index=raw_data.index) class ParameterScanComparer(BaseModelComparer): @silence_print def do_compare(self, scan_in, scan_range, output_list=None, custom_init=None, uniform_init=True, par_scan=False, par_engine='multiproc'): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- scan_in : str A string that specifies the parameter to be varied scan_range : array-like An array that specifies the range of values over which `scan_in` should be varied output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. par_scan : boolean, optional (Default : False) If True the parameter scan will be executed using parallel processing. par_enging: str, optional (Default : 'multiproc') The parallel engine to be used. Options are dictated by PySCeS's ParScanner. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(scan_in, output_list, scan_range, par_scan, par_engine) self._compare_raw_data() @silence_print def _generate_raw_data(self, scan_in, output_list, scan_range, par_scan, par_engine): output_list = self._output_to_ss(output_list) main_column_labels = [scan_in] + output_list start, end, points, is_log_range = scanner_range_setup(scan_range) all_results = DotDict() for i, mmap in enumerate(self.mmap_list): current_scan_in = mmap.getattrname(scan_in) current_scan_out = mmap.attr_names_from_base_names(output_list) current_col_labels = [scan_in] + mmap.base_names_from_attr_names(current_scan_out, add_ss=True) # parameter scan raw_result = ResultsGenerator.do_par_scan(model=mmap.model, scan_in=current_scan_in, scan_out=current_scan_out, start=start, end=end, points=points, is_log_range=is_log_range, par_scan=par_scan, par_engine=par_engine) complete_results = pd.DataFrame(data=raw_result, columns=current_col_labels) complete_results = complete_results.reindex(columns=main_column_labels) complete_results = complete_results.set_index(scan_in) all_results[mmap.model_name] = complete_results self.raw_data = all_results @silence_print def _compare_raw_data(self): raw_data = self.raw_data reference_model_name = self.mmap_list[0].model_name reference_matrix = raw_data[reference_model_name].reset_index().as_matrix() column_labels = raw_data[reference_model_name].reset_index().columns all_results = DotDict() for mmap in self.mmap_list[1:]: current_model_name = mmap.model_name comparison_name = '{}_{}'.format(reference_model_name, current_model_name) change_matrix = raw_data[current_model_name].reset_index().as_matrix() comparison_result = ResultsGenerator.percentage_change(reference_matrix[:,1:],change_matrix[:,1:]) comparison_result = np.hstack([reference_matrix[:,0][:,np.newaxis],comparison_result]) df = pd.DataFrame(data=comparison_result, columns=column_labels) index = df.columns[0] df = df.set_index(index) all_results[comparison_name] = df self.comparison = all_results def plot(self,cols=3, width=None, height=None): """ Produces a simple plot that allows for the visual comparison of results for each model. Parameters ---------- cols : int, optional (Default : 3) The number of columns to use when plotting subplots. width : float, optional (Default : 15.0) The width of the figure in inches. height : float, optional (Default : 5.0*number of subplot rows) The height of the figure in inches. By default the height is dynamic in will be adjusted based on the number of rows of subplots where each row is assigned 5 inches. Returns ------- f: matplotlib figure A matplotlib figure on which results are plotted. axxarr: 2-dimensional numpy array of AxesSubplots An array that contains the axes associate with the figure. """ columns = list(self.raw_data.values())[0].columns index = list(self.raw_data.values())[0].index assert cols >= 2 rows = int(np.ceil(len(columns)/float(cols))) if not height: height = 5.*rows if not width: width = 15. f, axarr = plt.subplots(rows,cols) f.set_size_inches(w=width, h=height) for i in range(cols*rows - len(columns)): f.delaxes(axarr.flat[-1-i]) for column, ax in zip(columns,axarr.flat): for k, v in self.raw_data.items(): ax.plot(index, v[column], '-',label=k) ax.set_xlabel(index.name) ax.set_title(column) ax.legend() return f,axarr class SimulationComparer(ParameterScanComparer): @silence_print def do_compare(self, time_range, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list, time_range) self._compare_raw_data() @silence_print def _generate_raw_data(self, output_list, time_range): main_column_labels = ['Time'] + output_list all_results = DotDict() for i, mmap in enumerate(self.mmap_list): now_fixed_indicies = [] for i,out in enumerate(output_list): if out in mmap.is_now_fixed: now_fixed_indicies.append(i) new_output_list = copy.deepcopy(output_list) param_cols = [] for ind in reversed(now_fixed_indicies): out_val = mmap.getattr(output_list[ind]) new_output_list.pop(ind) param_cols.append([out_val for _ in range(time_range.shape[0])]) param_cols = param_cols current_sim_out = mmap.attr_names_from_base_names(new_output_list) real_sim_out = mmap.attr_names_from_base_names(output_list) current_col_labels = ['Time'] + mmap.base_names_from_attr_names(real_sim_out ) # parameter scan raw_result = ResultsGenerator.do_simulation(model=mmap.model, time_range=time_range, sim_out=current_sim_out) new_raw_result = [col for col in raw_result.T] for ind, col in zip(reversed(now_fixed_indicies), param_cols): new_raw_result.insert(ind, col) new_raw_result = np.array(new_raw_result).T complete_results = pd.DataFrame(data=new_raw_result, columns=current_col_labels) complete_results = complete_results.reindex(columns=main_column_labels) complete_results = complete_results.set_index('Time') all_results[mmap.model_name] = complete_results self.raw_data = all_results class ClosedOpenComparer(SimulationComparer): @silence_print def do_compare(self, time_range, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list, time_range) self._compare_raw_data() @silence_print def _generate_raw_data(self, output_list, time_range): base_mmap = self.mmap_list[0] full_scan_column_names = [] for mmap in self.mmap_list: full_scan_column_names = full_scan_column_names + mmap.is_now_fixed full_scan_column_names = list(set(full_scan_column_names)) base_sim_out_list = full_scan_column_names + [out for out in output_list \ if out not in full_scan_column_names] base_column_names = ['Time'] + base_sim_out_list all_results = DotDict() simulation_results = ResultsGenerator.do_simulation(model=base_mmap.model, time_range=time_range, sim_out=base_sim_out_list) base_complete_results = pd.DataFrame(data=simulation_results, columns=base_column_names) base_complete_results = base_complete_results.set_index('Time') all_results[base_mmap.model_name] = base_complete_results for i, mmap in enumerate(self.mmap_list[1:]): scan_column_names = mmap.is_now_fixed output_partial = [out for out in output_list if out not in scan_column_names] outputs = self._output_to_ss(output_partial) output_col_names = ['Time'] + scan_column_names + output_partial time_col = base_complete_results.reset_index()['Time'].as_matrix() input_val_list = [base_complete_results[col_name].as_matrix() for col_name in scan_column_names] raw_results = [] for input_vals in zip(*input_val_list): current_row = [] + list(input_vals) dict_to_set = dict(list(zip(scan_column_names, input_vals))) mmap.setattrs_from_dict(dict_to_set) mmap.model.doState() current_row = current_row + mmap.getattrs_from_list(outputs) raw_results.append(current_row) raw_results = np.hstack((time_col[:,np.newaxis],np.array(raw_results))) complete_results = pd.DataFrame(data=raw_results, columns=output_col_names) complete_results = complete_results.reindex(columns=base_column_names) complete_results = complete_results.set_index('Time') all_results[mmap.model_name] = complete_results self.raw_data = all_results
import copy import warnings from os import path import numpy as np import pandas as pd from pysces import Scanner, ParScanner from pysces import model as pysces_model from matplotlib import pyplot as plt from .misc import scanner_range_setup, DotDict, cc_dict, rc_dict, ec_dict, prc_dict, is_parameter, is_species, \ is_mca_coef, silence_print __all__ = ['compare_models', 'SteadyStateComparer', 'SimulationComparer', 'ParameterScanComparer', 'ClosedOpenComparer'] def compare_models(model_list, model_mapping = None, augment_mapping=True, comparison_type = 'ss'): """ Returns a specified model comparer for a list of models. The returned model comparer object considers the first model in `model_list` as the "base model" to which the other models are compared. Since models may have a different naming scheme for reactions, species, etc. `model_mapping` allows the user to specify the names of attributes of other models as they relate to the base model's attribute names. Parameters ---------- model_list : list of PysMod A list of PysMod (Pysces model) objects to be compared. model_mapping : array, optional (Default : None) An array that maps the names attributes of the base model to others. Each column relates to a different model in `model_list` in order. The first column contains the names of attributes of the base model, whereas each other column contains the name as it appears in the other models. Only species, reactions and parameters are needed as other attributes (e.g. control coefficients) are derived from these three categories. If None is supplied, all attributes are assumed to be named in the same way. augment_mapping : boolean, optional (Default : True) This parameter specifies if `model_mapping` should be used to augment a model_mapping which assumes all attributes are named in the same way. This is useful if only a few model attributes differ in their naming. If set to false, `model_mapping` must specify the relationships between all species, reaction and parameter names. comparison_type : str, optional (Default : "ss") A string that specifies which type of comparison should be made. Options are 'ss' for SteadyStateComparer, "parscan" for ParameterScanComparer, 'sim' for SimulationComparer, and 'closed_open' for 'ClosedOpenComparer'. Returns ------- values: ModelComparer A model comparer object instantiated with the arguments supplied above. """ if comparison_type == 'ss': comparer = SteadyStateComparer elif comparison_type == 'parscan': comparer = ParameterScanComparer elif comparison_type == 'sim': comparer = SimulationComparer elif comparison_type == 'closed_open': comparer = ClosedOpenComparer else: raise AssertionError('Incorrect comparison_type') return comparer(model_list, model_mapping, augment_mapping) class ModelMapper(object): @staticmethod def map_models(model_list, model_mapping=None, augment_mapping=True): # Replace duplicate models with clones model_list = ModelMapper.replace_with_clones(model_list) base_model = model_list[0] # Generate unique model names model_names = ModelMapper.generate_unique_model_names(model_list) if augment_mapping and model_mapping is not None: augment_map_dict_list = ModelMapper.make_map_dict_list(model_mapping) model_mapping = None else: augment_map_dict_list = None # Generate model mapping if needed if model_mapping is None: model_mapping = ModelMapper.auto_map_models(model_list) # Ensure that supplied (or generated) model mapping # at least has the correct shape assert model_mapping.shape[1] == len(model_list) # Make list of model_dicts map_dict_list = ModelMapper.make_map_dict_list(model_mapping) if augment_map_dict_list: for map_dict, augment_map_dict in zip(map_dict_list, augment_map_dict_list): map_dict.update(augment_map_dict) # Get newly fixed parameters for other models fixed_param_list = [None] for i, map_dict in enumerate(map_dict_list[1:]): i = 1 + i fixed_params = ModelMapper.get_now_fixed(base_model, model_list[i], map_dict) fixed_param_list.append(fixed_params) # Add mca coefficients to model_dicts base_mca_dict = ModelMapper.make_mca_dict(base_model) for map_dict in map_dict_list: mca_map_dict = ModelMapper.get_mca_dict_mapping(base_mca_dict, map_dict) map_dict.update(mca_map_dict) model_map_params = list(zip(model_list, model_names, map_dict_list, fixed_param_list)) model_maps = [] for model, model_name, map_dict, fixed_params in model_map_params: model_maps.append(ModelMap(model, model_name, map_dict, fixed_params)) return model_maps @staticmethod def make_map_dict_list(mapping_array): """ For a model mapping array, returns a list of dictionaries where the keys correspond to the fist column and the values correspond to each column (including the first). A 4 column array will thus produce a list of dicts of len 4 with the first having the same keys as values. """ base_vals = mapping_array[:, 0] comp_vals = mapping_array[:, 1:] dict_mapping = [dict(list(zip(base_vals, base_vals)))] for col in comp_vals.T: dict_mapping.append(dict(list(zip(base_vals, col)))) return dict_mapping @staticmethod def replace_with_clones(model_list): """ For a list of models potentially containing duplicate PySMod instantiations, returns a list of unique objects. """ new_model_list = [] for model in model_list: if model in new_model_list: new_model_list.append(ModelMapper.clone_model(model)) else: new_model_list.append(model) return new_model_list @staticmethod def generate_unique_model_names(model_list): """ Returns a list of unique model names for a list of models. """ model_names = [path.split(model.ModelFile)[-1][:-4] \ for model in model_list] for i, model_name in enumerate(model_names): indices = [j for j, v in enumerate(model_names) \ if v == model_name] if len(indices) > 1: for j, index in enumerate(indices): model_names[index] = model_name + '_' + str(j) return model_names @staticmethod def auto_map_models(model_list): """ For a list of models returns an array where each column maps contains the names of model attributes as they appear in each model. Missing species, parameters, and reactions are replaced with None. """ base_model = model_list[0] comparison_models = model_list[1:] base_attributes = list(base_model.species) + \ list(base_model.reactions) + \ list(base_model.parameters) mapping_array = [base_attributes] for model in comparison_models: match_attributes = [attr if hasattr(model, attr) \ else None \ for attr in base_attributes] mapping_array.append(match_attributes) return np.array(mapping_array).T @staticmethod def clone_model(model): """ Given a model this method returns a new instantiation of the same model. See also: replace_with_clones """ new_model_path = path.join(model.ModelDir, model.ModelFile) new_model = pysces_model(new_model_path) return new_model @staticmethod def get_mca_dict_mapping(mca_dict, map_dict): """ Given an mca dictionary of the base model and a map dictionary of any comparison model, this returns a dictionary that maps the names of mca coefficients in the base model to those in the comparison. See also: get_equiv_coeff """ return {k: ModelMapper.get_equiv_coeff(k, mca_dict, map_dict) for k in mca_dict.keys()} @staticmethod def get_equiv_coeff(coeff, mca_dict, map_dict): """ Given an mca coefficient, an mca dictionary of the base model and a map dictionary of any comparison model, this returns the name of the equivalent mca coefficient in the comparison model. See also: get_mca_dict_mapping """ coeff_type = ModelMapper.get_coeff_type(coeff) coeff_components = mca_dict[coeff] equiv_components = [map_dict[component] for component \ in coeff_components] if None in equiv_components: return None else: if coeff_type in ['cc', 'prc', 'rc']: prefix = coeff_type + 'J' else: prefix = coeff_type if coeff_type == 'prc': return prefix + '{}_{}_{}'.format(*equiv_components) else: return prefix + '{}_{}'.format(*equiv_components) @staticmethod def make_mca_dict(model): """ Returns a dictionary with the mca coefficients of a model as keys and a tuple of the components that make up each coefficient as values. """ full_dict = {} full_dict.update(ec_dict(model)) full_dict.update(cc_dict(model)) full_dict.update(rc_dict(model)) full_dict.update(prc_dict(model)) return full_dict @staticmethod def get_coeff_type(coefficient): """ Returns the coefficient type. """ if coefficient.startswith('prc'): return 'prc' elif coefficient.startswith('rc'): return 'rc' elif coefficient.startswith('ec'): return 'ec' elif coefficient.startswith('cc'): return 'cc' @staticmethod def get_now_fixed(base_model, comparison_model, map_dict): now_fixed_list = [] for k, v in map_dict.items(): if is_species(k, base_model) and is_parameter(v, comparison_model): now_fixed_list.append(k) return now_fixed_list class ModelMap(object): def __init__(self, model, model_name, attr_dict, is_now_fixed=None): self.model = model self.model_name = model_name self.attr_dict = attr_dict self._rev_attr_dict = ModelMap._reverse_dict(self.attr_dict) if not is_now_fixed: is_now_fixed = [] self.is_now_fixed = is_now_fixed @staticmethod def _reverse_dict(dict_): return {v: k for k, v in dict_.items()} def getattrname(self, key): prefix, suffix, key = ModelMap._prefix_suffix_getter(key) attr = self.attr_dict[key] if attr is None: return None elif key in self.is_now_fixed: return attr else: return prefix + attr + suffix def hasattr(self, item): _, _, item = ModelMap._prefix_suffix_getter(item) if item in list(self.attr_dict.keys()): return True else: return False def setattr(self, key, value): if self.hasattr(key): true_key = self.getattrname(key) if true_key is not None and hasattr(self.model, true_key): setattr(self.model, true_key, value) def getattr(self, item): true_key = self.getattrname(item) if true_key is None: return np.NaN else: return getattr(self.model, true_key) def attr_names_from_base_names(self, key_list, include_nones=False): converted_attrs = [] for key in key_list: true_attr = self.getattrname(key) if true_attr is None: if include_nones: converted_attrs.append(true_attr) else: converted_attrs.append(true_attr) return converted_attrs def base_names_from_attr_names(self, attr_list, add_ss = False): new_attr_list = [ModelMap._prefix_suffix_getter(attr) for \ attr in attr_list] for i, p_s_a in enumerate(new_attr_list): prefix, suffix, attr = p_s_a base_attr = self._rev_attr_dict[attr] if base_attr in self.is_now_fixed and add_ss: suffix = '_ss' new_attr_list[i] = (prefix, suffix, attr) converted_attrs = [prefix + self._rev_attr_dict[attr] + suffix for \ prefix, suffix, attr in new_attr_list] return converted_attrs def setattrs_from_dict(self, attr_dict): for key, value in attr_dict.items(): self.setattr(key, value) def getattrs_from_list(self, attr_list): return [self.getattr(key) for key in attr_list] @staticmethod def _prefix_suffix_getter(key): prefix = '' suffix = '' flux_prefix = 'J_' ssconc_suffix = '_ss' init_prefix = '_init' if key.startswith(flux_prefix): key = key[2:] prefix = flux_prefix elif key.endswith(ssconc_suffix): key = key[:-3] suffix = ssconc_suffix elif key.endswith(init_prefix): key = key[:-5] suffix = init_prefix return prefix, suffix, key class ResultsGenerator(object): @staticmethod def percentage_change(a, b, abs_values = False): with warnings.catch_warnings(): warnings.simplefilter("ignore") if abs_values: return np.divide(np.abs(np.subtract(b, a)), np.abs(a)) * 100 else: return np.divide(np.subtract(b, a), a) * 100 @staticmethod def do_par_scan(model, scan_in, scan_out, start, end, points, is_log_range, par_scan, par_engine): if par_scan: scanner = ParScanner(model, engine=par_engine) else: scanner = Scanner(model) scan_out = [str(each) for each in scan_out] scanner.addScanParameter(scan_in, start=start, end=end, points=points, log=is_log_range) scanner.addUserOutput(*scan_out) scanner.Run() result = scanner.getResultMatrix() return result @staticmethod def do_simulation(model, time_range, sim_out): model.sim_time = time_range model.Simulate(userinit=1) results, labels = model.data_sim.getAllSimData(lbls=True) sim_out = ['Time'] + sim_out sim_out_index = [labels.index(out_label) for out_label in sim_out] results_to_keep = results[:,sim_out_index] return results_to_keep class BaseModelComparer(object): def __init__(self, model_list, model_mapping=None, augment_mapping=True): super(BaseModelComparer, self).__init__() assert len(model_list) > 1, 'Two or more models are needed to make a comparison' self.mmap_list = ModelMapper.map_models(model_list=model_list, model_mapping=model_mapping, augment_mapping=augment_mapping) self.raw_data = None self.comparison = None @silence_print def do_compare(self, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list) self._compare_raw_data() @silence_print def _get_default_outputs(self): base_model = self.mmap_list[0].model return list(base_model.species) + list(base_model.reactions) @silence_print def _custom_init(self, custom_init): if custom_init: if type(custom_init) is dict: for mmap in self.mmap_list: mmap.setattrs_from_dict(custom_init) elif type(custom_init) is list: num_of_models = len(self.mmap_list) all_dicts = all([type(each) is dict for each in custom_init]) correct_num_of_dicts = len(custom_init) == num_of_models assert all_dicts and correct_num_of_dicts, \ "list of custom inits must contain {} dictionaries".format(num_of_models) for custom_init_dict, mmap in zip(custom_init, self.mmap_list): mmap.setattrs_from_dict(custom_init_dict) else: raise AssertionError("custom_inits must be a dictionary or a list of dictionaries") @silence_print def _uniform_init(self, uniform_init): if uniform_init: base_model = self.mmap_list[0].model base_parameter_dict = {k:getattr(base_model, k) for k in base_model.parameters} base_species_dict = {k:getattr(base_model, k) for k in base_model.species} base_attribute_dict = {} base_attribute_dict.update(base_parameter_dict) base_attribute_dict.update(base_species_dict) for mmap in self.mmap_list[1:]: mmap.setattrs_from_dict(base_attribute_dict) def _compare_raw_data(self): raise NotImplementedError def _generate_raw_data(self, output_list): raise NotImplementedError @silence_print def _output_to_ss(self, output_list): base_model = self.mmap_list[0].model new_out_list = [] for each in output_list: if each in base_model.species: new_out_list.append(each + '_ss') elif each in base_model.reactions: new_out_list.append('J_' + each) else: new_out_list.append(each) return new_out_list class SteadyStateComparer(BaseModelComparer): @silence_print def _generate_raw_data(self, output_list): output_list = self._output_to_ss(output_list) all_results = [] base_model = self.mmap_list[0].model state_method = 'mca' if any([is_mca_coef(attr, base_model) for attr in output_list]) else 'ss' for mmap in self.mmap_list: if state_method == 'mca': mmap.model.doMca() else: mmap.model.doState() model_results = [mmap.getattr(attr) for attr in output_list] all_results.append(model_results) all_results = np.array(all_results).T self.raw_data = pd.DataFrame(data=all_results, columns=[mmap.model_name for mmap in self.mmap_list], index=output_list) @silence_print def _compare_raw_data(self): raw_data = self.raw_data data_matrix = raw_data.as_matrix() reference_values = data_matrix[:,0] change_values = data_matrix[:,1:] comparison_names = [] all_results = [] for i, change_col in enumerate(change_values.T): comparison_name = '{}_{}'.format(self.mmap_list[0].model_name, self.mmap_list[i+1].model_name) comparison_names.append(comparison_name) comparison_result = ResultsGenerator.percentage_change(reference_values, change_col) all_results.append(comparison_result) all_results = np.array(all_results).T self.comparison = pd.DataFrame(data=all_results, columns=comparison_names, index=raw_data.index) class ParameterScanComparer(BaseModelComparer): @silence_print def do_compare(self, scan_in, scan_range, output_list=None, custom_init=None, uniform_init=True, par_scan=False, par_engine='multiproc'): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- scan_in : str A string that specifies the parameter to be varied scan_range : array-like An array that specifies the range of values over which `scan_in` should be varied output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. par_scan : boolean, optional (Default : False) If True the parameter scan will be executed using parallel processing. par_enging: str, optional (Default : 'multiproc') The parallel engine to be used. Options are dictated by PySCeS's ParScanner. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(scan_in, output_list, scan_range, par_scan, par_engine) self._compare_raw_data() @silence_print def _generate_raw_data(self, scan_in, output_list, scan_range, par_scan, par_engine): output_list = self._output_to_ss(output_list) main_column_labels = [scan_in] + output_list start, end, points, is_log_range = scanner_range_setup(scan_range) all_results = DotDict() for i, mmap in enumerate(self.mmap_list): current_scan_in = mmap.getattrname(scan_in) current_scan_out = mmap.attr_names_from_base_names(output_list) current_col_labels = [scan_in] + mmap.base_names_from_attr_names(current_scan_out, add_ss=True) # parameter scan raw_result = ResultsGenerator.do_par_scan(model=mmap.model, scan_in=current_scan_in, scan_out=current_scan_out, start=start, end=end, points=points, is_log_range=is_log_range, par_scan=par_scan, par_engine=par_engine) complete_results = pd.DataFrame(data=raw_result, columns=current_col_labels) complete_results = complete_results.reindex(columns=main_column_labels) complete_results = complete_results.set_index(scan_in) all_results[mmap.model_name] = complete_results self.raw_data = all_results @silence_print def _compare_raw_data(self): raw_data = self.raw_data reference_model_name = self.mmap_list[0].model_name reference_matrix = raw_data[reference_model_name].reset_index().as_matrix() column_labels = raw_data[reference_model_name].reset_index().columns all_results = DotDict() for mmap in self.mmap_list[1:]: current_model_name = mmap.model_name comparison_name = '{}_{}'.format(reference_model_name, current_model_name) change_matrix = raw_data[current_model_name].reset_index().as_matrix() comparison_result = ResultsGenerator.percentage_change(reference_matrix[:,1:],change_matrix[:,1:]) comparison_result = np.hstack([reference_matrix[:,0][:,np.newaxis],comparison_result]) df = pd.DataFrame(data=comparison_result, columns=column_labels) index = df.columns[0] df = df.set_index(index) all_results[comparison_name] = df self.comparison = all_results def plot(self,cols=3, width=None, height=None): """ Produces a simple plot that allows for the visual comparison of results for each model. Parameters ---------- cols : int, optional (Default : 3) The number of columns to use when plotting subplots. width : float, optional (Default : 15.0) The width of the figure in inches. height : float, optional (Default : 5.0*number of subplot rows) The height of the figure in inches. By default the height is dynamic in will be adjusted based on the number of rows of subplots where each row is assigned 5 inches. Returns ------- f: matplotlib figure A matplotlib figure on which results are plotted. axxarr: 2-dimensional numpy array of AxesSubplots An array that contains the axes associate with the figure. """ columns = list(self.raw_data.values())[0].columns index = list(self.raw_data.values())[0].index assert cols >= 2 rows = int(np.ceil(len(columns)/float(cols))) if not height: height = 5.*rows if not width: width = 15. f, axarr = plt.subplots(rows,cols) f.set_size_inches(w=width, h=height) for i in range(cols*rows - len(columns)): f.delaxes(axarr.flat[-1-i]) for column, ax in zip(columns,axarr.flat): for k, v in self.raw_data.items(): ax.plot(index, v[column], '-',label=k) ax.set_xlabel(index.name) ax.set_title(column) ax.legend() return f,axarr class SimulationComparer(ParameterScanComparer): @silence_print def do_compare(self, time_range, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list, time_range) self._compare_raw_data() @silence_print def _generate_raw_data(self, output_list, time_range): main_column_labels = ['Time'] + output_list all_results = DotDict() for i, mmap in enumerate(self.mmap_list): now_fixed_indicies = [] for i,out in enumerate(output_list): if out in mmap.is_now_fixed: now_fixed_indicies.append(i) new_output_list = copy.deepcopy(output_list) param_cols = [] for ind in reversed(now_fixed_indicies): out_val = mmap.getattr(output_list[ind]) new_output_list.pop(ind) param_cols.append([out_val for _ in range(time_range.shape[0])]) param_cols = param_cols current_sim_out = mmap.attr_names_from_base_names(new_output_list) real_sim_out = mmap.attr_names_from_base_names(output_list) current_col_labels = ['Time'] + mmap.base_names_from_attr_names(real_sim_out ) # parameter scan raw_result = ResultsGenerator.do_simulation(model=mmap.model, time_range=time_range, sim_out=current_sim_out) new_raw_result = [col for col in raw_result.T] for ind, col in zip(reversed(now_fixed_indicies), param_cols): new_raw_result.insert(ind, col) new_raw_result = np.array(new_raw_result).T complete_results = pd.DataFrame(data=new_raw_result, columns=current_col_labels) complete_results = complete_results.reindex(columns=main_column_labels) complete_results = complete_results.set_index('Time') all_results[mmap.model_name] = complete_results self.raw_data = all_results class ClosedOpenComparer(SimulationComparer): @silence_print def do_compare(self, time_range, output_list=None, custom_init=None, uniform_init=True): """ Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. """ if output_list is None: output_list = self._get_default_outputs() self._uniform_init(uniform_init) self._custom_init(custom_init) self._generate_raw_data(output_list, time_range) self._compare_raw_data() @silence_print def _generate_raw_data(self, output_list, time_range): base_mmap = self.mmap_list[0] full_scan_column_names = [] for mmap in self.mmap_list: full_scan_column_names = full_scan_column_names + mmap.is_now_fixed full_scan_column_names = list(set(full_scan_column_names)) base_sim_out_list = full_scan_column_names + [out for out in output_list \ if out not in full_scan_column_names] base_column_names = ['Time'] + base_sim_out_list all_results = DotDict() simulation_results = ResultsGenerator.do_simulation(model=base_mmap.model, time_range=time_range, sim_out=base_sim_out_list) base_complete_results = pd.DataFrame(data=simulation_results, columns=base_column_names) base_complete_results = base_complete_results.set_index('Time') all_results[base_mmap.model_name] = base_complete_results for i, mmap in enumerate(self.mmap_list[1:]): scan_column_names = mmap.is_now_fixed output_partial = [out for out in output_list if out not in scan_column_names] outputs = self._output_to_ss(output_partial) output_col_names = ['Time'] + scan_column_names + output_partial time_col = base_complete_results.reset_index()['Time'].as_matrix() input_val_list = [base_complete_results[col_name].as_matrix() for col_name in scan_column_names] raw_results = [] for input_vals in zip(*input_val_list): current_row = [] + list(input_vals) dict_to_set = dict(list(zip(scan_column_names, input_vals))) mmap.setattrs_from_dict(dict_to_set) mmap.model.doState() current_row = current_row + mmap.getattrs_from_list(outputs) raw_results.append(current_row) raw_results = np.hstack((time_col[:,np.newaxis],np.array(raw_results))) complete_results = pd.DataFrame(data=raw_results, columns=output_col_names) complete_results = complete_results.reindex(columns=base_column_names) complete_results = complete_results.set_index('Time') all_results[mmap.model_name] = complete_results self.raw_data = all_results
en
0.723177
Returns a specified model comparer for a list of models. The returned model comparer object considers the first model in `model_list` as the "base model" to which the other models are compared. Since models may have a different naming scheme for reactions, species, etc. `model_mapping` allows the user to specify the names of attributes of other models as they relate to the base model's attribute names. Parameters ---------- model_list : list of PysMod A list of PysMod (Pysces model) objects to be compared. model_mapping : array, optional (Default : None) An array that maps the names attributes of the base model to others. Each column relates to a different model in `model_list` in order. The first column contains the names of attributes of the base model, whereas each other column contains the name as it appears in the other models. Only species, reactions and parameters are needed as other attributes (e.g. control coefficients) are derived from these three categories. If None is supplied, all attributes are assumed to be named in the same way. augment_mapping : boolean, optional (Default : True) This parameter specifies if `model_mapping` should be used to augment a model_mapping which assumes all attributes are named in the same way. This is useful if only a few model attributes differ in their naming. If set to false, `model_mapping` must specify the relationships between all species, reaction and parameter names. comparison_type : str, optional (Default : "ss") A string that specifies which type of comparison should be made. Options are 'ss' for SteadyStateComparer, "parscan" for ParameterScanComparer, 'sim' for SimulationComparer, and 'closed_open' for 'ClosedOpenComparer'. Returns ------- values: ModelComparer A model comparer object instantiated with the arguments supplied above. # Replace duplicate models with clones # Generate unique model names # Generate model mapping if needed # Ensure that supplied (or generated) model mapping # at least has the correct shape # Make list of model_dicts # Get newly fixed parameters for other models # Add mca coefficients to model_dicts For a model mapping array, returns a list of dictionaries where the keys correspond to the fist column and the values correspond to each column (including the first). A 4 column array will thus produce a list of dicts of len 4 with the first having the same keys as values. For a list of models potentially containing duplicate PySMod instantiations, returns a list of unique objects. Returns a list of unique model names for a list of models. For a list of models returns an array where each column maps contains the names of model attributes as they appear in each model. Missing species, parameters, and reactions are replaced with None. Given a model this method returns a new instantiation of the same model. See also: replace_with_clones Given an mca dictionary of the base model and a map dictionary of any comparison model, this returns a dictionary that maps the names of mca coefficients in the base model to those in the comparison. See also: get_equiv_coeff Given an mca coefficient, an mca dictionary of the base model and a map dictionary of any comparison model, this returns the name of the equivalent mca coefficient in the comparison model. See also: get_mca_dict_mapping Returns a dictionary with the mca coefficients of a model as keys and a tuple of the components that make up each coefficient as values. Returns the coefficient type. Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- scan_in : str A string that specifies the parameter to be varied scan_range : array-like An array that specifies the range of values over which `scan_in` should be varied output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. par_scan : boolean, optional (Default : False) If True the parameter scan will be executed using parallel processing. par_enging: str, optional (Default : 'multiproc') The parallel engine to be used. Options are dictated by PySCeS's ParScanner. # parameter scan Produces a simple plot that allows for the visual comparison of results for each model. Parameters ---------- cols : int, optional (Default : 3) The number of columns to use when plotting subplots. width : float, optional (Default : 15.0) The width of the figure in inches. height : float, optional (Default : 5.0*number of subplot rows) The height of the figure in inches. By default the height is dynamic in will be adjusted based on the number of rows of subplots where each row is assigned 5 inches. Returns ------- f: matplotlib figure A matplotlib figure on which results are plotted. axxarr: 2-dimensional numpy array of AxesSubplots An array that contains the axes associate with the figure. Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform. # parameter scan Performs the comparison of the models. Results are stored in `self.raw_data` and `self.comparison`. Parameters ---------- time_range : array-like An array that specifies the range of values over which `Time` should be varied. It allows for starting points other than zero. output_list : list of str, optional (Default : None) A list of model attributes to compare. Valid options are: species, reactions, parameters, and mca coefficients. custom_init : dict or list of dict, optional (Default : None) A dictionary specifying the initial conditions of the models. Keys specify model attributes (in str) and values are float values of these attributes. A list of dictionaries can also be supplied in order to give each model a different set of initial conditions. The list follows the same order as the `model_list` supplied during object instantiation. uniform_init : boolean, optional (Default : True) If set to True, the attributes of each model will be set to that of the base model prior to comparison. `custom_inits` are applied after making model attributes uniform.
2.256458
2
vipsevents/eventapp/apps.py
ACE-VSIT/vips-events
0
6630509
from django.apps import AppConfig class EventappConfig(AppConfig): name = 'vipsevents.eventapp'
from django.apps import AppConfig class EventappConfig(AppConfig): name = 'vipsevents.eventapp'
none
1
1.079371
1
dcorch/common/endpoint_cache.py
DadeCoderh/starlingx-stagingm
1
6630510
# Copyright 2015 Huawei Technologies Co., Ltd. # 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 from keystoneauth1 import loading from keystoneauth1 import session from keystoneclient.v3 import client as keystone_client from oslo_config import cfg from oslo_log import log as logging from dcorch.common import consts LOG = logging.getLogger(__name__) class EndpointCache(object): def __init__(self, region_name=None, auth_url=None): self.endpoint_map = collections.defaultdict(dict) self.admin_session = None self.keystone_client = None # if auth_url is provided use that otherwise use the one # defined in the config if auth_url: self.external_auth_url = auth_url else: self.external_auth_url = cfg.CONF.cache.auth_uri self._initialize_keystone_client(region_name, auth_url) self._update_endpoints() def _initialize_keystone_client(self, region_name=None, auth_url=None): loader = loading.get_plugin_loader( cfg.CONF.keystone_authtoken.auth_type) auth = loader.load_from_options( auth_url=self.external_auth_url, username=cfg.CONF.cache.admin_username, user_domain_name=cfg.CONF.cache.admin_user_domain_name, password=cfg.CONF.cache.admin_password, project_name=cfg.CONF.cache.admin_tenant, project_domain_name=cfg.CONF.cache.admin_project_domain_name, ) self.admin_session = session.Session( auth=auth, additional_headers=consts.USER_HEADER) self.keystone_client = keystone_client.Client( session=self.admin_session, region_name=consts.VIRTUAL_MASTER_CLOUD) # if Endpoint cache is intended for a subcloud then # we need to retrieve the subcloud token and session. # Skip this if auth_url was provided as its assumed that the # auth_url would correspond to a subcloud so session was # set up above if (not auth_url and region_name and region_name not in [consts.CLOUD_0, consts.VIRTUAL_MASTER_CLOUD]): identity_service = self.keystone_client.services.list( name='keystone', type='identity') sc_auth_url = self.keystone_client.endpoints.list( service=identity_service[0].id, interface=consts.KS_ENDPOINT_INTERNAL, region=region_name) try: sc_auth_url = sc_auth_url[0].url except IndexError: LOG.error("Cannot find identity auth_url for %s", region_name) raise sc_loader = loading.get_plugin_loader( cfg.CONF.keystone_authtoken.auth_type) # We assume that the Admin user names and passwords are the same # on this subcloud since this is an audited resource sc_auth = sc_loader.load_from_options( auth_url=sc_auth_url, username=cfg.CONF.cache.admin_username, user_domain_name=cfg.CONF.cache.admin_user_domain_name, password=cfg.CONF.cache.admin_password, project_name=cfg.CONF.cache.admin_tenant, project_domain_name=cfg.CONF.cache.admin_project_domain_name, ) self.admin_session = session.Session( auth=sc_auth, additional_headers=consts.USER_HEADER) self.keystone_client = keystone_client.Client( session=self.admin_session, region_name=region_name) self.external_auth_url = sc_auth_url @staticmethod def _get_endpoint_from_keystone(self): service_id_name_map = {} for service in self.keystone_client.services.list(): service_dict = service.to_dict() service_id_name_map[service_dict['id']] = service_dict['name'] region_service_endpoint_map = {} for endpoint in self.keystone_client.endpoints.list(): endpoint_dict = endpoint.to_dict() if endpoint_dict['interface'] != consts.KS_ENDPOINT_INTERNAL: continue region_id = endpoint_dict['region'] service_id = endpoint_dict['service_id'] url = endpoint_dict['url'] service_name = service_id_name_map[service_id] if region_id not in region_service_endpoint_map: region_service_endpoint_map[region_id] = {} region_service_endpoint_map[region_id][service_name] = url return region_service_endpoint_map def _get_endpoint(self, region, service, retry): if service not in self.endpoint_map[region]: if retry: self.update_endpoints() return self._get_endpoint(region, service, False) else: return '' else: return self.endpoint_map[region][service] def _update_endpoints(self): endpoint_map = EndpointCache._get_endpoint_from_keystone(self) for region in endpoint_map: for service in endpoint_map[region]: self.endpoint_map[region][ service] = endpoint_map[region][service] def get_endpoint(self, region, service): """Get service endpoint url. :param region: region the service belongs to :param service: service type :return: url of the service """ return self._get_endpoint(region, service, True) def update_endpoints(self): """Update endpoint cache from Keystone. :return: None """ self._update_endpoints() def get_all_regions(self): """Get region list. return: List of regions """ return self.endpoint_map.keys() def get_session_from_token(self, token, project_id): """Get session based on token to communicate with openstack services. :param token: token with which the request is triggered. :param project_id: UUID of the project. :return: session object. """ loader = loading.get_plugin_loader('token') auth = loader.load_from_options(auth_url=self.external_auth_url, token=token, project_id=project_id) sess = session.Session(auth=auth) return sess
# Copyright 2015 Huawei Technologies Co., Ltd. # 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 from keystoneauth1 import loading from keystoneauth1 import session from keystoneclient.v3 import client as keystone_client from oslo_config import cfg from oslo_log import log as logging from dcorch.common import consts LOG = logging.getLogger(__name__) class EndpointCache(object): def __init__(self, region_name=None, auth_url=None): self.endpoint_map = collections.defaultdict(dict) self.admin_session = None self.keystone_client = None # if auth_url is provided use that otherwise use the one # defined in the config if auth_url: self.external_auth_url = auth_url else: self.external_auth_url = cfg.CONF.cache.auth_uri self._initialize_keystone_client(region_name, auth_url) self._update_endpoints() def _initialize_keystone_client(self, region_name=None, auth_url=None): loader = loading.get_plugin_loader( cfg.CONF.keystone_authtoken.auth_type) auth = loader.load_from_options( auth_url=self.external_auth_url, username=cfg.CONF.cache.admin_username, user_domain_name=cfg.CONF.cache.admin_user_domain_name, password=cfg.CONF.cache.admin_password, project_name=cfg.CONF.cache.admin_tenant, project_domain_name=cfg.CONF.cache.admin_project_domain_name, ) self.admin_session = session.Session( auth=auth, additional_headers=consts.USER_HEADER) self.keystone_client = keystone_client.Client( session=self.admin_session, region_name=consts.VIRTUAL_MASTER_CLOUD) # if Endpoint cache is intended for a subcloud then # we need to retrieve the subcloud token and session. # Skip this if auth_url was provided as its assumed that the # auth_url would correspond to a subcloud so session was # set up above if (not auth_url and region_name and region_name not in [consts.CLOUD_0, consts.VIRTUAL_MASTER_CLOUD]): identity_service = self.keystone_client.services.list( name='keystone', type='identity') sc_auth_url = self.keystone_client.endpoints.list( service=identity_service[0].id, interface=consts.KS_ENDPOINT_INTERNAL, region=region_name) try: sc_auth_url = sc_auth_url[0].url except IndexError: LOG.error("Cannot find identity auth_url for %s", region_name) raise sc_loader = loading.get_plugin_loader( cfg.CONF.keystone_authtoken.auth_type) # We assume that the Admin user names and passwords are the same # on this subcloud since this is an audited resource sc_auth = sc_loader.load_from_options( auth_url=sc_auth_url, username=cfg.CONF.cache.admin_username, user_domain_name=cfg.CONF.cache.admin_user_domain_name, password=cfg.CONF.cache.admin_password, project_name=cfg.CONF.cache.admin_tenant, project_domain_name=cfg.CONF.cache.admin_project_domain_name, ) self.admin_session = session.Session( auth=sc_auth, additional_headers=consts.USER_HEADER) self.keystone_client = keystone_client.Client( session=self.admin_session, region_name=region_name) self.external_auth_url = sc_auth_url @staticmethod def _get_endpoint_from_keystone(self): service_id_name_map = {} for service in self.keystone_client.services.list(): service_dict = service.to_dict() service_id_name_map[service_dict['id']] = service_dict['name'] region_service_endpoint_map = {} for endpoint in self.keystone_client.endpoints.list(): endpoint_dict = endpoint.to_dict() if endpoint_dict['interface'] != consts.KS_ENDPOINT_INTERNAL: continue region_id = endpoint_dict['region'] service_id = endpoint_dict['service_id'] url = endpoint_dict['url'] service_name = service_id_name_map[service_id] if region_id not in region_service_endpoint_map: region_service_endpoint_map[region_id] = {} region_service_endpoint_map[region_id][service_name] = url return region_service_endpoint_map def _get_endpoint(self, region, service, retry): if service not in self.endpoint_map[region]: if retry: self.update_endpoints() return self._get_endpoint(region, service, False) else: return '' else: return self.endpoint_map[region][service] def _update_endpoints(self): endpoint_map = EndpointCache._get_endpoint_from_keystone(self) for region in endpoint_map: for service in endpoint_map[region]: self.endpoint_map[region][ service] = endpoint_map[region][service] def get_endpoint(self, region, service): """Get service endpoint url. :param region: region the service belongs to :param service: service type :return: url of the service """ return self._get_endpoint(region, service, True) def update_endpoints(self): """Update endpoint cache from Keystone. :return: None """ self._update_endpoints() def get_all_regions(self): """Get region list. return: List of regions """ return self.endpoint_map.keys() def get_session_from_token(self, token, project_id): """Get session based on token to communicate with openstack services. :param token: token with which the request is triggered. :param project_id: UUID of the project. :return: session object. """ loader = loading.get_plugin_loader('token') auth = loader.load_from_options(auth_url=self.external_auth_url, token=token, project_id=project_id) sess = session.Session(auth=auth) return sess
en
0.87691
# Copyright 2015 Huawei Technologies Co., Ltd. # 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. # if auth_url is provided use that otherwise use the one # defined in the config # if Endpoint cache is intended for a subcloud then # we need to retrieve the subcloud token and session. # Skip this if auth_url was provided as its assumed that the # auth_url would correspond to a subcloud so session was # set up above # We assume that the Admin user names and passwords are the same # on this subcloud since this is an audited resource Get service endpoint url. :param region: region the service belongs to :param service: service type :return: url of the service Update endpoint cache from Keystone. :return: None Get region list. return: List of regions Get session based on token to communicate with openstack services. :param token: token with which the request is triggered. :param project_id: UUID of the project. :return: session object.
1.700357
2
checkov/secrets/runner.py
jasonckeating/checkov
0
6630511
import linecache import logging import os import re from typing import Optional, List from detect_secrets import SecretsCollection from detect_secrets.core import scan from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.settings import transient_settings from typing_extensions import TypedDict from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.comment.enum import COMMENT_REGEX from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.models.enums import CheckResult from checkov.common.output.record import Record from checkov.common.output.report import Report from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.common.runners.base_runner import ignored_directories from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.runner_filter import RunnerFilter SECRET_TYPE_TO_ID = { 'Artifactory Credentials': 'CKV_SECRET_1', 'AWS Access Key': 'CKV_SECRET_2', 'Azure Storage Account access key': 'CKV_SECRET_3', 'Basic Auth Credentials': 'CKV_SECRET_4', 'Cloudant Credentials': 'CKV_SECRET_5', 'Base64 High Entropy String': 'CKV_SECRET_6', 'IBM Cloud IAM Key': 'CKV_SECRET_7', 'IBM COS HMAC Credentials': 'CKV_SECRET_8', 'JSON Web Token': 'CKV_SECRET_9', # 'Secret Keyword': 'CKV_SECRET_10', 'Mailchimp Access Key': 'CKV_SECRET_11', 'NPM tokens': 'CKV_SECRET_12', 'Private Key': 'CKV_SECRET_13', 'Slack Token': '<PASSWORD>', 'SoftLayer Credentials': 'CKV_SECRET_15', 'Square OAuth Secret': 'CKV_SECRET_16', 'Stripe Access Key': 'CKV_SECRET_17', 'Twilio API Key': 'CKV_SECRET_18', 'Hex High Entropy String': 'CKV_SECRET_19' } CHECK_ID_TO_SECRET_TYPE = {v: k for k, v in SECRET_TYPE_TO_ID.items()} ENTROPY_KEYWORD_LIMIT = 3 PROHIBITED_FILES = ['Pipfile.lock', 'yarn.lock', 'package-lock.json', 'requirements.txt'] class _CheckResult(TypedDict, total=False): result: CheckResult suppress_comment: str class Runner(BaseRunner): check_type = 'secrets' def run( self, root_folder: str, external_checks_dir: Optional[List[str]] = None, files: Optional[List[str]] = None, runner_filter: RunnerFilter = RunnerFilter(), collect_skip_comments: bool = True ) -> Report: current_dir = os.path.dirname(os.path.realpath(__file__)) secrets = SecretsCollection() with transient_settings({ # Only run scans with only these plugins. 'plugins_used': [ { 'name': 'AWSKeyDetector' }, { 'name': 'ArtifactoryDetector' }, { 'name': 'AzureStorageKeyDetector' }, { 'name': 'BasicAuthDetector' }, { 'name': 'CloudantDetector' }, { 'name': 'IbmCloudIamDetector' }, { 'name': 'MailchimpDetector' }, { 'name': 'PrivateKeyDetector' }, { 'name': 'SlackDetector' }, { 'name': 'SoftlayerDetector' }, { 'name': 'SquareOAuthDetector' }, { 'name': 'StripeDetector' }, { 'name': 'TwilioKeyDetector' }, { 'name': 'EntropyKeywordCombinator', 'path': f'file://{current_dir}/plugins/entropy_keyword_combinator.py', 'limit': ENTROPY_KEYWORD_LIMIT } ] }) as settings: report = Report(self.check_type) # Implement non IaC files (including .terraform dir) files_to_scan = files or [] excluded_paths = (runner_filter.excluded_paths or []) + ignored_directories + [DEFAULT_EXTERNAL_MODULES_DIR] if root_folder: for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) for file in f_names: if file not in PROHIBITED_FILES and f".{file.split('.')[-1]}" in SUPPORTED_FILE_EXTENSIONS: files_to_scan.append(os.path.join(root, file)) logging.info(f'Secrets scanning will scan {len(files_to_scan)} files') settings.disable_filters(*['detect_secrets.filters.heuristic.is_indirect_reference']) Runner._scan_files(files_to_scan, secrets) for _, secret in iter(secrets): check_id = SECRET_TYPE_TO_ID.get(secret.type) bc_check_id = bc_integration.ckv_to_bc_id_mapping.get(check_id) if bc_integration.ckv_to_bc_id_mapping else None if not check_id: continue if runner_filter.checks and not runner_filter.should_run_check(check_id, bc_check_id): continue result: _CheckResult = {'result': CheckResult.FAILED} line_text = linecache.getline(secret.filename, secret.line_number) if line_text != "" and len(line_text.split()) > 0 and line_text.split()[0] == 'git_commit': continue result = self.search_for_suppression( check_id=check_id, bc_check_id=bc_check_id, secret=secret, runner_filter=runner_filter, ) or result report.add_resource(f'{secret.filename}:{secret.secret_hash}') report.add_record(Record( check_id=check_id, bc_check_id=bc_check_id, check_name=secret.type, check_result=result, code_block=[(secret.line_number, line_text)], file_path=f'/{os.path.relpath(secret.filename, root_folder)}', file_line_range=[secret.line_number, secret.line_number + 1], resource=secret.secret_hash, check_class=None, evaluations=None, file_abs_path=os.path.abspath(secret.filename) )) return report @staticmethod def _scan_files(files_to_scan, secrets): # implemented the scan function like secrets.scan_files results = parallel_runner.run_function( lambda f: list(scan.scan_file(os.path.join(secrets.root, f))), files_to_scan) for secrets_results in results: for secret in secrets_results: secrets[os.path.relpath(secret.filename, secrets.root)].add(secret) @staticmethod def search_for_suppression( check_id: str, bc_check_id: str, secret: PotentialSecret, runner_filter: RunnerFilter ) -> Optional[_CheckResult]: if not runner_filter.should_run_check(check_id, bc_check_id) and check_id in CHECK_ID_TO_SECRET_TYPE.keys(): return { "result": CheckResult.SKIPPED, "suppress_comment": f"Secret scan {check_id} is skipped" } # Check for suppression comment in the line before, the line of, and the line after the secret for line_number in [secret.line_number, secret.line_number - 1, secret.line_number + 1]: lt = linecache.getline(secret.filename, line_number) skip_search = re.search(COMMENT_REGEX, lt) if skip_search and (skip_search.group(2) == check_id or skip_search.group(2) == bc_check_id): return { "result": CheckResult.SKIPPED, "suppress_comment": skip_search.group(3)[1:] if skip_search.group(3) else "No comment provided" } return None
import linecache import logging import os import re from typing import Optional, List from detect_secrets import SecretsCollection from detect_secrets.core import scan from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.settings import transient_settings from typing_extensions import TypedDict from checkov.common.bridgecrew.platform_integration import bc_integration from checkov.common.comment.enum import COMMENT_REGEX from checkov.common.parallelizer.parallel_runner import parallel_runner from checkov.common.models.consts import SUPPORTED_FILE_EXTENSIONS from checkov.common.models.enums import CheckResult from checkov.common.output.record import Record from checkov.common.output.report import Report from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths from checkov.common.runners.base_runner import ignored_directories from checkov.common.util.consts import DEFAULT_EXTERNAL_MODULES_DIR from checkov.runner_filter import RunnerFilter SECRET_TYPE_TO_ID = { 'Artifactory Credentials': 'CKV_SECRET_1', 'AWS Access Key': 'CKV_SECRET_2', 'Azure Storage Account access key': 'CKV_SECRET_3', 'Basic Auth Credentials': 'CKV_SECRET_4', 'Cloudant Credentials': 'CKV_SECRET_5', 'Base64 High Entropy String': 'CKV_SECRET_6', 'IBM Cloud IAM Key': 'CKV_SECRET_7', 'IBM COS HMAC Credentials': 'CKV_SECRET_8', 'JSON Web Token': 'CKV_SECRET_9', # 'Secret Keyword': 'CKV_SECRET_10', 'Mailchimp Access Key': 'CKV_SECRET_11', 'NPM tokens': 'CKV_SECRET_12', 'Private Key': 'CKV_SECRET_13', 'Slack Token': '<PASSWORD>', 'SoftLayer Credentials': 'CKV_SECRET_15', 'Square OAuth Secret': 'CKV_SECRET_16', 'Stripe Access Key': 'CKV_SECRET_17', 'Twilio API Key': 'CKV_SECRET_18', 'Hex High Entropy String': 'CKV_SECRET_19' } CHECK_ID_TO_SECRET_TYPE = {v: k for k, v in SECRET_TYPE_TO_ID.items()} ENTROPY_KEYWORD_LIMIT = 3 PROHIBITED_FILES = ['Pipfile.lock', 'yarn.lock', 'package-lock.json', 'requirements.txt'] class _CheckResult(TypedDict, total=False): result: CheckResult suppress_comment: str class Runner(BaseRunner): check_type = 'secrets' def run( self, root_folder: str, external_checks_dir: Optional[List[str]] = None, files: Optional[List[str]] = None, runner_filter: RunnerFilter = RunnerFilter(), collect_skip_comments: bool = True ) -> Report: current_dir = os.path.dirname(os.path.realpath(__file__)) secrets = SecretsCollection() with transient_settings({ # Only run scans with only these plugins. 'plugins_used': [ { 'name': 'AWSKeyDetector' }, { 'name': 'ArtifactoryDetector' }, { 'name': 'AzureStorageKeyDetector' }, { 'name': 'BasicAuthDetector' }, { 'name': 'CloudantDetector' }, { 'name': 'IbmCloudIamDetector' }, { 'name': 'MailchimpDetector' }, { 'name': 'PrivateKeyDetector' }, { 'name': 'SlackDetector' }, { 'name': 'SoftlayerDetector' }, { 'name': 'SquareOAuthDetector' }, { 'name': 'StripeDetector' }, { 'name': 'TwilioKeyDetector' }, { 'name': 'EntropyKeywordCombinator', 'path': f'file://{current_dir}/plugins/entropy_keyword_combinator.py', 'limit': ENTROPY_KEYWORD_LIMIT } ] }) as settings: report = Report(self.check_type) # Implement non IaC files (including .terraform dir) files_to_scan = files or [] excluded_paths = (runner_filter.excluded_paths or []) + ignored_directories + [DEFAULT_EXTERNAL_MODULES_DIR] if root_folder: for root, d_names, f_names in os.walk(root_folder): filter_ignored_paths(root, d_names, excluded_paths) filter_ignored_paths(root, f_names, excluded_paths) for file in f_names: if file not in PROHIBITED_FILES and f".{file.split('.')[-1]}" in SUPPORTED_FILE_EXTENSIONS: files_to_scan.append(os.path.join(root, file)) logging.info(f'Secrets scanning will scan {len(files_to_scan)} files') settings.disable_filters(*['detect_secrets.filters.heuristic.is_indirect_reference']) Runner._scan_files(files_to_scan, secrets) for _, secret in iter(secrets): check_id = SECRET_TYPE_TO_ID.get(secret.type) bc_check_id = bc_integration.ckv_to_bc_id_mapping.get(check_id) if bc_integration.ckv_to_bc_id_mapping else None if not check_id: continue if runner_filter.checks and not runner_filter.should_run_check(check_id, bc_check_id): continue result: _CheckResult = {'result': CheckResult.FAILED} line_text = linecache.getline(secret.filename, secret.line_number) if line_text != "" and len(line_text.split()) > 0 and line_text.split()[0] == 'git_commit': continue result = self.search_for_suppression( check_id=check_id, bc_check_id=bc_check_id, secret=secret, runner_filter=runner_filter, ) or result report.add_resource(f'{secret.filename}:{secret.secret_hash}') report.add_record(Record( check_id=check_id, bc_check_id=bc_check_id, check_name=secret.type, check_result=result, code_block=[(secret.line_number, line_text)], file_path=f'/{os.path.relpath(secret.filename, root_folder)}', file_line_range=[secret.line_number, secret.line_number + 1], resource=secret.secret_hash, check_class=None, evaluations=None, file_abs_path=os.path.abspath(secret.filename) )) return report @staticmethod def _scan_files(files_to_scan, secrets): # implemented the scan function like secrets.scan_files results = parallel_runner.run_function( lambda f: list(scan.scan_file(os.path.join(secrets.root, f))), files_to_scan) for secrets_results in results: for secret in secrets_results: secrets[os.path.relpath(secret.filename, secrets.root)].add(secret) @staticmethod def search_for_suppression( check_id: str, bc_check_id: str, secret: PotentialSecret, runner_filter: RunnerFilter ) -> Optional[_CheckResult]: if not runner_filter.should_run_check(check_id, bc_check_id) and check_id in CHECK_ID_TO_SECRET_TYPE.keys(): return { "result": CheckResult.SKIPPED, "suppress_comment": f"Secret scan {check_id} is skipped" } # Check for suppression comment in the line before, the line of, and the line after the secret for line_number in [secret.line_number, secret.line_number - 1, secret.line_number + 1]: lt = linecache.getline(secret.filename, line_number) skip_search = re.search(COMMENT_REGEX, lt) if skip_search and (skip_search.group(2) == check_id or skip_search.group(2) == bc_check_id): return { "result": CheckResult.SKIPPED, "suppress_comment": skip_search.group(3)[1:] if skip_search.group(3) else "No comment provided" } return None
en
0.726259
# 'Secret Keyword': 'CKV_SECRET_10', # Only run scans with only these plugins. # Implement non IaC files (including .terraform dir) # implemented the scan function like secrets.scan_files # Check for suppression comment in the line before, the line of, and the line after the secret
1.497397
1
waymo_open_dataset/utils/box_utils_test.py
DKandrew/waymo-open-dataset
8
6630512
<gh_stars>1-10 # Copyright 2019 The Waymo Open Dataset 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. # ============================================================================== """Tests for waymo_open_dataset.utils.box_utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from waymo_open_dataset.utils import box_utils from waymo_open_dataset.utils import test_utils from waymo_open_dataset.utils import transform_utils class BoxUtilsTest(tf.test.TestCase): def test_is_within_box_3d(self): # Unit size boxes centered at (center, 0, 2) box, _, num_box = test_utils.generate_boxes([5.0, 19.6], 1) box = box[0, 0:num_box[0], :] point = tf.constant( [ [5.0, 0.0, 1.5], # in [20.0, 0.0, 1.6], # in [20.0, 0.0, 2.6], # not in ], dtype=tf.float32) point_in_box = box_utils.is_within_box_3d(point, box) with self.test_session() as sess: point_in_box = sess.run(point_in_box) self.assertAllEqual(point_in_box, [[True, False], [False, True], [False, False]]) def test_compute_num_points_in_box_3d(self): # Unit size boxes centered at (center, 0, 2) box, _, num_box = test_utils.generate_boxes([5.0, 5.5, 19.6, 50], 1) box = box[0, 0:num_box[0], :] point = tf.constant( [ [5.0, 0.0, 1.5], # in [5.0, 0.0, 2.5], # in [20.0, 0.0, 1.6], # in [20.0, 0.0, 2.6], # not in ], dtype=tf.float32) num_points_in_box = box_utils.compute_num_points_in_box_3d(point, box) with self.test_session() as sess: num_points_in_box = sess.run(num_points_in_box) self.assertAllEqual(num_points_in_box, [2, 2, 1, 0]) def test_transform_point_among_frames(self): p = tf.constant([[1.0, 0, 0]], dtype=tf.float32) from_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.5), tf.constant([0.0, 0.0, 2.0], dtype=tf.float32)) to_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.1), tf.constant([0.0, 0.0, 0.0], dtype=tf.float32)) p = p[tf.newaxis, tf.newaxis, tf.newaxis, ...] from_frame_pose = from_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] to_frame_pose = to_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] pp = box_utils.transform_point(p, from_frame_pose, to_frame_pose) with self.test_session(): self.assertAllClose( pp[0, 0, 0, ...].eval(), [[math.cos(math.pi * 0.4), math.sin(math.pi * 0.4), 2.0]]) def test_transform_box_among_frames(self): b = tf.constant([[1.0, 0, 0, 2.0, 2.0, 2.0, math.pi * 0.1]], dtype=tf.float32) from_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.5), tf.constant([0.0, 0.0, 1.0], dtype=tf.float32)) to_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.25), tf.constant([0.0, 0.0, 0.0], dtype=tf.float32)) b = b[tf.newaxis, tf.newaxis, tf.newaxis, ...] from_frame_pose = from_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] to_frame_pose = to_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] bb = box_utils.transform_box(b, from_frame_pose, to_frame_pose) with self.test_session(): self.assertAllClose(bb[0, 0, 0, ...].eval(), [[ math.cos(math.pi * 0.25), math.sin(math.pi * 0.25), 1.0, 2.0, 2.0, 2.0, math.pi * 0.35 ]]) if __name__ == "__main__": tf.compat.v1.disable_eager_execution() tf.test.main()
# Copyright 2019 The Waymo Open Dataset 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. # ============================================================================== """Tests for waymo_open_dataset.utils.box_utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from waymo_open_dataset.utils import box_utils from waymo_open_dataset.utils import test_utils from waymo_open_dataset.utils import transform_utils class BoxUtilsTest(tf.test.TestCase): def test_is_within_box_3d(self): # Unit size boxes centered at (center, 0, 2) box, _, num_box = test_utils.generate_boxes([5.0, 19.6], 1) box = box[0, 0:num_box[0], :] point = tf.constant( [ [5.0, 0.0, 1.5], # in [20.0, 0.0, 1.6], # in [20.0, 0.0, 2.6], # not in ], dtype=tf.float32) point_in_box = box_utils.is_within_box_3d(point, box) with self.test_session() as sess: point_in_box = sess.run(point_in_box) self.assertAllEqual(point_in_box, [[True, False], [False, True], [False, False]]) def test_compute_num_points_in_box_3d(self): # Unit size boxes centered at (center, 0, 2) box, _, num_box = test_utils.generate_boxes([5.0, 5.5, 19.6, 50], 1) box = box[0, 0:num_box[0], :] point = tf.constant( [ [5.0, 0.0, 1.5], # in [5.0, 0.0, 2.5], # in [20.0, 0.0, 1.6], # in [20.0, 0.0, 2.6], # not in ], dtype=tf.float32) num_points_in_box = box_utils.compute_num_points_in_box_3d(point, box) with self.test_session() as sess: num_points_in_box = sess.run(num_points_in_box) self.assertAllEqual(num_points_in_box, [2, 2, 1, 0]) def test_transform_point_among_frames(self): p = tf.constant([[1.0, 0, 0]], dtype=tf.float32) from_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.5), tf.constant([0.0, 0.0, 2.0], dtype=tf.float32)) to_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.1), tf.constant([0.0, 0.0, 0.0], dtype=tf.float32)) p = p[tf.newaxis, tf.newaxis, tf.newaxis, ...] from_frame_pose = from_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] to_frame_pose = to_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] pp = box_utils.transform_point(p, from_frame_pose, to_frame_pose) with self.test_session(): self.assertAllClose( pp[0, 0, 0, ...].eval(), [[math.cos(math.pi * 0.4), math.sin(math.pi * 0.4), 2.0]]) def test_transform_box_among_frames(self): b = tf.constant([[1.0, 0, 0, 2.0, 2.0, 2.0, math.pi * 0.1]], dtype=tf.float32) from_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.5), tf.constant([0.0, 0.0, 1.0], dtype=tf.float32)) to_frame_pose = transform_utils.get_transform( transform_utils.get_yaw_rotation(math.pi * 0.25), tf.constant([0.0, 0.0, 0.0], dtype=tf.float32)) b = b[tf.newaxis, tf.newaxis, tf.newaxis, ...] from_frame_pose = from_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] to_frame_pose = to_frame_pose[tf.newaxis, tf.newaxis, tf.newaxis, ...] bb = box_utils.transform_box(b, from_frame_pose, to_frame_pose) with self.test_session(): self.assertAllClose(bb[0, 0, 0, ...].eval(), [[ math.cos(math.pi * 0.25), math.sin(math.pi * 0.25), 1.0, 2.0, 2.0, 2.0, math.pi * 0.35 ]]) if __name__ == "__main__": tf.compat.v1.disable_eager_execution() tf.test.main()
en
0.809498
# Copyright 2019 The Waymo Open Dataset 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. # ============================================================================== Tests for waymo_open_dataset.utils.box_utils. # Unit size boxes centered at (center, 0, 2) # in # in # not in # Unit size boxes centered at (center, 0, 2) # in # in # in # not in
2.048139
2
FEArena/feaapi/models/play/ActiveUnit.py
Superbird11/FEArena
1
6630513
<filename>FEArena/feaapi/models/play/ActiveUnit.py from django.db import models from .._util import BaseModel from ..build.BuiltUnit import BuiltUnit from .ActiveWeapon import ActiveWeapon from .ActiveItem import ActiveItem from ..core import Skill class ActiveUnit(BaseModel): id: int = models.AutoField(primary_key=True) # demographic information should be contained in the template unit template: BuiltUnit = models.ForeignKey(BuiltUnit, on_delete=models.CASCADE) # for skill use. This should be reset at the beginning of each turn. restricted_actions: str = models.TextField(default='') # otherwise, current state information current_hp: int = models.IntegerField(default=0) mod_max_hp: int = models.IntegerField(default=0) mod_str: int = models.IntegerField(default=0) mod_mag: int = models.IntegerField(default=0, null=True, blank=True) mod_skl: int = models.IntegerField(default=0) mod_spd: int = models.IntegerField(default=0) mod_luk: int = models.IntegerField(default=0) mod_def: int = models.IntegerField(default=0) mod_res: int = models.IntegerField(default=0) mod_cha: int = models.IntegerField(default=0, null=True, blank=True) mod_mov: int = models.IntegerField(default=0) mod_con: int = models.IntegerField(default=0, null=True, blank=True) # inventory (limit should be in template unit) weapons = models.ManyToManyField(ActiveWeapon) items = models.ManyToManyField(ActiveItem) # weapon rank modifiers mod_rank_sword: int = models.IntegerField(default=0) mod_rank_lance: int = models.IntegerField(default=0) mod_rank_axe: int = models.IntegerField(default=0) mod_rank_bow: int = models.IntegerField(default=0) mod_rank_gauntlet: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_hidden: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_tome: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_fire: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_wind: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_thunder: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_dark: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_light: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_anima: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_black: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_white: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_staff: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_dragonstone: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_beast: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_special: int = models.IntegerField(default=0, null=True, blank=True) # temporary skills temp_skills = models.ManyToManyField(Skill) def to_dict(self): # extract all_classes to its own variable at once, to keep the order consistent all_classes = self.template.unit_class_history.all() return { 'id': self.id, 'nickname': self.template.nickname, 'name': self.template.unit.name, 'description': self.template.unit.description, 'sex': self.template.unit.sex, 'game': self.template.unit.game.name, 'route': self.template.unit.route.name if self.template.unit.route else None, 'class': self.template.unit_class.to_dict(), 'level': self.template.unit_level, 'all_class_levels': [pc.levels for pc in all_classes], 'current_hp': self.current_hp, 'stats': { 'level': self.template.unit_level, 'hp': { 'unit_base': self.template.unit.base_hp, 'class_base': self.template.unit_class.base_hp, 'unit_growth': self.template.unit.growth_hp, 'all_class_growths': [pc.template.growth_hp for pc in all_classes], 'boosts': self.template.boosts_hp, 'modifiers': self.mod_max_hp, 'unit_max': self.template.unit.max_hp, 'unit_max_mod': self.template.unit.mod_max_hp, 'class_max': self.template.unit_class.max_hp }, 'str': { 'unit_base': self.template.unit.base_str, 'class_base': self.template.unit_class.base_str, 'unit_growth': self.template.unit.growth_str, 'all_class_growths': [pc.template.growth_str for pc in all_classes], 'boosts': self.template.boosts_str, 'modifiers': self.mod_str, 'unit_max': self.template.unit.max_str, 'unit_max_mod': self.template.unit.mod_max_str, 'class_max': self.template.unit_class.max_str }, 'mag': { 'unit_base': self.template.unit.base_mag, 'class_base': self.template.unit_class.base_mag, 'unit_growth': self.template.unit.growth_mag, 'all_class_growths': [pc.template.growth_mag for pc in all_classes], 'boosts': self.template.boosts_mag, 'modifiers': self.mod_mag, 'unit_max': self.template.unit.max_mag, 'unit_max_mod': self.template.unit.mod_max_mag, 'class_max': self.template.unit_class.max_mag }, 'skl': { 'unit_base': self.template.unit.base_skl, 'class_base': self.template.unit_class.base_skl, 'unit_growth': self.template.unit.growth_skl, 'all_class_growths': [pc.template.growth_skl for pc in all_classes], 'boosts': self.template.boosts_skl, 'modifiers': self.mod_skl, 'unit_max': self.template.unit.max_skl, 'unit_max_mod': self.template.unit.mod_max_skl, 'class_max': self.template.unit_class.max_skl }, 'spd': { 'unit_base': self.template.unit.base_spd, 'class_base': self.template.unit_class.base_spd, 'unit_growth': self.template.unit.growth_spd, 'all_class_growths': [pc.template.growth_spd for pc in all_classes], 'boosts': self.template.boosts_spd, 'modifiers': self.mod_spd, 'unit_max': self.template.unit.max_spd, 'unit_max_mod': self.template.unit.mod_max_spd, 'class_max': self.template.unit_class.max_spd }, 'luk': { 'unit_base': self.template.unit.base_luk, 'class_base': self.template.unit_class.base_luk, 'unit_growth': self.template.unit.growth_luk, 'all_class_growths': [pc.template.growth_luk for pc in all_classes], 'boosts': self.template.boosts_luk, 'modifiers': self.mod_luk, 'unit_max': self.template.unit.max_luk, 'unit_max_mod': self.template.unit.mod_max_luk, 'class_max': self.template.unit_class.max_luk }, 'def': { 'unit_base': self.template.unit.base_def, 'class_base': self.template.unit_class.base_def, 'unit_growth': self.template.unit.growth_def, 'all_class_growths': [pc.template.growth_def for pc in all_classes], 'boosts': self.template.boosts_def, 'modifiers': self.mod_def, 'unit_max': self.template.unit.max_def, 'unit_max_mod': self.template.unit.mod_max_def, 'class_max': self.template.unit_class.max_def }, 'res': { 'unit_base': self.template.unit.base_res, 'class_base': self.template.unit_class.base_res, 'unit_growth': self.template.unit.growth_res, 'all_class_growths': [pc.template.growth_res for pc in all_classes], 'boosts': self.template.boosts_res, 'modifiers': self.mod_res, 'unit_max': self.template.unit.max_res, 'unit_max_mod': self.template.unit.mod_max_res, 'class_max': self.template.unit_class.max_res }, 'cha': { 'unit_base': self.template.unit.base_cha, 'class_base': self.template.unit_class.base_cha, 'unit_growth': self.template.unit.growth_cha, 'all_class_growths': [pc.template.growth_cha for pc in all_classes], 'boosts': self.template.boosts_cha, 'modifiers': self.mod_cha, 'unit_max': self.template.unit.max_cha, 'unit_max_mod': self.template.unit.mod_max_cha, 'class_max': self.template.unit_class.max_cha }, 'con': { 'unit_base': self.template.unit.base_con, 'class_base': self.template.unit_class.base_con, 'unit_growth': self.template.unit.growth_con, 'all_class_growths': [pc.template.growth_con for pc in all_classes], 'boosts': self.template.boosts_con, 'modifiers': self.mod_con, 'unit_max': self.template.unit.max_con, 'unit_max_mod': self.template.unit.mod_max_con, 'class_max': self.template.unit_class.max_con }, 'mov': { 'unit_base': self.template.unit.base_mov, 'class_base': self.template.unit_class.base_mov, 'unit_growth': self.template.unit.growth_mov, 'all_class_growths': [pc.template.growth_mov for pc in all_classes], 'boosts': self.template.boosts_mov, 'modifiers': self.mod_mov, 'unit_max': self.template.unit.max_mov, 'unit_max_mod': self.template.unit.mod_max_mov, 'class_max': self.template.unit_class.max_mov }, }, 'weapon_ranks': { 'sword': { 'unit_base': self.template.unit.base_rank_sword, 'class_base': self.template.unit_class.base_rank_sword, 'boosts': self.template.boost_rank_sword, 'modifiers': self.mod_rank_sword, }, 'lance': { 'unit_base': self.template.unit.base_rank_lance, 'class_base': self.template.unit_class.base_rank_lance, 'boosts': self.template.boost_rank_lance, 'modifiers': self.mod_rank_lance, }, 'axe': { 'unit_base': self.template.unit.base_rank_axe, 'class_base': self.template.unit_class.base_rank_axe, 'boosts': self.template.boost_rank_axe, 'modifiers': self.mod_rank_axe, }, 'bow': { 'unit_base': self.template.unit.base_rank_bow, 'class_base': self.template.unit_class.base_rank_bow, 'boosts': self.template.boost_rank_bow, 'modifiers': self.mod_rank_bow, }, 'gauntlet': { 'unit_base': self.template.unit.base_rank_gauntlet, 'class_base': self.template.unit_class.base_rank_gauntlet, 'boosts': self.template.boost_rank_gauntlet, 'modifiers': self.mod_rank_gauntlet, }, 'hidden': { 'unit_base': self.template.unit.base_rank_hidden, 'class_base': self.template.unit_class.base_rank_hidden, 'boosts': self.template.boost_rank_hidden, 'modifiers': self.mod_rank_hidden, }, 'tome': { 'unit_base': self.template.unit.base_rank_tome, 'class_base': self.template.unit_class.base_rank_tome, 'boosts': self.template.boost_rank_tome, 'modifiers': self.mod_rank_tome, }, 'fire': { 'unit_base': self.template.unit.base_rank_fire, 'class_base': self.template.unit_class.base_rank_fire, 'boosts': self.template.boost_rank_fire, 'modifiers': self.mod_rank_fire, }, 'wind': { 'unit_base': self.template.unit.base_rank_wind, 'class_base': self.template.unit_class.base_rank_wind, 'boosts': self.template.boost_rank_wind, 'modifiers': self.mod_rank_wind, }, 'thunder': { 'unit_base': self.template.unit.base_rank_thunder, 'class_base': self.template.unit_class.base_rank_thunder, 'boosts': self.template.boost_rank_thunder, 'modifiers': self.mod_rank_thunder, }, 'dark': { 'unit_base': self.template.unit.base_rank_dark, 'class_base': self.template.unit_class.base_rank_dark, 'boosts': self.template.boost_rank_dark, 'modifiers': self.mod_rank_dark, }, 'light': { 'unit_base': self.template.unit.base_rank_light, 'class_base': self.template.unit_class.base_rank_light, 'boosts': self.template.boost_rank_light, 'modifiers': self.mod_rank_light, }, 'anima': { 'unit_base': self.template.unit.base_rank_anima, 'class_base': self.template.unit_class.base_rank_anima, 'boosts': self.template.boost_rank_anima, 'modifiers': self.mod_rank_anima, }, 'black': { 'unit_base': self.template.unit.base_rank_black, 'class_base': self.template.unit_class.base_rank_black, 'boosts': self.template.boost_rank_black, 'modifiers': self.mod_rank_black, }, 'white': { 'unit_base': self.template.unit.base_rank_white, 'class_base': self.template.unit_class.base_rank_white, 'boosts': self.template.boost_rank_white, 'modifiers': self.mod_rank_white, }, 'staff': { 'unit_base': self.template.unit.base_rank_staff, 'class_base': self.template.unit_class.base_rank_staff, 'boosts': self.template.boost_rank_staff, 'modifiers': self.mod_rank_staff, }, 'dragonstone': { 'unit_base': self.template.unit.base_rank_dragonstone, 'class_base': self.template.unit_class.base_rank_dragonstone, 'boosts': self.template.boost_rank_dragonstone, 'modifiers': self.mod_rank_dragonstone, }, 'beast': { 'unit_base': self.template.unit.base_rank_beast, 'class_base': self.template.unit_class.base_rank_beast, 'boosts': self.template.boost_rank_beast, 'modifiers': self.mod_rank_beast, }, 'special': { 'unit_base': self.template.unit.base_rank_special, 'class_base': self.template.unit_class.base_rank_special, 'boosts': self.template.boost_rank_special, 'modifiers': self.mod_rank_special, }, }, 'inventory': { 'weapons': [weapon.to_dict() for weapon in self.weapons.all()], 'items': [item.to_dict() for item in self.items.all()], }, 'personal_skills': [skill.to_dict() for skill in self.template.unit.personal_skills.all()], 'extra_skills': [skill.to_dict() for skill in self.template.extra_skills.all()], 'temporary_skills': [skill.to_dict() for skill in self.temp_skills.all()] }
<filename>FEArena/feaapi/models/play/ActiveUnit.py from django.db import models from .._util import BaseModel from ..build.BuiltUnit import BuiltUnit from .ActiveWeapon import ActiveWeapon from .ActiveItem import ActiveItem from ..core import Skill class ActiveUnit(BaseModel): id: int = models.AutoField(primary_key=True) # demographic information should be contained in the template unit template: BuiltUnit = models.ForeignKey(BuiltUnit, on_delete=models.CASCADE) # for skill use. This should be reset at the beginning of each turn. restricted_actions: str = models.TextField(default='') # otherwise, current state information current_hp: int = models.IntegerField(default=0) mod_max_hp: int = models.IntegerField(default=0) mod_str: int = models.IntegerField(default=0) mod_mag: int = models.IntegerField(default=0, null=True, blank=True) mod_skl: int = models.IntegerField(default=0) mod_spd: int = models.IntegerField(default=0) mod_luk: int = models.IntegerField(default=0) mod_def: int = models.IntegerField(default=0) mod_res: int = models.IntegerField(default=0) mod_cha: int = models.IntegerField(default=0, null=True, blank=True) mod_mov: int = models.IntegerField(default=0) mod_con: int = models.IntegerField(default=0, null=True, blank=True) # inventory (limit should be in template unit) weapons = models.ManyToManyField(ActiveWeapon) items = models.ManyToManyField(ActiveItem) # weapon rank modifiers mod_rank_sword: int = models.IntegerField(default=0) mod_rank_lance: int = models.IntegerField(default=0) mod_rank_axe: int = models.IntegerField(default=0) mod_rank_bow: int = models.IntegerField(default=0) mod_rank_gauntlet: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_hidden: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_tome: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_fire: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_wind: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_thunder: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_dark: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_light: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_anima: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_black: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_white: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_staff: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_dragonstone: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_beast: int = models.IntegerField(default=0, null=True, blank=True) mod_rank_special: int = models.IntegerField(default=0, null=True, blank=True) # temporary skills temp_skills = models.ManyToManyField(Skill) def to_dict(self): # extract all_classes to its own variable at once, to keep the order consistent all_classes = self.template.unit_class_history.all() return { 'id': self.id, 'nickname': self.template.nickname, 'name': self.template.unit.name, 'description': self.template.unit.description, 'sex': self.template.unit.sex, 'game': self.template.unit.game.name, 'route': self.template.unit.route.name if self.template.unit.route else None, 'class': self.template.unit_class.to_dict(), 'level': self.template.unit_level, 'all_class_levels': [pc.levels for pc in all_classes], 'current_hp': self.current_hp, 'stats': { 'level': self.template.unit_level, 'hp': { 'unit_base': self.template.unit.base_hp, 'class_base': self.template.unit_class.base_hp, 'unit_growth': self.template.unit.growth_hp, 'all_class_growths': [pc.template.growth_hp for pc in all_classes], 'boosts': self.template.boosts_hp, 'modifiers': self.mod_max_hp, 'unit_max': self.template.unit.max_hp, 'unit_max_mod': self.template.unit.mod_max_hp, 'class_max': self.template.unit_class.max_hp }, 'str': { 'unit_base': self.template.unit.base_str, 'class_base': self.template.unit_class.base_str, 'unit_growth': self.template.unit.growth_str, 'all_class_growths': [pc.template.growth_str for pc in all_classes], 'boosts': self.template.boosts_str, 'modifiers': self.mod_str, 'unit_max': self.template.unit.max_str, 'unit_max_mod': self.template.unit.mod_max_str, 'class_max': self.template.unit_class.max_str }, 'mag': { 'unit_base': self.template.unit.base_mag, 'class_base': self.template.unit_class.base_mag, 'unit_growth': self.template.unit.growth_mag, 'all_class_growths': [pc.template.growth_mag for pc in all_classes], 'boosts': self.template.boosts_mag, 'modifiers': self.mod_mag, 'unit_max': self.template.unit.max_mag, 'unit_max_mod': self.template.unit.mod_max_mag, 'class_max': self.template.unit_class.max_mag }, 'skl': { 'unit_base': self.template.unit.base_skl, 'class_base': self.template.unit_class.base_skl, 'unit_growth': self.template.unit.growth_skl, 'all_class_growths': [pc.template.growth_skl for pc in all_classes], 'boosts': self.template.boosts_skl, 'modifiers': self.mod_skl, 'unit_max': self.template.unit.max_skl, 'unit_max_mod': self.template.unit.mod_max_skl, 'class_max': self.template.unit_class.max_skl }, 'spd': { 'unit_base': self.template.unit.base_spd, 'class_base': self.template.unit_class.base_spd, 'unit_growth': self.template.unit.growth_spd, 'all_class_growths': [pc.template.growth_spd for pc in all_classes], 'boosts': self.template.boosts_spd, 'modifiers': self.mod_spd, 'unit_max': self.template.unit.max_spd, 'unit_max_mod': self.template.unit.mod_max_spd, 'class_max': self.template.unit_class.max_spd }, 'luk': { 'unit_base': self.template.unit.base_luk, 'class_base': self.template.unit_class.base_luk, 'unit_growth': self.template.unit.growth_luk, 'all_class_growths': [pc.template.growth_luk for pc in all_classes], 'boosts': self.template.boosts_luk, 'modifiers': self.mod_luk, 'unit_max': self.template.unit.max_luk, 'unit_max_mod': self.template.unit.mod_max_luk, 'class_max': self.template.unit_class.max_luk }, 'def': { 'unit_base': self.template.unit.base_def, 'class_base': self.template.unit_class.base_def, 'unit_growth': self.template.unit.growth_def, 'all_class_growths': [pc.template.growth_def for pc in all_classes], 'boosts': self.template.boosts_def, 'modifiers': self.mod_def, 'unit_max': self.template.unit.max_def, 'unit_max_mod': self.template.unit.mod_max_def, 'class_max': self.template.unit_class.max_def }, 'res': { 'unit_base': self.template.unit.base_res, 'class_base': self.template.unit_class.base_res, 'unit_growth': self.template.unit.growth_res, 'all_class_growths': [pc.template.growth_res for pc in all_classes], 'boosts': self.template.boosts_res, 'modifiers': self.mod_res, 'unit_max': self.template.unit.max_res, 'unit_max_mod': self.template.unit.mod_max_res, 'class_max': self.template.unit_class.max_res }, 'cha': { 'unit_base': self.template.unit.base_cha, 'class_base': self.template.unit_class.base_cha, 'unit_growth': self.template.unit.growth_cha, 'all_class_growths': [pc.template.growth_cha for pc in all_classes], 'boosts': self.template.boosts_cha, 'modifiers': self.mod_cha, 'unit_max': self.template.unit.max_cha, 'unit_max_mod': self.template.unit.mod_max_cha, 'class_max': self.template.unit_class.max_cha }, 'con': { 'unit_base': self.template.unit.base_con, 'class_base': self.template.unit_class.base_con, 'unit_growth': self.template.unit.growth_con, 'all_class_growths': [pc.template.growth_con for pc in all_classes], 'boosts': self.template.boosts_con, 'modifiers': self.mod_con, 'unit_max': self.template.unit.max_con, 'unit_max_mod': self.template.unit.mod_max_con, 'class_max': self.template.unit_class.max_con }, 'mov': { 'unit_base': self.template.unit.base_mov, 'class_base': self.template.unit_class.base_mov, 'unit_growth': self.template.unit.growth_mov, 'all_class_growths': [pc.template.growth_mov for pc in all_classes], 'boosts': self.template.boosts_mov, 'modifiers': self.mod_mov, 'unit_max': self.template.unit.max_mov, 'unit_max_mod': self.template.unit.mod_max_mov, 'class_max': self.template.unit_class.max_mov }, }, 'weapon_ranks': { 'sword': { 'unit_base': self.template.unit.base_rank_sword, 'class_base': self.template.unit_class.base_rank_sword, 'boosts': self.template.boost_rank_sword, 'modifiers': self.mod_rank_sword, }, 'lance': { 'unit_base': self.template.unit.base_rank_lance, 'class_base': self.template.unit_class.base_rank_lance, 'boosts': self.template.boost_rank_lance, 'modifiers': self.mod_rank_lance, }, 'axe': { 'unit_base': self.template.unit.base_rank_axe, 'class_base': self.template.unit_class.base_rank_axe, 'boosts': self.template.boost_rank_axe, 'modifiers': self.mod_rank_axe, }, 'bow': { 'unit_base': self.template.unit.base_rank_bow, 'class_base': self.template.unit_class.base_rank_bow, 'boosts': self.template.boost_rank_bow, 'modifiers': self.mod_rank_bow, }, 'gauntlet': { 'unit_base': self.template.unit.base_rank_gauntlet, 'class_base': self.template.unit_class.base_rank_gauntlet, 'boosts': self.template.boost_rank_gauntlet, 'modifiers': self.mod_rank_gauntlet, }, 'hidden': { 'unit_base': self.template.unit.base_rank_hidden, 'class_base': self.template.unit_class.base_rank_hidden, 'boosts': self.template.boost_rank_hidden, 'modifiers': self.mod_rank_hidden, }, 'tome': { 'unit_base': self.template.unit.base_rank_tome, 'class_base': self.template.unit_class.base_rank_tome, 'boosts': self.template.boost_rank_tome, 'modifiers': self.mod_rank_tome, }, 'fire': { 'unit_base': self.template.unit.base_rank_fire, 'class_base': self.template.unit_class.base_rank_fire, 'boosts': self.template.boost_rank_fire, 'modifiers': self.mod_rank_fire, }, 'wind': { 'unit_base': self.template.unit.base_rank_wind, 'class_base': self.template.unit_class.base_rank_wind, 'boosts': self.template.boost_rank_wind, 'modifiers': self.mod_rank_wind, }, 'thunder': { 'unit_base': self.template.unit.base_rank_thunder, 'class_base': self.template.unit_class.base_rank_thunder, 'boosts': self.template.boost_rank_thunder, 'modifiers': self.mod_rank_thunder, }, 'dark': { 'unit_base': self.template.unit.base_rank_dark, 'class_base': self.template.unit_class.base_rank_dark, 'boosts': self.template.boost_rank_dark, 'modifiers': self.mod_rank_dark, }, 'light': { 'unit_base': self.template.unit.base_rank_light, 'class_base': self.template.unit_class.base_rank_light, 'boosts': self.template.boost_rank_light, 'modifiers': self.mod_rank_light, }, 'anima': { 'unit_base': self.template.unit.base_rank_anima, 'class_base': self.template.unit_class.base_rank_anima, 'boosts': self.template.boost_rank_anima, 'modifiers': self.mod_rank_anima, }, 'black': { 'unit_base': self.template.unit.base_rank_black, 'class_base': self.template.unit_class.base_rank_black, 'boosts': self.template.boost_rank_black, 'modifiers': self.mod_rank_black, }, 'white': { 'unit_base': self.template.unit.base_rank_white, 'class_base': self.template.unit_class.base_rank_white, 'boosts': self.template.boost_rank_white, 'modifiers': self.mod_rank_white, }, 'staff': { 'unit_base': self.template.unit.base_rank_staff, 'class_base': self.template.unit_class.base_rank_staff, 'boosts': self.template.boost_rank_staff, 'modifiers': self.mod_rank_staff, }, 'dragonstone': { 'unit_base': self.template.unit.base_rank_dragonstone, 'class_base': self.template.unit_class.base_rank_dragonstone, 'boosts': self.template.boost_rank_dragonstone, 'modifiers': self.mod_rank_dragonstone, }, 'beast': { 'unit_base': self.template.unit.base_rank_beast, 'class_base': self.template.unit_class.base_rank_beast, 'boosts': self.template.boost_rank_beast, 'modifiers': self.mod_rank_beast, }, 'special': { 'unit_base': self.template.unit.base_rank_special, 'class_base': self.template.unit_class.base_rank_special, 'boosts': self.template.boost_rank_special, 'modifiers': self.mod_rank_special, }, }, 'inventory': { 'weapons': [weapon.to_dict() for weapon in self.weapons.all()], 'items': [item.to_dict() for item in self.items.all()], }, 'personal_skills': [skill.to_dict() for skill in self.template.unit.personal_skills.all()], 'extra_skills': [skill.to_dict() for skill in self.template.extra_skills.all()], 'temporary_skills': [skill.to_dict() for skill in self.temp_skills.all()] }
en
0.790269
# demographic information should be contained in the template unit # for skill use. This should be reset at the beginning of each turn. # otherwise, current state information # inventory (limit should be in template unit) # weapon rank modifiers # temporary skills # extract all_classes to its own variable at once, to keep the order consistent
2.130676
2
src/cryptography/hazmat/primitives/serialization/ssh.py
Capfly/cryptography
1
6630514
<reponame>Capfly/cryptography<gh_stars>1-10 # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import binascii import os import re import typing from base64 import encodebytes as _base64_encode from cryptography import utils from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed25519, rsa from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.serialization import ( Encoding, NoEncryption, PrivateFormat, PublicFormat, ) try: from bcrypt import kdf as _bcrypt_kdf _bcrypt_supported = True except ImportError: _bcrypt_supported = False def _bcrypt_kdf( password: <PASSWORD>, salt: bytes, desired_key_bytes: int, rounds: int, ignore_few_rounds: bool = False, ) -> bytes: raise UnsupportedAlgorithm("Need bcrypt module") _SSH_ED25519 = b"ssh-ed25519" _SSH_RSA = b"ssh-rsa" _SSH_DSA = b"ssh-dss" _ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" _ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" _ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" _CERT_SUFFIX = b"-<EMAIL>" _SSH_PUBKEY_RC = re.compile(br"\A(\S+)[ \t]+(\S+)") _SK_MAGIC = b"openssh-key-v1\0" _SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" _SK_END = b"-----END OPENSSH PRIVATE KEY-----" _BCRYPT = b"bcrypt" _NONE = b"none" _DEFAULT_CIPHER = b"aes256-ctr" _DEFAULT_ROUNDS = 16 _MAX_PASSWORD = 72 # re is only way to work on bytes-like data _PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) # padding for max blocksize _PADDING = memoryview(bytearray(range(1, 1 + 16))) # ciphers that are actually used in key wrapping _SSH_CIPHERS: typing.Dict[ bytes, typing.Tuple[ typing.Type[algorithms.AES], int, typing.Union[typing.Type[modes.CTR], typing.Type[modes.CBC]], int, ], ] = { b"aes256-ctr": (algorithms.AES, 32, modes.CTR, 16), b"aes256-cbc": (algorithms.AES, 32, modes.CBC, 16), } # map local curve name to key type _ECDSA_KEY_TYPE = { "secp256r1": _ECDSA_NISTP256, "secp384r1": _ECDSA_NISTP384, "secp521r1": _ECDSA_NISTP521, } def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: """Return SSH key_type and curve_name for private key.""" curve = public_key.curve if curve.name not in _ECDSA_KEY_TYPE: raise ValueError( "Unsupported curve for ssh private key: %r" % curve.name ) return _ECDSA_KEY_TYPE[curve.name] def _ssh_pem_encode( data: bytes, prefix: bytes = _SK_START + b"\n", suffix: bytes = _SK_END + b"\n", ) -> bytes: return b"".join([prefix, _base64_encode(data), suffix]) def _check_block_size(data: bytes, block_len: int) -> None: """Require data to be full blocks""" if not data or len(data) % block_len != 0: raise ValueError("Corrupt data: missing padding") def _check_empty(data: bytes) -> None: """All data should have been parsed.""" if data: raise ValueError("Corrupt data: unparsed data") def _init_cipher( ciphername: bytes, password: typing.Optional[bytes], salt: bytes, rounds: int, ) -> Cipher[typing.Union[modes.CBC, modes.CTR]]: """Generate key + iv and return cipher.""" if not password: raise ValueError("Key is password-protected.") algo, key_len, mode, iv_len = _SSH_CIPHERS[ciphername] seed = _bcrypt_kdf(password, salt, key_len + iv_len, rounds, True) return Cipher(algo(seed[:key_len]), mode(seed[key_len:])) def _get_u32(data: memoryview) -> typing.Tuple[int, memoryview]: """Uint32""" if len(data) < 4: raise ValueError("Invalid data") return int.from_bytes(data[:4], byteorder="big"), data[4:] def _get_u64(data: memoryview) -> typing.Tuple[int, memoryview]: """Uint64""" if len(data) < 8: raise ValueError("Invalid data") return int.from_bytes(data[:8], byteorder="big"), data[8:] def _get_sshstr(data: memoryview) -> typing.Tuple[memoryview, memoryview]: """Bytes with u32 length prefix""" n, data = _get_u32(data) if n > len(data): raise ValueError("Invalid data") return data[:n], data[n:] def _get_mpint(data: memoryview) -> typing.Tuple[int, memoryview]: """Big integer.""" val, data = _get_sshstr(data) if val and val[0] > 0x7F: raise ValueError("Invalid data") return int.from_bytes(val, "big"), data def _to_mpint(val: int) -> bytes: """Storage format for signed bigint.""" if val < 0: raise ValueError("negative mpint not allowed") if not val: return b"" nbytes = (val.bit_length() + 8) // 8 return utils.int_to_bytes(val, nbytes) class _FragList(object): """Build recursive structure without data copy.""" flist: typing.List[bytes] def __init__(self, init: typing.List[bytes] = None) -> None: self.flist = [] if init: self.flist.extend(init) def put_raw(self, val: bytes) -> None: """Add plain bytes""" self.flist.append(val) def put_u32(self, val: int) -> None: """Big-endian uint32""" self.flist.append(val.to_bytes(length=4, byteorder="big")) def put_sshstr(self, val: typing.Union[bytes, "_FragList"]) -> None: """Bytes prefixed with u32 length""" if isinstance(val, (bytes, memoryview, bytearray)): self.put_u32(len(val)) self.flist.append(val) else: self.put_u32(val.size()) self.flist.extend(val.flist) def put_mpint(self, val: int) -> None: """Big-endian bigint prefixed with u32 length""" self.put_sshstr(_to_mpint(val)) def size(self) -> int: """Current number of bytes""" return sum(map(len, self.flist)) def render(self, dstbuf: memoryview, pos: int = 0) -> int: """Write into bytearray""" for frag in self.flist: flen = len(frag) start, pos = pos, pos + flen dstbuf[start:pos] = frag return pos def tobytes(self) -> bytes: """Return as bytes""" buf = memoryview(bytearray(self.size())) self.render(buf) return buf.tobytes() class _SSHFormatRSA(object): """Format for RSA keys. Public: mpint e, n Private: mpint n, e, d, iqmp, p, q """ def get_public(self, data: memoryview): """RSA public fields""" e, data = _get_mpint(data) n, data = _get_mpint(data) return (e, n), data def load_public( self, data: memoryview ) -> typing.Tuple[rsa.RSAPublicKey, memoryview]: """Make RSA public key from data.""" (e, n), data = self.get_public(data) public_numbers = rsa.RSAPublicNumbers(e, n) public_key = public_numbers.public_key() return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[rsa.RSAPrivateKey, memoryview]: """Make RSA private key from data.""" n, data = _get_mpint(data) e, data = _get_mpint(data) d, data = _get_mpint(data) iqmp, data = _get_mpint(data) p, data = _get_mpint(data) q, data = _get_mpint(data) if (e, n) != pubfields: raise ValueError("Corrupt data: rsa field mismatch") dmp1 = rsa.rsa_crt_dmp1(d, p) dmq1 = rsa.rsa_crt_dmq1(d, q) public_numbers = rsa.RSAPublicNumbers(e, n) private_numbers = rsa.RSAPrivateNumbers( p, q, d, dmp1, dmq1, iqmp, public_numbers ) private_key = private_numbers.private_key() return private_key, data def encode_public( self, public_key: rsa.RSAPublicKey, f_pub: _FragList ) -> None: """Write RSA public key""" pubn = public_key.public_numbers() f_pub.put_mpint(pubn.e) f_pub.put_mpint(pubn.n) def encode_private( self, private_key: rsa.RSAPrivateKey, f_priv: _FragList ) -> None: """Write RSA private key""" private_numbers = private_key.private_numbers() public_numbers = private_numbers.public_numbers f_priv.put_mpint(public_numbers.n) f_priv.put_mpint(public_numbers.e) f_priv.put_mpint(private_numbers.d) f_priv.put_mpint(private_numbers.iqmp) f_priv.put_mpint(private_numbers.p) f_priv.put_mpint(private_numbers.q) class _SSHFormatDSA(object): """Format for DSA keys. Public: mpint p, q, g, y Private: mpint p, q, g, y, x """ def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """DSA public fields""" p, data = _get_mpint(data) q, data = _get_mpint(data) g, data = _get_mpint(data) y, data = _get_mpint(data) return (p, q, g, y), data def load_public( self, data: memoryview ) -> typing.Tuple[dsa.DSAPublicKey, memoryview]: """Make DSA public key from data.""" (p, q, g, y), data = self.get_public(data) parameter_numbers = dsa.DSAParameterNumbers(p, q, g) public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) self._validate(public_numbers) public_key = public_numbers.public_key() return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[dsa.DSAPrivateKey, memoryview]: """Make DSA private key from data.""" (p, q, g, y), data = self.get_public(data) x, data = _get_mpint(data) if (p, q, g, y) != pubfields: raise ValueError("Corrupt data: dsa field mismatch") parameter_numbers = dsa.DSAParameterNumbers(p, q, g) public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) self._validate(public_numbers) private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) private_key = private_numbers.private_key() return private_key, data def encode_public( self, public_key: dsa.DSAPublicKey, f_pub: _FragList ) -> None: """Write DSA public key""" public_numbers = public_key.public_numbers() parameter_numbers = public_numbers.parameter_numbers self._validate(public_numbers) f_pub.put_mpint(parameter_numbers.p) f_pub.put_mpint(parameter_numbers.q) f_pub.put_mpint(parameter_numbers.g) f_pub.put_mpint(public_numbers.y) def encode_private( self, private_key: dsa.DSAPrivateKey, f_priv: _FragList ) -> None: """Write DSA private key""" self.encode_public(private_key.public_key(), f_priv) f_priv.put_mpint(private_key.private_numbers().x) def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: parameter_numbers = public_numbers.parameter_numbers if parameter_numbers.p.bit_length() != 1024: raise ValueError("SSH supports only 1024 bit DSA keys") class _SSHFormatECDSA(object): """Format for ECDSA keys. Public: str curve bytes point Private: str curve bytes point mpint secret """ def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): self.ssh_curve_name = ssh_curve_name self.curve = curve def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """ECDSA public fields""" curve, data = _get_sshstr(data) point, data = _get_sshstr(data) if curve != self.ssh_curve_name: raise ValueError("Curve name mismatch") if point[0] != 4: raise NotImplementedError("Need uncompressed point") return (curve, point), data def load_public( self, data: memoryview ) -> typing.Tuple[ec.EllipticCurvePublicKey, memoryview]: """Make ECDSA public key from data.""" (curve_name, point), data = self.get_public(data) public_key = ec.EllipticCurvePublicKey.from_encoded_point( self.curve, point.tobytes() ) return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[ec.EllipticCurvePrivateKey, memoryview]: """Make ECDSA private key from data.""" (curve_name, point), data = self.get_public(data) secret, data = _get_mpint(data) if (curve_name, point) != pubfields: raise ValueError("Corrupt data: ecdsa field mismatch") private_key = ec.derive_private_key(secret, self.curve) return private_key, data def encode_public( self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList ) -> None: """Write ECDSA public key""" point = public_key.public_bytes( Encoding.X962, PublicFormat.UncompressedPoint ) f_pub.put_sshstr(self.ssh_curve_name) f_pub.put_sshstr(point) def encode_private( self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList ) -> None: """Write ECDSA private key""" public_key = private_key.public_key() private_numbers = private_key.private_numbers() self.encode_public(public_key, f_priv) f_priv.put_mpint(private_numbers.private_value) class _SSHFormatEd25519(object): """Format for Ed25519 keys. Public: bytes point Private: bytes point bytes secret_and_point """ def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """Ed25519 public fields""" point, data = _get_sshstr(data) return (point,), data def load_public( self, data: memoryview ) -> typing.Tuple[ed25519.Ed25519PublicKey, memoryview]: """Make Ed25519 public key from data.""" (point,), data = self.get_public(data) public_key = ed25519.Ed25519PublicKey.from_public_bytes( point.tobytes() ) return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[ed25519.Ed25519PrivateKey, memoryview]: """Make Ed25519 private key from data.""" (point,), data = self.get_public(data) keypair, data = _get_sshstr(data) secret = keypair[:32] point2 = keypair[32:] if point != point2 or (point,) != pubfields: raise ValueError("Corrupt data: ed25519 field mismatch") private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) return private_key, data def encode_public( self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList ) -> None: """Write Ed25519 public key""" raw_public_key = public_key.public_bytes( Encoding.Raw, PublicFormat.Raw ) f_pub.put_sshstr(raw_public_key) def encode_private( self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList ) -> None: """Write Ed25519 private key""" public_key = private_key.public_key() raw_private_key = private_key.private_bytes( Encoding.Raw, PrivateFormat.Raw, NoEncryption() ) raw_public_key = public_key.public_bytes( Encoding.Raw, PublicFormat.Raw ) f_keypair = _FragList([raw_private_key, raw_public_key]) self.encode_public(public_key, f_priv) f_priv.put_sshstr(f_keypair) _KEY_FORMATS = { _SSH_RSA: _SSHFormatRSA(), _SSH_DSA: _SSHFormatDSA(), _SSH_ED25519: _SSHFormatEd25519(), _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), } def _lookup_kformat(key_type: bytes): """Return valid format or throw error""" if not isinstance(key_type, bytes): key_type = memoryview(key_type).tobytes() if key_type in _KEY_FORMATS: return _KEY_FORMATS[key_type] raise UnsupportedAlgorithm("Unsupported key type: %r" % key_type) _SSH_PRIVATE_KEY_TYPES = typing.Union[ ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey, dsa.DSAPrivateKey, ed25519.Ed25519PrivateKey, ] def load_ssh_private_key( data: bytes, password: typing.Optional[bytes], backend: typing.Any = None, ) -> _SSH_PRIVATE_KEY_TYPES: """Load private key from OpenSSH custom encoding.""" utils._check_byteslike("data", data) if password is not None: utils._check_bytes("password", password) m = _PEM_RC.search(data) if not m: raise ValueError("Not OpenSSH private key format") p1 = m.start(1) p2 = m.end(1) data = binascii.a2b_base64(memoryview(data)[p1:p2]) if not data.startswith(_SK_MAGIC): raise ValueError("Not OpenSSH private key format") data = memoryview(data)[len(_SK_MAGIC) :] # parse header ciphername, data = _get_sshstr(data) kdfname, data = _get_sshstr(data) kdfoptions, data = _get_sshstr(data) nkeys, data = _get_u32(data) if nkeys != 1: raise ValueError("Only one key supported") # load public key data pubdata, data = _get_sshstr(data) pub_key_type, pubdata = _get_sshstr(pubdata) kformat = _lookup_kformat(pub_key_type) pubfields, pubdata = kformat.get_public(pubdata) _check_empty(pubdata) # load secret data edata, data = _get_sshstr(data) _check_empty(data) if (ciphername, kdfname) != (_NONE, _NONE): ciphername_bytes = ciphername.tobytes() if ciphername_bytes not in _SSH_CIPHERS: raise UnsupportedAlgorithm( "Unsupported cipher: %r" % ciphername_bytes ) if kdfname != _BCRYPT: raise UnsupportedAlgorithm("Unsupported KDF: %r" % kdfname) blklen = _SSH_CIPHERS[ciphername_bytes][3] _check_block_size(edata, blklen) salt, kbuf = _get_sshstr(kdfoptions) rounds, kbuf = _get_u32(kbuf) _check_empty(kbuf) ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) edata = memoryview(ciph.decryptor().update(edata)) else: blklen = 8 _check_block_size(edata, blklen) ck1, edata = _get_u32(edata) ck2, edata = _get_u32(edata) if ck1 != ck2: raise ValueError("Corrupt data: broken checksum") # load per-key struct key_type, edata = _get_sshstr(edata) if key_type != pub_key_type: raise ValueError("Corrupt data: key type mismatch") private_key, edata = kformat.load_private(edata, pubfields) comment, edata = _get_sshstr(edata) # yes, SSH does padding check *after* all other parsing is done. # need to follow as it writes zero-byte padding too. if edata != _PADDING[: len(edata)]: raise ValueError("Corrupt data: invalid padding") return private_key def serialize_ssh_private_key( private_key: _SSH_PRIVATE_KEY_TYPES, password: typing.Optional[bytes] = None, ) -> bytes: """Serialize private key with OpenSSH custom encoding.""" if password is not None: utils._check_bytes("password", password) if password and len(password) > _MAX_PASSWORD: raise ValueError( "Passwords longer than 72 bytes are not supported by " "OpenSSH private key format" ) if isinstance(private_key, ec.EllipticCurvePrivateKey): key_type = _ecdsa_key_type(private_key.public_key()) elif isinstance(private_key, rsa.RSAPrivateKey): key_type = _SSH_RSA elif isinstance(private_key, dsa.DSAPrivateKey): key_type = _SSH_DSA elif isinstance(private_key, ed25519.Ed25519PrivateKey): key_type = _SSH_ED25519 else: raise ValueError("Unsupported key type") kformat = _lookup_kformat(key_type) # setup parameters f_kdfoptions = _FragList() if password: ciphername = _DEFAULT_CIPHER blklen = _SSH_CIPHERS[ciphername][3] kdfname = _BCRYPT rounds = _DEFAULT_ROUNDS salt = os.urandom(16) f_kdfoptions.put_sshstr(salt) f_kdfoptions.put_u32(rounds) ciph = _init_cipher(ciphername, password, salt, rounds) else: ciphername = kdfname = _NONE blklen = 8 ciph = None nkeys = 1 checkval = os.urandom(4) comment = b"" # encode public and private parts together f_public_key = _FragList() f_public_key.put_sshstr(key_type) kformat.encode_public(private_key.public_key(), f_public_key) f_secrets = _FragList([checkval, checkval]) f_secrets.put_sshstr(key_type) kformat.encode_private(private_key, f_secrets) f_secrets.put_sshstr(comment) f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) # top-level structure f_main = _FragList() f_main.put_raw(_SK_MAGIC) f_main.put_sshstr(ciphername) f_main.put_sshstr(kdfname) f_main.put_sshstr(f_kdfoptions) f_main.put_u32(nkeys) f_main.put_sshstr(f_public_key) f_main.put_sshstr(f_secrets) # copy result info bytearray slen = f_secrets.size() mlen = f_main.size() buf = memoryview(bytearray(mlen + blklen)) f_main.render(buf) ofs = mlen - slen # encrypt in-place if ciph is not None: ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) txt = _ssh_pem_encode(buf[:mlen]) buf[ofs:mlen] = bytearray(slen) return txt _SSH_PUBLIC_KEY_TYPES = typing.Union[ ec.EllipticCurvePublicKey, rsa.RSAPublicKey, dsa.DSAPublicKey, ed25519.Ed25519PublicKey, ] def load_ssh_public_key( data: bytes, backend: typing.Any = None ) -> _SSH_PUBLIC_KEY_TYPES: """Load public key from OpenSSH one-line format.""" utils._check_byteslike("data", data) m = _SSH_PUBKEY_RC.match(data) if not m: raise ValueError("Invalid line format") key_type = orig_key_type = m.group(1) key_body = m.group(2) with_cert = False if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]: with_cert = True key_type = key_type[: -len(_CERT_SUFFIX)] kformat = _lookup_kformat(key_type) try: rest = memoryview(binascii.a2b_base64(key_body)) except (TypeError, binascii.Error): raise ValueError("Invalid key format") inner_key_type, rest = _get_sshstr(rest) if inner_key_type != orig_key_type: raise ValueError("Invalid key format") if with_cert: nonce, rest = _get_sshstr(rest) public_key, rest = kformat.load_public(rest) if with_cert: serial, rest = _get_u64(rest) cctype, rest = _get_u32(rest) key_id, rest = _get_sshstr(rest) principals, rest = _get_sshstr(rest) valid_after, rest = _get_u64(rest) valid_before, rest = _get_u64(rest) crit_options, rest = _get_sshstr(rest) extensions, rest = _get_sshstr(rest) reserved, rest = _get_sshstr(rest) sig_key, rest = _get_sshstr(rest) signature, rest = _get_sshstr(rest) _check_empty(rest) return public_key def serialize_ssh_public_key(public_key: _SSH_PUBLIC_KEY_TYPES) -> bytes: """One-line public key format for OpenSSH""" if isinstance(public_key, ec.EllipticCurvePublicKey): key_type = _ecdsa_key_type(public_key) elif isinstance(public_key, rsa.RSAPublicKey): key_type = _SSH_RSA elif isinstance(public_key, dsa.DSAPublicKey): key_type = _SSH_DSA elif isinstance(public_key, ed25519.Ed25519PublicKey): key_type = _SSH_ED25519 else: raise ValueError("Unsupported key type") kformat = _lookup_kformat(key_type) f_pub = _FragList() f_pub.put_sshstr(key_type) kformat.encode_public(public_key, f_pub) pub = binascii.b2a_base64(f_pub.tobytes()).strip() return b"".join([key_type, b" ", pub])
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import binascii import os import re import typing from base64 import encodebytes as _base64_encode from cryptography import utils from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed25519, rsa from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.serialization import ( Encoding, NoEncryption, PrivateFormat, PublicFormat, ) try: from bcrypt import kdf as _bcrypt_kdf _bcrypt_supported = True except ImportError: _bcrypt_supported = False def _bcrypt_kdf( password: <PASSWORD>, salt: bytes, desired_key_bytes: int, rounds: int, ignore_few_rounds: bool = False, ) -> bytes: raise UnsupportedAlgorithm("Need bcrypt module") _SSH_ED25519 = b"ssh-ed25519" _SSH_RSA = b"ssh-rsa" _SSH_DSA = b"ssh-dss" _ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" _ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" _ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" _CERT_SUFFIX = b"-<EMAIL>" _SSH_PUBKEY_RC = re.compile(br"\A(\S+)[ \t]+(\S+)") _SK_MAGIC = b"openssh-key-v1\0" _SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" _SK_END = b"-----END OPENSSH PRIVATE KEY-----" _BCRYPT = b"bcrypt" _NONE = b"none" _DEFAULT_CIPHER = b"aes256-ctr" _DEFAULT_ROUNDS = 16 _MAX_PASSWORD = 72 # re is only way to work on bytes-like data _PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) # padding for max blocksize _PADDING = memoryview(bytearray(range(1, 1 + 16))) # ciphers that are actually used in key wrapping _SSH_CIPHERS: typing.Dict[ bytes, typing.Tuple[ typing.Type[algorithms.AES], int, typing.Union[typing.Type[modes.CTR], typing.Type[modes.CBC]], int, ], ] = { b"aes256-ctr": (algorithms.AES, 32, modes.CTR, 16), b"aes256-cbc": (algorithms.AES, 32, modes.CBC, 16), } # map local curve name to key type _ECDSA_KEY_TYPE = { "secp256r1": _ECDSA_NISTP256, "secp384r1": _ECDSA_NISTP384, "secp521r1": _ECDSA_NISTP521, } def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: """Return SSH key_type and curve_name for private key.""" curve = public_key.curve if curve.name not in _ECDSA_KEY_TYPE: raise ValueError( "Unsupported curve for ssh private key: %r" % curve.name ) return _ECDSA_KEY_TYPE[curve.name] def _ssh_pem_encode( data: bytes, prefix: bytes = _SK_START + b"\n", suffix: bytes = _SK_END + b"\n", ) -> bytes: return b"".join([prefix, _base64_encode(data), suffix]) def _check_block_size(data: bytes, block_len: int) -> None: """Require data to be full blocks""" if not data or len(data) % block_len != 0: raise ValueError("Corrupt data: missing padding") def _check_empty(data: bytes) -> None: """All data should have been parsed.""" if data: raise ValueError("Corrupt data: unparsed data") def _init_cipher( ciphername: bytes, password: typing.Optional[bytes], salt: bytes, rounds: int, ) -> Cipher[typing.Union[modes.CBC, modes.CTR]]: """Generate key + iv and return cipher.""" if not password: raise ValueError("Key is password-protected.") algo, key_len, mode, iv_len = _SSH_CIPHERS[ciphername] seed = _bcrypt_kdf(password, salt, key_len + iv_len, rounds, True) return Cipher(algo(seed[:key_len]), mode(seed[key_len:])) def _get_u32(data: memoryview) -> typing.Tuple[int, memoryview]: """Uint32""" if len(data) < 4: raise ValueError("Invalid data") return int.from_bytes(data[:4], byteorder="big"), data[4:] def _get_u64(data: memoryview) -> typing.Tuple[int, memoryview]: """Uint64""" if len(data) < 8: raise ValueError("Invalid data") return int.from_bytes(data[:8], byteorder="big"), data[8:] def _get_sshstr(data: memoryview) -> typing.Tuple[memoryview, memoryview]: """Bytes with u32 length prefix""" n, data = _get_u32(data) if n > len(data): raise ValueError("Invalid data") return data[:n], data[n:] def _get_mpint(data: memoryview) -> typing.Tuple[int, memoryview]: """Big integer.""" val, data = _get_sshstr(data) if val and val[0] > 0x7F: raise ValueError("Invalid data") return int.from_bytes(val, "big"), data def _to_mpint(val: int) -> bytes: """Storage format for signed bigint.""" if val < 0: raise ValueError("negative mpint not allowed") if not val: return b"" nbytes = (val.bit_length() + 8) // 8 return utils.int_to_bytes(val, nbytes) class _FragList(object): """Build recursive structure without data copy.""" flist: typing.List[bytes] def __init__(self, init: typing.List[bytes] = None) -> None: self.flist = [] if init: self.flist.extend(init) def put_raw(self, val: bytes) -> None: """Add plain bytes""" self.flist.append(val) def put_u32(self, val: int) -> None: """Big-endian uint32""" self.flist.append(val.to_bytes(length=4, byteorder="big")) def put_sshstr(self, val: typing.Union[bytes, "_FragList"]) -> None: """Bytes prefixed with u32 length""" if isinstance(val, (bytes, memoryview, bytearray)): self.put_u32(len(val)) self.flist.append(val) else: self.put_u32(val.size()) self.flist.extend(val.flist) def put_mpint(self, val: int) -> None: """Big-endian bigint prefixed with u32 length""" self.put_sshstr(_to_mpint(val)) def size(self) -> int: """Current number of bytes""" return sum(map(len, self.flist)) def render(self, dstbuf: memoryview, pos: int = 0) -> int: """Write into bytearray""" for frag in self.flist: flen = len(frag) start, pos = pos, pos + flen dstbuf[start:pos] = frag return pos def tobytes(self) -> bytes: """Return as bytes""" buf = memoryview(bytearray(self.size())) self.render(buf) return buf.tobytes() class _SSHFormatRSA(object): """Format for RSA keys. Public: mpint e, n Private: mpint n, e, d, iqmp, p, q """ def get_public(self, data: memoryview): """RSA public fields""" e, data = _get_mpint(data) n, data = _get_mpint(data) return (e, n), data def load_public( self, data: memoryview ) -> typing.Tuple[rsa.RSAPublicKey, memoryview]: """Make RSA public key from data.""" (e, n), data = self.get_public(data) public_numbers = rsa.RSAPublicNumbers(e, n) public_key = public_numbers.public_key() return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[rsa.RSAPrivateKey, memoryview]: """Make RSA private key from data.""" n, data = _get_mpint(data) e, data = _get_mpint(data) d, data = _get_mpint(data) iqmp, data = _get_mpint(data) p, data = _get_mpint(data) q, data = _get_mpint(data) if (e, n) != pubfields: raise ValueError("Corrupt data: rsa field mismatch") dmp1 = rsa.rsa_crt_dmp1(d, p) dmq1 = rsa.rsa_crt_dmq1(d, q) public_numbers = rsa.RSAPublicNumbers(e, n) private_numbers = rsa.RSAPrivateNumbers( p, q, d, dmp1, dmq1, iqmp, public_numbers ) private_key = private_numbers.private_key() return private_key, data def encode_public( self, public_key: rsa.RSAPublicKey, f_pub: _FragList ) -> None: """Write RSA public key""" pubn = public_key.public_numbers() f_pub.put_mpint(pubn.e) f_pub.put_mpint(pubn.n) def encode_private( self, private_key: rsa.RSAPrivateKey, f_priv: _FragList ) -> None: """Write RSA private key""" private_numbers = private_key.private_numbers() public_numbers = private_numbers.public_numbers f_priv.put_mpint(public_numbers.n) f_priv.put_mpint(public_numbers.e) f_priv.put_mpint(private_numbers.d) f_priv.put_mpint(private_numbers.iqmp) f_priv.put_mpint(private_numbers.p) f_priv.put_mpint(private_numbers.q) class _SSHFormatDSA(object): """Format for DSA keys. Public: mpint p, q, g, y Private: mpint p, q, g, y, x """ def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """DSA public fields""" p, data = _get_mpint(data) q, data = _get_mpint(data) g, data = _get_mpint(data) y, data = _get_mpint(data) return (p, q, g, y), data def load_public( self, data: memoryview ) -> typing.Tuple[dsa.DSAPublicKey, memoryview]: """Make DSA public key from data.""" (p, q, g, y), data = self.get_public(data) parameter_numbers = dsa.DSAParameterNumbers(p, q, g) public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) self._validate(public_numbers) public_key = public_numbers.public_key() return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[dsa.DSAPrivateKey, memoryview]: """Make DSA private key from data.""" (p, q, g, y), data = self.get_public(data) x, data = _get_mpint(data) if (p, q, g, y) != pubfields: raise ValueError("Corrupt data: dsa field mismatch") parameter_numbers = dsa.DSAParameterNumbers(p, q, g) public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) self._validate(public_numbers) private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) private_key = private_numbers.private_key() return private_key, data def encode_public( self, public_key: dsa.DSAPublicKey, f_pub: _FragList ) -> None: """Write DSA public key""" public_numbers = public_key.public_numbers() parameter_numbers = public_numbers.parameter_numbers self._validate(public_numbers) f_pub.put_mpint(parameter_numbers.p) f_pub.put_mpint(parameter_numbers.q) f_pub.put_mpint(parameter_numbers.g) f_pub.put_mpint(public_numbers.y) def encode_private( self, private_key: dsa.DSAPrivateKey, f_priv: _FragList ) -> None: """Write DSA private key""" self.encode_public(private_key.public_key(), f_priv) f_priv.put_mpint(private_key.private_numbers().x) def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: parameter_numbers = public_numbers.parameter_numbers if parameter_numbers.p.bit_length() != 1024: raise ValueError("SSH supports only 1024 bit DSA keys") class _SSHFormatECDSA(object): """Format for ECDSA keys. Public: str curve bytes point Private: str curve bytes point mpint secret """ def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): self.ssh_curve_name = ssh_curve_name self.curve = curve def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """ECDSA public fields""" curve, data = _get_sshstr(data) point, data = _get_sshstr(data) if curve != self.ssh_curve_name: raise ValueError("Curve name mismatch") if point[0] != 4: raise NotImplementedError("Need uncompressed point") return (curve, point), data def load_public( self, data: memoryview ) -> typing.Tuple[ec.EllipticCurvePublicKey, memoryview]: """Make ECDSA public key from data.""" (curve_name, point), data = self.get_public(data) public_key = ec.EllipticCurvePublicKey.from_encoded_point( self.curve, point.tobytes() ) return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[ec.EllipticCurvePrivateKey, memoryview]: """Make ECDSA private key from data.""" (curve_name, point), data = self.get_public(data) secret, data = _get_mpint(data) if (curve_name, point) != pubfields: raise ValueError("Corrupt data: ecdsa field mismatch") private_key = ec.derive_private_key(secret, self.curve) return private_key, data def encode_public( self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList ) -> None: """Write ECDSA public key""" point = public_key.public_bytes( Encoding.X962, PublicFormat.UncompressedPoint ) f_pub.put_sshstr(self.ssh_curve_name) f_pub.put_sshstr(point) def encode_private( self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList ) -> None: """Write ECDSA private key""" public_key = private_key.public_key() private_numbers = private_key.private_numbers() self.encode_public(public_key, f_priv) f_priv.put_mpint(private_numbers.private_value) class _SSHFormatEd25519(object): """Format for Ed25519 keys. Public: bytes point Private: bytes point bytes secret_and_point """ def get_public( self, data: memoryview ) -> typing.Tuple[typing.Tuple, memoryview]: """Ed25519 public fields""" point, data = _get_sshstr(data) return (point,), data def load_public( self, data: memoryview ) -> typing.Tuple[ed25519.Ed25519PublicKey, memoryview]: """Make Ed25519 public key from data.""" (point,), data = self.get_public(data) public_key = ed25519.Ed25519PublicKey.from_public_bytes( point.tobytes() ) return public_key, data def load_private( self, data: memoryview, pubfields ) -> typing.Tuple[ed25519.Ed25519PrivateKey, memoryview]: """Make Ed25519 private key from data.""" (point,), data = self.get_public(data) keypair, data = _get_sshstr(data) secret = keypair[:32] point2 = keypair[32:] if point != point2 or (point,) != pubfields: raise ValueError("Corrupt data: ed25519 field mismatch") private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) return private_key, data def encode_public( self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList ) -> None: """Write Ed25519 public key""" raw_public_key = public_key.public_bytes( Encoding.Raw, PublicFormat.Raw ) f_pub.put_sshstr(raw_public_key) def encode_private( self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList ) -> None: """Write Ed25519 private key""" public_key = private_key.public_key() raw_private_key = private_key.private_bytes( Encoding.Raw, PrivateFormat.Raw, NoEncryption() ) raw_public_key = public_key.public_bytes( Encoding.Raw, PublicFormat.Raw ) f_keypair = _FragList([raw_private_key, raw_public_key]) self.encode_public(public_key, f_priv) f_priv.put_sshstr(f_keypair) _KEY_FORMATS = { _SSH_RSA: _SSHFormatRSA(), _SSH_DSA: _SSHFormatDSA(), _SSH_ED25519: _SSHFormatEd25519(), _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), } def _lookup_kformat(key_type: bytes): """Return valid format or throw error""" if not isinstance(key_type, bytes): key_type = memoryview(key_type).tobytes() if key_type in _KEY_FORMATS: return _KEY_FORMATS[key_type] raise UnsupportedAlgorithm("Unsupported key type: %r" % key_type) _SSH_PRIVATE_KEY_TYPES = typing.Union[ ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey, dsa.DSAPrivateKey, ed25519.Ed25519PrivateKey, ] def load_ssh_private_key( data: bytes, password: typing.Optional[bytes], backend: typing.Any = None, ) -> _SSH_PRIVATE_KEY_TYPES: """Load private key from OpenSSH custom encoding.""" utils._check_byteslike("data", data) if password is not None: utils._check_bytes("password", password) m = _PEM_RC.search(data) if not m: raise ValueError("Not OpenSSH private key format") p1 = m.start(1) p2 = m.end(1) data = binascii.a2b_base64(memoryview(data)[p1:p2]) if not data.startswith(_SK_MAGIC): raise ValueError("Not OpenSSH private key format") data = memoryview(data)[len(_SK_MAGIC) :] # parse header ciphername, data = _get_sshstr(data) kdfname, data = _get_sshstr(data) kdfoptions, data = _get_sshstr(data) nkeys, data = _get_u32(data) if nkeys != 1: raise ValueError("Only one key supported") # load public key data pubdata, data = _get_sshstr(data) pub_key_type, pubdata = _get_sshstr(pubdata) kformat = _lookup_kformat(pub_key_type) pubfields, pubdata = kformat.get_public(pubdata) _check_empty(pubdata) # load secret data edata, data = _get_sshstr(data) _check_empty(data) if (ciphername, kdfname) != (_NONE, _NONE): ciphername_bytes = ciphername.tobytes() if ciphername_bytes not in _SSH_CIPHERS: raise UnsupportedAlgorithm( "Unsupported cipher: %r" % ciphername_bytes ) if kdfname != _BCRYPT: raise UnsupportedAlgorithm("Unsupported KDF: %r" % kdfname) blklen = _SSH_CIPHERS[ciphername_bytes][3] _check_block_size(edata, blklen) salt, kbuf = _get_sshstr(kdfoptions) rounds, kbuf = _get_u32(kbuf) _check_empty(kbuf) ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) edata = memoryview(ciph.decryptor().update(edata)) else: blklen = 8 _check_block_size(edata, blklen) ck1, edata = _get_u32(edata) ck2, edata = _get_u32(edata) if ck1 != ck2: raise ValueError("Corrupt data: broken checksum") # load per-key struct key_type, edata = _get_sshstr(edata) if key_type != pub_key_type: raise ValueError("Corrupt data: key type mismatch") private_key, edata = kformat.load_private(edata, pubfields) comment, edata = _get_sshstr(edata) # yes, SSH does padding check *after* all other parsing is done. # need to follow as it writes zero-byte padding too. if edata != _PADDING[: len(edata)]: raise ValueError("Corrupt data: invalid padding") return private_key def serialize_ssh_private_key( private_key: _SSH_PRIVATE_KEY_TYPES, password: typing.Optional[bytes] = None, ) -> bytes: """Serialize private key with OpenSSH custom encoding.""" if password is not None: utils._check_bytes("password", password) if password and len(password) > _MAX_PASSWORD: raise ValueError( "Passwords longer than 72 bytes are not supported by " "OpenSSH private key format" ) if isinstance(private_key, ec.EllipticCurvePrivateKey): key_type = _ecdsa_key_type(private_key.public_key()) elif isinstance(private_key, rsa.RSAPrivateKey): key_type = _SSH_RSA elif isinstance(private_key, dsa.DSAPrivateKey): key_type = _SSH_DSA elif isinstance(private_key, ed25519.Ed25519PrivateKey): key_type = _SSH_ED25519 else: raise ValueError("Unsupported key type") kformat = _lookup_kformat(key_type) # setup parameters f_kdfoptions = _FragList() if password: ciphername = _DEFAULT_CIPHER blklen = _SSH_CIPHERS[ciphername][3] kdfname = _BCRYPT rounds = _DEFAULT_ROUNDS salt = os.urandom(16) f_kdfoptions.put_sshstr(salt) f_kdfoptions.put_u32(rounds) ciph = _init_cipher(ciphername, password, salt, rounds) else: ciphername = kdfname = _NONE blklen = 8 ciph = None nkeys = 1 checkval = os.urandom(4) comment = b"" # encode public and private parts together f_public_key = _FragList() f_public_key.put_sshstr(key_type) kformat.encode_public(private_key.public_key(), f_public_key) f_secrets = _FragList([checkval, checkval]) f_secrets.put_sshstr(key_type) kformat.encode_private(private_key, f_secrets) f_secrets.put_sshstr(comment) f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) # top-level structure f_main = _FragList() f_main.put_raw(_SK_MAGIC) f_main.put_sshstr(ciphername) f_main.put_sshstr(kdfname) f_main.put_sshstr(f_kdfoptions) f_main.put_u32(nkeys) f_main.put_sshstr(f_public_key) f_main.put_sshstr(f_secrets) # copy result info bytearray slen = f_secrets.size() mlen = f_main.size() buf = memoryview(bytearray(mlen + blklen)) f_main.render(buf) ofs = mlen - slen # encrypt in-place if ciph is not None: ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) txt = _ssh_pem_encode(buf[:mlen]) buf[ofs:mlen] = bytearray(slen) return txt _SSH_PUBLIC_KEY_TYPES = typing.Union[ ec.EllipticCurvePublicKey, rsa.RSAPublicKey, dsa.DSAPublicKey, ed25519.Ed25519PublicKey, ] def load_ssh_public_key( data: bytes, backend: typing.Any = None ) -> _SSH_PUBLIC_KEY_TYPES: """Load public key from OpenSSH one-line format.""" utils._check_byteslike("data", data) m = _SSH_PUBKEY_RC.match(data) if not m: raise ValueError("Invalid line format") key_type = orig_key_type = m.group(1) key_body = m.group(2) with_cert = False if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]: with_cert = True key_type = key_type[: -len(_CERT_SUFFIX)] kformat = _lookup_kformat(key_type) try: rest = memoryview(binascii.a2b_base64(key_body)) except (TypeError, binascii.Error): raise ValueError("Invalid key format") inner_key_type, rest = _get_sshstr(rest) if inner_key_type != orig_key_type: raise ValueError("Invalid key format") if with_cert: nonce, rest = _get_sshstr(rest) public_key, rest = kformat.load_public(rest) if with_cert: serial, rest = _get_u64(rest) cctype, rest = _get_u32(rest) key_id, rest = _get_sshstr(rest) principals, rest = _get_sshstr(rest) valid_after, rest = _get_u64(rest) valid_before, rest = _get_u64(rest) crit_options, rest = _get_sshstr(rest) extensions, rest = _get_sshstr(rest) reserved, rest = _get_sshstr(rest) sig_key, rest = _get_sshstr(rest) signature, rest = _get_sshstr(rest) _check_empty(rest) return public_key def serialize_ssh_public_key(public_key: _SSH_PUBLIC_KEY_TYPES) -> bytes: """One-line public key format for OpenSSH""" if isinstance(public_key, ec.EllipticCurvePublicKey): key_type = _ecdsa_key_type(public_key) elif isinstance(public_key, rsa.RSAPublicKey): key_type = _SSH_RSA elif isinstance(public_key, dsa.DSAPublicKey): key_type = _SSH_DSA elif isinstance(public_key, ed25519.Ed25519PublicKey): key_type = _SSH_ED25519 else: raise ValueError("Unsupported key type") kformat = _lookup_kformat(key_type) f_pub = _FragList() f_pub.put_sshstr(key_type) kformat.encode_public(public_key, f_pub) pub = binascii.b2a_base64(f_pub.tobytes()).strip() return b"".join([key_type, b" ", pub])
en
0.713052
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. # re is only way to work on bytes-like data # padding for max blocksize # ciphers that are actually used in key wrapping # map local curve name to key type Return SSH key_type and curve_name for private key. Require data to be full blocks All data should have been parsed. Generate key + iv and return cipher. Uint32 Uint64 Bytes with u32 length prefix Big integer. Storage format for signed bigint. Build recursive structure without data copy. Add plain bytes Big-endian uint32 Bytes prefixed with u32 length Big-endian bigint prefixed with u32 length Current number of bytes Write into bytearray Return as bytes Format for RSA keys. Public: mpint e, n Private: mpint n, e, d, iqmp, p, q RSA public fields Make RSA public key from data. Make RSA private key from data. Write RSA public key Write RSA private key Format for DSA keys. Public: mpint p, q, g, y Private: mpint p, q, g, y, x DSA public fields Make DSA public key from data. Make DSA private key from data. Write DSA public key Write DSA private key Format for ECDSA keys. Public: str curve bytes point Private: str curve bytes point mpint secret ECDSA public fields Make ECDSA public key from data. Make ECDSA private key from data. Write ECDSA public key Write ECDSA private key Format for Ed25519 keys. Public: bytes point Private: bytes point bytes secret_and_point Ed25519 public fields Make Ed25519 public key from data. Make Ed25519 private key from data. Write Ed25519 public key Write Ed25519 private key Return valid format or throw error Load private key from OpenSSH custom encoding. # parse header # load public key data # load secret data # load per-key struct # yes, SSH does padding check *after* all other parsing is done. # need to follow as it writes zero-byte padding too. Serialize private key with OpenSSH custom encoding. # setup parameters # encode public and private parts together # top-level structure # copy result info bytearray # encrypt in-place Load public key from OpenSSH one-line format. One-line public key format for OpenSSH
2.102288
2
examples/hacker_news/hacker_news/legacy/repo.py
geoHeil/dagster
0
6630515
from dagster import repository from ..schedules.hourly_hn_download_schedule import hourly_hn_download_schedule from ..sensors.download_pipeline_finished_sensor import dbt_on_hn_download_finished from ..sensors.hn_tables_updated_sensor import story_recommender_on_hn_table_update from ..sensors.slack_on_failure_sensor import make_pipeline_failure_sensor from .pipelines.dbt_pipeline import dbt_pipeline from .pipelines.download_pipeline import download_pipeline from .pipelines.story_recommender import story_recommender # Creates a hacker news reference repository using the legacy dagster APIs of pipeline, solid, # and mode. @repository def hacker_news_legacy(): pipelines = [ download_pipeline, story_recommender, dbt_pipeline, ] schedules = [ hourly_hn_download_schedule, ] sensors = [ make_pipeline_failure_sensor(base_url="my_dagit_url.com"), story_recommender_on_hn_table_update, dbt_on_hn_download_finished, ] return pipelines + schedules + sensors
from dagster import repository from ..schedules.hourly_hn_download_schedule import hourly_hn_download_schedule from ..sensors.download_pipeline_finished_sensor import dbt_on_hn_download_finished from ..sensors.hn_tables_updated_sensor import story_recommender_on_hn_table_update from ..sensors.slack_on_failure_sensor import make_pipeline_failure_sensor from .pipelines.dbt_pipeline import dbt_pipeline from .pipelines.download_pipeline import download_pipeline from .pipelines.story_recommender import story_recommender # Creates a hacker news reference repository using the legacy dagster APIs of pipeline, solid, # and mode. @repository def hacker_news_legacy(): pipelines = [ download_pipeline, story_recommender, dbt_pipeline, ] schedules = [ hourly_hn_download_schedule, ] sensors = [ make_pipeline_failure_sensor(base_url="my_dagit_url.com"), story_recommender_on_hn_table_update, dbt_on_hn_download_finished, ] return pipelines + schedules + sensors
en
0.494526
# Creates a hacker news reference repository using the legacy dagster APIs of pipeline, solid, # and mode.
1.866747
2
clean_mws.py
Wonqu/SMAA2019_Team5
0
6630516
<gh_stars>0 import uuid from extract_sentences import extract_sentences, extract_chapters FRANKENSTEIN_CHAPTERS = { x.upper().strip() for x in """Letter 1 Letter 2 Letter 3 Letter 4 Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 """.split('\n') if x.upper().strip() } if __name__ == '__main__': sentences = [ sentence for poem in extract_chapters(FRANKENSTEIN_CHAPTERS, 'mws_clean.txt') for sentence in extract_sentences(poem) ] with open('./data/out/mws.csv', 'w', encoding='UTF-8') as mws: newline = '\n' mws.write(f'"id","text","author"{newline}') for s in sentences: mws.write(f'"{uuid.uuid4()}","{s}","MWS"{newline}')
import uuid from extract_sentences import extract_sentences, extract_chapters FRANKENSTEIN_CHAPTERS = { x.upper().strip() for x in """Letter 1 Letter 2 Letter 3 Letter 4 Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24 """.split('\n') if x.upper().strip() } if __name__ == '__main__': sentences = [ sentence for poem in extract_chapters(FRANKENSTEIN_CHAPTERS, 'mws_clean.txt') for sentence in extract_sentences(poem) ] with open('./data/out/mws.csv', 'w', encoding='UTF-8') as mws: newline = '\n' mws.write(f'"id","text","author"{newline}') for s in sentences: mws.write(f'"{uuid.uuid4()}","{s}","MWS"{newline}')
en
0.682626
Letter 1 Letter 2 Letter 3 Letter 4 Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20 Chapter 21 Chapter 22 Chapter 23 Chapter 24
2.689702
3
rhea/vendor/_output_serdes.py
meetps/rhea
1
6630517
<filename>rhea/vendor/_output_serdes.py from myhdl import Signal, intbv, concat, always, always_comb from . import SERDESInterface
<filename>rhea/vendor/_output_serdes.py from myhdl import Signal, intbv, concat, always, always_comb from . import SERDESInterface
none
1
1.30917
1
bayesmark/xgb_cuml.py
daxiongshu/bayesmark
3
6630518
<filename>bayesmark/xgb_cuml.py<gh_stars>1-10 import xgboost as xgb import cupy as cp from cuml.preprocessing.model_selection import train_test_split def get_default_params(): return { 'objective': 'multi:softprob', 'eval_metric': 'mlogloss', 'tree_method': 'gpu_hist', 'verbosity': 0, 'early_stopping':False, 'validation_fraction':0.1, 'early_stopping_rounds':10, } def print_shape(*x): for i in x: print(i.shape, end=' ') print() class XGBbase: def __init__(self, **params): self.params = get_default_params() self.params.update(params) def fit(self, X, y): test_size = self.params['validation_fraction'] num_boost_round = self.params['n_estimators'] #ext_params = ['early_stopping', 'early_stopping_rounds', # 'n_estimators', 'silent', 'validation_fraction', 'verbose'] if test_size >0: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = test_size) dtrain = xgb.DMatrix(data=X_train, label=y_train) dvalid = xgb.DMatrix(data=X_test, label=y_test) watchlist = [(dtrain, 'train'), (dvalid, 'eval')] early_stopping_rounds = self.params['early_stopping_rounds'] self.clf = xgb.train(self.params, dtrain=dtrain, num_boost_round=num_boost_round,evals=watchlist, early_stopping_rounds=early_stopping_rounds, verbose_eval=1000) else: dtrain = xgb.DMatrix(data=X, label=y) self.clf = xgb.train(self.params, dtrain=dtrain, num_boost_round=num_boost_round) return self def predict(self, X): self.clf.set_param({'predictor': 'gpu_predictor'}) dtest = xgb.DMatrix(data=X) yp = self.clf.predict(dtest) yp = cp.asarray(yp) return yp class XGBClassifier(XGBbase): def __init__(self, **params): super().__init__(**params) def fit(self, X, y): num_class = int(y.max()+1) if num_class > 2: self.params['num_class'] = num_class else: self.params['objective'] = 'binary:logistic' self.params['eval_metric'] = 'logloss' return super().fit(X, y) def predict_proba(self, X): return super().predict(X) def predict(self, X): yp = super().predict(X) if len(yp.shape) == 2: yp = cp.argmax(yp, axis=1) else: yp = yp>0.5 return yp class XGBRegressor(XGBbase): def __init__(self, **params): params['objective'] = 'reg:squarederror' params['eval_metric'] = 'rmse' super().__init__(**params)
<filename>bayesmark/xgb_cuml.py<gh_stars>1-10 import xgboost as xgb import cupy as cp from cuml.preprocessing.model_selection import train_test_split def get_default_params(): return { 'objective': 'multi:softprob', 'eval_metric': 'mlogloss', 'tree_method': 'gpu_hist', 'verbosity': 0, 'early_stopping':False, 'validation_fraction':0.1, 'early_stopping_rounds':10, } def print_shape(*x): for i in x: print(i.shape, end=' ') print() class XGBbase: def __init__(self, **params): self.params = get_default_params() self.params.update(params) def fit(self, X, y): test_size = self.params['validation_fraction'] num_boost_round = self.params['n_estimators'] #ext_params = ['early_stopping', 'early_stopping_rounds', # 'n_estimators', 'silent', 'validation_fraction', 'verbose'] if test_size >0: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = test_size) dtrain = xgb.DMatrix(data=X_train, label=y_train) dvalid = xgb.DMatrix(data=X_test, label=y_test) watchlist = [(dtrain, 'train'), (dvalid, 'eval')] early_stopping_rounds = self.params['early_stopping_rounds'] self.clf = xgb.train(self.params, dtrain=dtrain, num_boost_round=num_boost_round,evals=watchlist, early_stopping_rounds=early_stopping_rounds, verbose_eval=1000) else: dtrain = xgb.DMatrix(data=X, label=y) self.clf = xgb.train(self.params, dtrain=dtrain, num_boost_round=num_boost_round) return self def predict(self, X): self.clf.set_param({'predictor': 'gpu_predictor'}) dtest = xgb.DMatrix(data=X) yp = self.clf.predict(dtest) yp = cp.asarray(yp) return yp class XGBClassifier(XGBbase): def __init__(self, **params): super().__init__(**params) def fit(self, X, y): num_class = int(y.max()+1) if num_class > 2: self.params['num_class'] = num_class else: self.params['objective'] = 'binary:logistic' self.params['eval_metric'] = 'logloss' return super().fit(X, y) def predict_proba(self, X): return super().predict(X) def predict(self, X): yp = super().predict(X) if len(yp.shape) == 2: yp = cp.argmax(yp, axis=1) else: yp = yp>0.5 return yp class XGBRegressor(XGBbase): def __init__(self, **params): params['objective'] = 'reg:squarederror' params['eval_metric'] = 'rmse' super().__init__(**params)
en
0.247735
#ext_params = ['early_stopping', 'early_stopping_rounds', # 'n_estimators', 'silent', 'validation_fraction', 'verbose']
2.249122
2
netnir/plugins/facts.py
jtdub/netnir
0
6630519
from nornir.core.task import Task, Result from typing import Any def inventory_facts(task: Task, **kwargs: Any) -> Result: """gather inventory facts :params task: type object :returns: inventory host facts dictionary """ return Result( host=task.host, result={"facts": task.host.data, "groups": task.host.groups}, )
from nornir.core.task import Task, Result from typing import Any def inventory_facts(task: Task, **kwargs: Any) -> Result: """gather inventory facts :params task: type object :returns: inventory host facts dictionary """ return Result( host=task.host, result={"facts": task.host.data, "groups": task.host.groups}, )
en
0.51312
gather inventory facts :params task: type object :returns: inventory host facts dictionary
2.334316
2
microcosm_flask/tests/conventions/test_create_collection_conflict.py
Sinon/microcosm-flask
11
6630520
from hamcrest import assert_that, calling, raises from marshmallow import Schema from microcosm.api import create_object_graph from microcosm_flask.conventions.base import EndpointDefinition, RouteAlreadyRegisteredException from microcosm_flask.conventions.crud import configure_crud from microcosm_flask.namespaces import Namespace from microcosm_flask.operations import Operation class TestCreateCollectionConflict: def setup(self): self.graph = create_object_graph(name="example", testing=True) self.ns = Namespace(subject="foo") self.client = self.graph.flask.test_client() def test_register_both_create_and_create_collection(self): mappings = { Operation.Create: EndpointDefinition( func=lambda x: x, request_schema=Schema(), response_schema=Schema(), ), Operation.CreateCollection: EndpointDefinition( func=lambda x: x, request_schema=Schema(), response_schema=Schema(), ), } assert_that( calling(configure_crud).with_args(self.graph, self.ns, mappings), raises(RouteAlreadyRegisteredException), )
from hamcrest import assert_that, calling, raises from marshmallow import Schema from microcosm.api import create_object_graph from microcosm_flask.conventions.base import EndpointDefinition, RouteAlreadyRegisteredException from microcosm_flask.conventions.crud import configure_crud from microcosm_flask.namespaces import Namespace from microcosm_flask.operations import Operation class TestCreateCollectionConflict: def setup(self): self.graph = create_object_graph(name="example", testing=True) self.ns = Namespace(subject="foo") self.client = self.graph.flask.test_client() def test_register_both_create_and_create_collection(self): mappings = { Operation.Create: EndpointDefinition( func=lambda x: x, request_schema=Schema(), response_schema=Schema(), ), Operation.CreateCollection: EndpointDefinition( func=lambda x: x, request_schema=Schema(), response_schema=Schema(), ), } assert_that( calling(configure_crud).with_args(self.graph, self.ns, mappings), raises(RouteAlreadyRegisteredException), )
none
1
2.114926
2
scripts/recon_enum3/nfsrecon.py
r4b3rt/OSCPRepo
2,109
6630521
#!/usr/bin/python import sys import os import subprocess import argparse import errno import pathlib # TODO: this relied on nfspy to do certain checks. Look into dockerizing nfspy and re-implementing # mkdir_p function updated for >= python 3.5 def mkdir_p(path): pathlib.Path(path).mkdir(parents=True, exist_ok=True) #Running #nfs-ls: Attempts to get useful info about files from NFS Exports #nfs-showmount: Show NFS explorts like 'showmount -e' #nfs-statfs: Retrieves disk space from NFS like 'df' def doNmap(ip_address, port): print("INFO: Starting nfs nmap on %s:%s" % (ip_address, port)) if len(port.split(",")) > 1: for ports in port.split(","): outfileNmap = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsnmap" % (ip_address, ports) subprocess.check_output(['nmap','-n','-sV','-Pn','-vv','-p',ports,'--script','nfs-ls,nfs-showmount,nfs-statfs,vulners',"-oA",outfileNmap,ip_address],encoding='utf8') else: outfileNmap = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsnmap" % (ip_address, port) subprocess.check_output(['nmap','-n','-sV','-Pn','-vv','-p',port,'--script','nfs-ls,nfs-showmount,nfs-statfs,vulners',"-oA",outfileNmap,ip_address],encoding='utf8') print("INFO: Nfs nmap completed on %s:%s" % (ip_address, port)) return def doSysCommands(ip_address, port): print("INFO: Starting nfs sysCommands on %s:%s" % (ip_address, port)) f = open(outfile,'w') DEVNULL = open(os.devnull, 'w') try: results1 = subprocess.check_output(['showmount','-a',ip_address],encoding='utf8',stderr=DEVNULL) if results1: f.write("Showmount -a: " + "\n") f.write(results1) f.write("\n") except subprocess.CalledProcessError as e: if e.returncode == 1: print("Unable to showmount -a, try manually") else: print("Unexpected error in nfsrecon doSysCommands 1") try: results2 = subprocess.check_output(['showmount','-e',ip_address],encoding='utf8',stderr=DEVNULL) DEVNULL.close() if results2: f.write("Showmount -e: " + "\n") f.write(results2) f.write("\n") f.close() results = results2.split("\n") doNfspy(results) except subprocess.CalledProcessError as e: if e.returncode == 1: print("Unable to showmount -e, try manually") else: print("Unexpected error in nfsrecon doSysCommands 2") def doNfspy(results): for res in results: if "/" in res: try: sharename = res.split(" ")[0] #grab just the mount/share fqsharename = "%s:%s" % (ip_address, sharename) if os.path.isfile('/bin/nfspy'): try: dir = sharename.split("/")[-1] #grab last element so we can make a name for it dir = "/mnt/%s" % dir if not os.path.isdir(dir): mkdir_p(dir) subprocess.check_output(['nfspy',dir,'-o','server=%s,getroot,hide,allow_root,rw' % (fqsharename)],encoding='utf8') print("INFO: %s should be mounted at %s" % (sharename, dir)) except: print("Error in NFSRecon, nfspy failed") except: print("Something went wrong with nfspy or creation. Try manually for: %s" % res) print("INFO: nfs sysCommands completed on %s:%s" % (ip_address, port)) return if __name__=='__main__': parser = argparse.ArgumentParser(description='Rough script to handle nfs enumeration. Usage: nfsrecon.py ip {port}') parser.add_argument('ip', help="IP address of target") parser.add_argument('--port', default='111,2049', help="Port. Default is 111,2049") args = parser.parse_args() ip_address = args.ip if args.port != '111,2049': port = '111,2049,%s' % args.port #need rpc for nmap scripts else: port = '111,2049' BASE = "/root/scripts/recon_enum/results/exam/nfs" mkdir_p(BASE) outfile = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsrecon.txt" % (ip_address, port) doNmap(ip_address, port) doSysCommands(ip_address, port) print("INFO: nfsRecon completed for %s:%s" % (ip_address, port))
#!/usr/bin/python import sys import os import subprocess import argparse import errno import pathlib # TODO: this relied on nfspy to do certain checks. Look into dockerizing nfspy and re-implementing # mkdir_p function updated for >= python 3.5 def mkdir_p(path): pathlib.Path(path).mkdir(parents=True, exist_ok=True) #Running #nfs-ls: Attempts to get useful info about files from NFS Exports #nfs-showmount: Show NFS explorts like 'showmount -e' #nfs-statfs: Retrieves disk space from NFS like 'df' def doNmap(ip_address, port): print("INFO: Starting nfs nmap on %s:%s" % (ip_address, port)) if len(port.split(",")) > 1: for ports in port.split(","): outfileNmap = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsnmap" % (ip_address, ports) subprocess.check_output(['nmap','-n','-sV','-Pn','-vv','-p',ports,'--script','nfs-ls,nfs-showmount,nfs-statfs,vulners',"-oA",outfileNmap,ip_address],encoding='utf8') else: outfileNmap = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsnmap" % (ip_address, port) subprocess.check_output(['nmap','-n','-sV','-Pn','-vv','-p',port,'--script','nfs-ls,nfs-showmount,nfs-statfs,vulners',"-oA",outfileNmap,ip_address],encoding='utf8') print("INFO: Nfs nmap completed on %s:%s" % (ip_address, port)) return def doSysCommands(ip_address, port): print("INFO: Starting nfs sysCommands on %s:%s" % (ip_address, port)) f = open(outfile,'w') DEVNULL = open(os.devnull, 'w') try: results1 = subprocess.check_output(['showmount','-a',ip_address],encoding='utf8',stderr=DEVNULL) if results1: f.write("Showmount -a: " + "\n") f.write(results1) f.write("\n") except subprocess.CalledProcessError as e: if e.returncode == 1: print("Unable to showmount -a, try manually") else: print("Unexpected error in nfsrecon doSysCommands 1") try: results2 = subprocess.check_output(['showmount','-e',ip_address],encoding='utf8',stderr=DEVNULL) DEVNULL.close() if results2: f.write("Showmount -e: " + "\n") f.write(results2) f.write("\n") f.close() results = results2.split("\n") doNfspy(results) except subprocess.CalledProcessError as e: if e.returncode == 1: print("Unable to showmount -e, try manually") else: print("Unexpected error in nfsrecon doSysCommands 2") def doNfspy(results): for res in results: if "/" in res: try: sharename = res.split(" ")[0] #grab just the mount/share fqsharename = "%s:%s" % (ip_address, sharename) if os.path.isfile('/bin/nfspy'): try: dir = sharename.split("/")[-1] #grab last element so we can make a name for it dir = "/mnt/%s" % dir if not os.path.isdir(dir): mkdir_p(dir) subprocess.check_output(['nfspy',dir,'-o','server=%s,getroot,hide,allow_root,rw' % (fqsharename)],encoding='utf8') print("INFO: %s should be mounted at %s" % (sharename, dir)) except: print("Error in NFSRecon, nfspy failed") except: print("Something went wrong with nfspy or creation. Try manually for: %s" % res) print("INFO: nfs sysCommands completed on %s:%s" % (ip_address, port)) return if __name__=='__main__': parser = argparse.ArgumentParser(description='Rough script to handle nfs enumeration. Usage: nfsrecon.py ip {port}') parser.add_argument('ip', help="IP address of target") parser.add_argument('--port', default='111,2049', help="Port. Default is 111,2049") args = parser.parse_args() ip_address = args.ip if args.port != '111,2049': port = '111,2049,%s' % args.port #need rpc for nmap scripts else: port = '111,2049' BASE = "/root/scripts/recon_enum/results/exam/nfs" mkdir_p(BASE) outfile = "/root/scripts/recon_enum/results/exam/nfs/%s_%s_nfsrecon.txt" % (ip_address, port) doNmap(ip_address, port) doSysCommands(ip_address, port) print("INFO: nfsRecon completed for %s:%s" % (ip_address, port))
en
0.709396
#!/usr/bin/python # TODO: this relied on nfspy to do certain checks. Look into dockerizing nfspy and re-implementing # mkdir_p function updated for >= python 3.5 #Running #nfs-ls: Attempts to get useful info about files from NFS Exports #nfs-showmount: Show NFS explorts like 'showmount -e' #nfs-statfs: Retrieves disk space from NFS like 'df' #grab just the mount/share #grab last element so we can make a name for it #need rpc for nmap scripts
2.335058
2
stacked_capsule_autoencoders/capsules/data/constellation.py
rmitra/google-research
1
6630522
<gh_stars>1-10 # coding=utf-8 # Copyright 2019 The Google Research 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. """Constellation dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow.compat.v1 as tf ConstellationTuple = collections.namedtuple('ConstellationTuple', 'presence corners pattern_presence ' 'pattern_id') def create_numpy( size_n=1, shuffle_corners=True, gaussian_noise=0., max_translation=1., rotation_percent=0.0, max_upscale=0.0, which_patterns='basic', drop_prob=0.0, ): """Creates a batch of data using numpy.""" sm = 1 if which_patterns == 'basic': which_patterns = [[0], [1]] elif which_patterns == 'all': which_patterns = [[0], [1], [2], [3]] elif isinstance(which_patterns, str): raise ValueError('Pattern "{}" has not been ' 'implemented.'.format(which_patterns)) pattern = [ np.array([[1 + 2 * sm, 1 + 2 * sm, 1], [1, 1, 1], [1 + 2 * sm, 1, 1], [1, 1 + 2 * sm, 1]]), # square np.array([[1, 1 + sm, 1], [1 + 2 * sm, 1, 1], [1 + 2 * sm, 1 + 2 * sm, 1]]), # triangle np.array([[1, 1, 1], [1 + sm, 1 - 2 * sm, 1], [1 + 2 * sm, 1 - sm, 1], [1 + 2 * sm, 1 + sm, 1], [1 + sm, 1 + 2 * sm, 1]]), # pentagon np.array([[1, 1, 1], [1 + sm, 1, 1], [1 + 2 * sm, 1, 1], [1 + 2 * sm, 1 + sm, 1], [1 + 2 * sm, 1 + 2 * sm, 1]]), # L ] caps_dim = pattern[0].shape[1] transformations = [] all_corners = [] all_corner_presence = [] all_pattern_presence = [] centers = np.array([0, 0, 1]) for i in range(len(which_patterns)): corners = centers.copy() for j in range(len(which_patterns[i])): corner_trans = np.zeros((pattern[which_patterns[i][j]].shape[0], caps_dim, caps_dim)) corner_trans[:, -1, :] = pattern[which_patterns[i][j]] * (j + 1) corner_trans[:, :-1, :-1] = np.eye(caps_dim - 1) corners = np.matmul(corners, corner_trans) corners = corners.reshape(-1, caps_dim) transformation = np.zeros((size_n, caps_dim, caps_dim)) transformation[:, :, -1] = [0, 0, 1] # [pi/2, pi] degree = (np.random.random((size_n)) - .5) * 2. * np.pi * rotation_percent scale = 1. + np.random.random((size_n)) * max_upscale translation = np.random.random((size_n, 2)) * 24. * max_translation transformation[:, 0, 0] = np.cos(degree) * scale transformation[:, 1, 1] = np.cos(degree) * scale transformation[:, 0, 1] = np.sin(degree) * scale transformation[:, 1, 0] = -np.sin(degree) * scale transformation[:, -1, :-1] = translation / scale[Ellipsis, np.newaxis] corners = np.matmul(corners, transformation) random_pattern_choice = np.random.binomial(1, 1. - drop_prob, (corners.shape[0], 1)) random_corer_choice = np.tile(random_pattern_choice, (1, corners.shape[1])) all_corner_presence.append(random_corer_choice) all_pattern_presence.append(random_pattern_choice) transformations.append(transformation) all_corners.append(corners) capsules = np.concatenate(all_corners, axis=1)[Ellipsis, :2] all_corner_presence = np.concatenate(all_corner_presence, axis=1) all_pattern_presence = np.concatenate(all_pattern_presence, axis=1) pattern_ids = [] current_pattern_id = 0 for i in range(len(which_patterns)): for j in which_patterns[i]: corner_ids = [current_pattern_id] * len(pattern[j]) pattern_ids.extend(corner_ids) current_pattern_id += 1 pattern_ids = np.asarray(pattern_ids)[np.newaxis] pattern_ids = np.tile(pattern_ids, [capsules.shape[0], 1]) capsules, all_corner_presence, all_pattern_presence = [ i.astype(np.float32) for i in (capsules, all_corner_presence, all_pattern_presence) ] if shuffle_corners: for i in range(capsules.shape[0]): p = np.random.permutation(len(capsules[i])) capsules[i] = capsules[i][p] all_corner_presence[i] = all_corner_presence[i][p] pattern_ids[i] = pattern_ids[i][p] if gaussian_noise > 0.: capsules += np.random.normal(scale=gaussian_noise, size=capsules.shape) # normalize corners min_d, max_d = capsules.min(), capsules.max() capsules = (capsules - min_d) / (max_d - min_d + 1e-8) * 2 - 1. minibatch = dict(corners=capsules, presence=all_corner_presence, pattern_presence=all_pattern_presence, pattern_id=pattern_ids) return minibatch def create( batch_size=32, subset=None, shuffle_corners=True, gaussian_noise=0., max_translation=1., rotation_percent=0.0, which_patterns='basic', drop_prob=0.0, max_scale=3., min_scale=.1, use_scale_schedule=False, schedule_steps=100000., ): """Creates the dataset loader.""" del subset def generator(n_batches=100): """Generates `n_batches` of data.""" step = 0 n = n_batches * batch_size while True: if use_scale_schedule: scale = (max_scale - min_scale) * float(step) / schedule_steps scale = min(scale + min_scale, max_scale) step += n_batches else: scale = max_scale batch = create_numpy(n, shuffle_corners, gaussian_noise, max_translation, rotation_percent, scale, which_patterns, drop_prob) for i in range(n_batches): st = i * batch_size ed = st + batch_size b = {k: v[st:ed] for k, v in batch.items()} yield b minibatch = next(generator(n_batches=1)) dtypes = {k: v.dtype for k, v in minibatch.items()} shapes = {k: v.shape for k, v in minibatch.items()} dataset = tf.data.Dataset.from_generator(generator, dtypes, shapes) iter_data = dataset.make_one_shot_iterator() input_batch = iter_data.get_next() for _, v in input_batch.items(): v.set_shape([batch_size] + v.shape[1:].as_list()) return ConstellationTuple(**input_batch)
# coding=utf-8 # Copyright 2019 The Google Research 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. """Constellation dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow.compat.v1 as tf ConstellationTuple = collections.namedtuple('ConstellationTuple', 'presence corners pattern_presence ' 'pattern_id') def create_numpy( size_n=1, shuffle_corners=True, gaussian_noise=0., max_translation=1., rotation_percent=0.0, max_upscale=0.0, which_patterns='basic', drop_prob=0.0, ): """Creates a batch of data using numpy.""" sm = 1 if which_patterns == 'basic': which_patterns = [[0], [1]] elif which_patterns == 'all': which_patterns = [[0], [1], [2], [3]] elif isinstance(which_patterns, str): raise ValueError('Pattern "{}" has not been ' 'implemented.'.format(which_patterns)) pattern = [ np.array([[1 + 2 * sm, 1 + 2 * sm, 1], [1, 1, 1], [1 + 2 * sm, 1, 1], [1, 1 + 2 * sm, 1]]), # square np.array([[1, 1 + sm, 1], [1 + 2 * sm, 1, 1], [1 + 2 * sm, 1 + 2 * sm, 1]]), # triangle np.array([[1, 1, 1], [1 + sm, 1 - 2 * sm, 1], [1 + 2 * sm, 1 - sm, 1], [1 + 2 * sm, 1 + sm, 1], [1 + sm, 1 + 2 * sm, 1]]), # pentagon np.array([[1, 1, 1], [1 + sm, 1, 1], [1 + 2 * sm, 1, 1], [1 + 2 * sm, 1 + sm, 1], [1 + 2 * sm, 1 + 2 * sm, 1]]), # L ] caps_dim = pattern[0].shape[1] transformations = [] all_corners = [] all_corner_presence = [] all_pattern_presence = [] centers = np.array([0, 0, 1]) for i in range(len(which_patterns)): corners = centers.copy() for j in range(len(which_patterns[i])): corner_trans = np.zeros((pattern[which_patterns[i][j]].shape[0], caps_dim, caps_dim)) corner_trans[:, -1, :] = pattern[which_patterns[i][j]] * (j + 1) corner_trans[:, :-1, :-1] = np.eye(caps_dim - 1) corners = np.matmul(corners, corner_trans) corners = corners.reshape(-1, caps_dim) transformation = np.zeros((size_n, caps_dim, caps_dim)) transformation[:, :, -1] = [0, 0, 1] # [pi/2, pi] degree = (np.random.random((size_n)) - .5) * 2. * np.pi * rotation_percent scale = 1. + np.random.random((size_n)) * max_upscale translation = np.random.random((size_n, 2)) * 24. * max_translation transformation[:, 0, 0] = np.cos(degree) * scale transformation[:, 1, 1] = np.cos(degree) * scale transformation[:, 0, 1] = np.sin(degree) * scale transformation[:, 1, 0] = -np.sin(degree) * scale transformation[:, -1, :-1] = translation / scale[Ellipsis, np.newaxis] corners = np.matmul(corners, transformation) random_pattern_choice = np.random.binomial(1, 1. - drop_prob, (corners.shape[0], 1)) random_corer_choice = np.tile(random_pattern_choice, (1, corners.shape[1])) all_corner_presence.append(random_corer_choice) all_pattern_presence.append(random_pattern_choice) transformations.append(transformation) all_corners.append(corners) capsules = np.concatenate(all_corners, axis=1)[Ellipsis, :2] all_corner_presence = np.concatenate(all_corner_presence, axis=1) all_pattern_presence = np.concatenate(all_pattern_presence, axis=1) pattern_ids = [] current_pattern_id = 0 for i in range(len(which_patterns)): for j in which_patterns[i]: corner_ids = [current_pattern_id] * len(pattern[j]) pattern_ids.extend(corner_ids) current_pattern_id += 1 pattern_ids = np.asarray(pattern_ids)[np.newaxis] pattern_ids = np.tile(pattern_ids, [capsules.shape[0], 1]) capsules, all_corner_presence, all_pattern_presence = [ i.astype(np.float32) for i in (capsules, all_corner_presence, all_pattern_presence) ] if shuffle_corners: for i in range(capsules.shape[0]): p = np.random.permutation(len(capsules[i])) capsules[i] = capsules[i][p] all_corner_presence[i] = all_corner_presence[i][p] pattern_ids[i] = pattern_ids[i][p] if gaussian_noise > 0.: capsules += np.random.normal(scale=gaussian_noise, size=capsules.shape) # normalize corners min_d, max_d = capsules.min(), capsules.max() capsules = (capsules - min_d) / (max_d - min_d + 1e-8) * 2 - 1. minibatch = dict(corners=capsules, presence=all_corner_presence, pattern_presence=all_pattern_presence, pattern_id=pattern_ids) return minibatch def create( batch_size=32, subset=None, shuffle_corners=True, gaussian_noise=0., max_translation=1., rotation_percent=0.0, which_patterns='basic', drop_prob=0.0, max_scale=3., min_scale=.1, use_scale_schedule=False, schedule_steps=100000., ): """Creates the dataset loader.""" del subset def generator(n_batches=100): """Generates `n_batches` of data.""" step = 0 n = n_batches * batch_size while True: if use_scale_schedule: scale = (max_scale - min_scale) * float(step) / schedule_steps scale = min(scale + min_scale, max_scale) step += n_batches else: scale = max_scale batch = create_numpy(n, shuffle_corners, gaussian_noise, max_translation, rotation_percent, scale, which_patterns, drop_prob) for i in range(n_batches): st = i * batch_size ed = st + batch_size b = {k: v[st:ed] for k, v in batch.items()} yield b minibatch = next(generator(n_batches=1)) dtypes = {k: v.dtype for k, v in minibatch.items()} shapes = {k: v.shape for k, v in minibatch.items()} dataset = tf.data.Dataset.from_generator(generator, dtypes, shapes) iter_data = dataset.make_one_shot_iterator() input_batch = iter_data.get_next() for _, v in input_batch.items(): v.set_shape([batch_size] + v.shape[1:].as_list()) return ConstellationTuple(**input_batch)
en
0.793324
# coding=utf-8 # Copyright 2019 The Google Research 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. Constellation dataset. Creates a batch of data using numpy. # square # triangle # pentagon # L # [pi/2, pi] # normalize corners Creates the dataset loader. Generates `n_batches` of data.
2.144808
2
examples/matplotlib/mpl_plot_kde_2d_hdi.py
sudojarvis/arviz
1,159
6630523
<reponame>sudojarvis/arviz """ 2d KDE with HDI Contours ======================== _thumb: .5, .8 _example_title: 2d KDE with HDI Contours """ import matplotlib.pyplot as plt import numpy as np import arviz as az az.style.use("arviz-darkgrid") rng = np.random.default_rng() data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000) ax = az.plot_kde( data[:, 0], data[:, 1], hdi_probs=[0.393, 0.865, 0.989], # 1, 2 and 3 sigma contours contourf_kwargs={"cmap": "Blues"}, ) ax.set_aspect("equal") plt.show()
""" 2d KDE with HDI Contours ======================== _thumb: .5, .8 _example_title: 2d KDE with HDI Contours """ import matplotlib.pyplot as plt import numpy as np import arviz as az az.style.use("arviz-darkgrid") rng = np.random.default_rng() data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000) ax = az.plot_kde( data[:, 0], data[:, 1], hdi_probs=[0.393, 0.865, 0.989], # 1, 2 and 3 sigma contours contourf_kwargs={"cmap": "Blues"}, ) ax.set_aspect("equal") plt.show()
en
0.556357
2d KDE with HDI Contours ======================== _thumb: .5, .8 _example_title: 2d KDE with HDI Contours # 1, 2 and 3 sigma contours
2.507939
3
setup.py
himanshu-dutta/pycoder
1
6630524
<reponame>himanshu-dutta/pycoder from setuptools import setup, find_packages from pycoder.version import __version__ from pathlib import Path PACKAGE_DIR = (Path(__file__).parent / "pycoder").absolute() HTML_PATH = PACKAGE_DIR / "api" / "index.html" if not HTML_PATH.exists(): raise FileNotFoundError(HTML_PATH) with open("README.md") as f: long_description = f.read() setup( name="pycoder", version=__version__, packages=find_packages(), description="A package to generate Python code from given topics and description", long_description=long_description, long_description_content_type="text/markdown", author="<NAME>", author_email="<EMAIL>", url="https://github.com/himanshu-dutta/pycoder", install_requires=[ "torch==1.8.1", "typer==0.3.2", "transformers==4.6.1", "markdown==3.3.4", "fastapi==0.65.1", "uvicorn==0.13.4", "pygments==2.9.0", "click-spinner==0.1.10", ], extras_require={"dev": ["pytest", "black", "wandb", "pygithub"]}, entry_points={ "console_scripts": [ "pycoder=pycoder.api.cli:cli", ], }, include_package_data=True, package_data={ "pycoder": [ str(HTML_PATH.relative_to(PACKAGE_DIR)), ] }, python_requires=">3.7", license="MIT License", classifiers=[ "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], platforms=["linux", "unix", "windows"], )
from setuptools import setup, find_packages from pycoder.version import __version__ from pathlib import Path PACKAGE_DIR = (Path(__file__).parent / "pycoder").absolute() HTML_PATH = PACKAGE_DIR / "api" / "index.html" if not HTML_PATH.exists(): raise FileNotFoundError(HTML_PATH) with open("README.md") as f: long_description = f.read() setup( name="pycoder", version=__version__, packages=find_packages(), description="A package to generate Python code from given topics and description", long_description=long_description, long_description_content_type="text/markdown", author="<NAME>", author_email="<EMAIL>", url="https://github.com/himanshu-dutta/pycoder", install_requires=[ "torch==1.8.1", "typer==0.3.2", "transformers==4.6.1", "markdown==3.3.4", "fastapi==0.65.1", "uvicorn==0.13.4", "pygments==2.9.0", "click-spinner==0.1.10", ], extras_require={"dev": ["pytest", "black", "wandb", "pygithub"]}, entry_points={ "console_scripts": [ "pycoder=pycoder.api.cli:cli", ], }, include_package_data=True, package_data={ "pycoder": [ str(HTML_PATH.relative_to(PACKAGE_DIR)), ] }, python_requires=">3.7", license="MIT License", classifiers=[ "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], platforms=["linux", "unix", "windows"], )
none
1
2.045601
2
VUsbTools/Style.py
scanlime/vusb-analyzer
34
6630525
<filename>VUsbTools/Style.py # # VUsbTools.Views # <NAME> <<EMAIL>> # # A container for color and font preferences # # Copyright (C) 2005-2010 VMware, Inc. Licensed under the MIT # License, please see the README.txt. All rights reserved. # import math from VUsbTools.Types import Color # # Use the default monospace font. If this is too large/small for your # tastes, you can try a specific font name and size like "courier 9". # monospaceFont = "monospace" def toMonospaceMarkup(text): """Convert arbitrary text to pango markup in our monospace font""" return '<span font_desc="%s">%s</span>' % ( monospaceFont, text.replace("&", "&amp;").replace("<", "&lt;")) directionColors = { "Up": Color(0x00, 0x00, 0xFF), "Down": Color(0x00, 0x80, 0x00), } directionIcons = { "Down": "gtk-go-forward", "Up": "gtk-go-back", } errorMarkerColor = Color(0xFF, 0x00, 0x00, 0x80) diffMarkerColor = Color(0x00, 0xA0, 0x00, 0x30) diffBorderColor = Color(0x00, 0xA0, 0x00, 0xA0) emptyTransactionColor = Color(0x80, 0x80, 0x80) smallTransactionColor = Color(0x80, 0x80, 0xFF) largeTransactionColor = Color(0xFF, 0xFF, 0x80) frameMarkerColor = Color(0x00, 0x00, 0xFF) duplicateFrameColor = Color(0x80, 0x00, 0x00) def getBarColor(transaction): """Get the color to use for a transaction's bar on the timing diagram. This implementation bases the color on a transaction's size. """ s = transaction.datalen or 0 if not s: return emptyTransactionColor # For non-empty transactions, the color is actually proportional # to size on a logarithmic scale. return smallTransactionColor.lerp( math.log(s) / math.log(4096), largeTransactionColor)
<filename>VUsbTools/Style.py # # VUsbTools.Views # <NAME> <<EMAIL>> # # A container for color and font preferences # # Copyright (C) 2005-2010 VMware, Inc. Licensed under the MIT # License, please see the README.txt. All rights reserved. # import math from VUsbTools.Types import Color # # Use the default monospace font. If this is too large/small for your # tastes, you can try a specific font name and size like "courier 9". # monospaceFont = "monospace" def toMonospaceMarkup(text): """Convert arbitrary text to pango markup in our monospace font""" return '<span font_desc="%s">%s</span>' % ( monospaceFont, text.replace("&", "&amp;").replace("<", "&lt;")) directionColors = { "Up": Color(0x00, 0x00, 0xFF), "Down": Color(0x00, 0x80, 0x00), } directionIcons = { "Down": "gtk-go-forward", "Up": "gtk-go-back", } errorMarkerColor = Color(0xFF, 0x00, 0x00, 0x80) diffMarkerColor = Color(0x00, 0xA0, 0x00, 0x30) diffBorderColor = Color(0x00, 0xA0, 0x00, 0xA0) emptyTransactionColor = Color(0x80, 0x80, 0x80) smallTransactionColor = Color(0x80, 0x80, 0xFF) largeTransactionColor = Color(0xFF, 0xFF, 0x80) frameMarkerColor = Color(0x00, 0x00, 0xFF) duplicateFrameColor = Color(0x80, 0x00, 0x00) def getBarColor(transaction): """Get the color to use for a transaction's bar on the timing diagram. This implementation bases the color on a transaction's size. """ s = transaction.datalen or 0 if not s: return emptyTransactionColor # For non-empty transactions, the color is actually proportional # to size on a logarithmic scale. return smallTransactionColor.lerp( math.log(s) / math.log(4096), largeTransactionColor)
en
0.670161
# # VUsbTools.Views # <NAME> <<EMAIL>> # # A container for color and font preferences # # Copyright (C) 2005-2010 VMware, Inc. Licensed under the MIT # License, please see the README.txt. All rights reserved. # # # Use the default monospace font. If this is too large/small for your # tastes, you can try a specific font name and size like "courier 9". # Convert arbitrary text to pango markup in our monospace font Get the color to use for a transaction's bar on the timing diagram. This implementation bases the color on a transaction's size. # For non-empty transactions, the color is actually proportional # to size on a logarithmic scale.
2.272134
2
tests/test_pep8.py
sdrees/jupytext
11
6630526
import pytest from nbformat.v4.nbbase import new_code_cell, new_notebook from jupytext import read, reads, writes from jupytext.compare import compare from jupytext.pep8 import ( cell_ends_with_code, cell_ends_with_function_or_class, cell_has_code, next_instruction_is_function_or_class, pep8_lines_between_cells, ) from .utils import list_notebooks def test_next_instruction_is_function_or_class(): text = """@pytest.mark.parametrize('py_file', [py_file for py_file in list_notebooks('../jupytext') + list_notebooks('.') if py_file.endswith('.py')]) def test_no_metadata_when_py_is_pep8(py_file): pass """ assert next_instruction_is_function_or_class(text.splitlines()) def test_cell_ends_with_code(): assert not cell_ends_with_code([]) def test_cell_ends_with_function_or_class(): text = """class A: __init__(): '''A docstring with two lines or more''' self.a = 0 """ assert cell_ends_with_function_or_class(text.splitlines()) lines = ["#", "#"] assert not cell_ends_with_function_or_class(lines) text = """# two blank line after this class class A: pass # so we do not need to insert two blank lines below this cell """ assert not cell_ends_with_function_or_class(text.splitlines()) text = """# All lines # are commented""" assert not cell_ends_with_function_or_class(text.splitlines()) text = """# Two blank lines after function def f(x): return x # And a comment here""" assert not cell_ends_with_function_or_class(text.splitlines()) assert not cell_ends_with_function_or_class(["", "#"]) def test_pep8_lines_between_cells(): prev_lines = """a = a_long_instruction( over_two_lines=True)""".splitlines() next_lines = """def f(x): return x""".splitlines() assert cell_ends_with_code(prev_lines) assert next_instruction_is_function_or_class(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 def test_pep8_lines_between_cells_bis(): prev_lines = """def f(x): return x""".splitlines() next_lines = """# A markdown cell # An instruction a = 5 """.splitlines() assert cell_ends_with_function_or_class(prev_lines) assert cell_has_code(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 next_lines = """# A markdown cell # Only markdown here # And here """.splitlines() assert cell_ends_with_function_or_class(prev_lines) assert not cell_has_code(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 1 def test_pep8_lines_between_cells_ter(): prev_lines = ["from jupytext.cell_to_text import RMarkdownCellExporter"] next_lines = '''@pytest.mark.parametrize( "lines", [ "# text", """# # %%R # # comment # 1 + 1 # 2 + 2 """, ], ) def test_paragraph_is_fully_commented(lines): assert paragraph_is_fully_commented( lines.splitlines(), comment="#", main_language="python" )'''.splitlines() assert cell_ends_with_code(prev_lines) assert next_instruction_is_function_or_class(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 def test_pep8(): text = """import os path = os.path # code cell #1, with a comment on f def f(x): return x + 1 # markdown cell #1 # code cell #2 - an instruction a = 4 # markdown cell #2 # code cell #3 with a comment on g def g(x): return x + 1 # markdown cell #3 # the two lines are: # - right below the function/class # - below the last python paragraph (i.e. NOT ABOVE g) # code cell #4 x = 4 """ nb = reads(text, "py") for cell in nb.cells: assert not cell.metadata text2 = writes(nb, "py") compare(text2, text) def test_pep8_bis(): text = """# This is a markdown cell # a code cell def f(x): return x + 1 # And another markdown cell # Separated from f by just one line # As there is no code here """ nb = reads(text, "py") for cell in nb.cells: assert not cell.metadata text2 = writes(nb, "py") compare(text2, text) @pytest.mark.parametrize( "py_file", [ py_file for py_file in list_notebooks("../jupytext") + list_notebooks(".") if py_file.endswith(".py") and "folding_markers" not in py_file ], ) def test_no_metadata_when_py_is_pep8(py_file): """This test assumes that all Python files in the jupytext folder follow PEP8 rules""" nb = read(py_file) for i, cell in enumerate(nb.cells): if "title" in cell.metadata: cell.metadata.pop("title") # pragma: no cover if i == 0 and not cell.source: assert cell.metadata == { "lines_to_next_cell": 0 }, py_file # pragma: no cover else: assert not cell.metadata, (py_file, cell.source) def test_notebook_ends_with_exactly_one_empty_line_682(): """(Issue #682) Steps to reproduce: Have a notebook that ends in a python code cell (with no empty lines at the end of the cell). run jupytext --to py:percent notebookWithCodeCell.ipynb. See that the generated python code file has two empty lines at the end. I would expect there to just be one new line.""" nb = new_notebook( cells=[new_code_cell("1+1")], metadata={"jupytext": {"main_language": "python"}} ) py = writes(nb, "py:percent") assert py.endswith("1+1\n")
import pytest from nbformat.v4.nbbase import new_code_cell, new_notebook from jupytext import read, reads, writes from jupytext.compare import compare from jupytext.pep8 import ( cell_ends_with_code, cell_ends_with_function_or_class, cell_has_code, next_instruction_is_function_or_class, pep8_lines_between_cells, ) from .utils import list_notebooks def test_next_instruction_is_function_or_class(): text = """@pytest.mark.parametrize('py_file', [py_file for py_file in list_notebooks('../jupytext') + list_notebooks('.') if py_file.endswith('.py')]) def test_no_metadata_when_py_is_pep8(py_file): pass """ assert next_instruction_is_function_or_class(text.splitlines()) def test_cell_ends_with_code(): assert not cell_ends_with_code([]) def test_cell_ends_with_function_or_class(): text = """class A: __init__(): '''A docstring with two lines or more''' self.a = 0 """ assert cell_ends_with_function_or_class(text.splitlines()) lines = ["#", "#"] assert not cell_ends_with_function_or_class(lines) text = """# two blank line after this class class A: pass # so we do not need to insert two blank lines below this cell """ assert not cell_ends_with_function_or_class(text.splitlines()) text = """# All lines # are commented""" assert not cell_ends_with_function_or_class(text.splitlines()) text = """# Two blank lines after function def f(x): return x # And a comment here""" assert not cell_ends_with_function_or_class(text.splitlines()) assert not cell_ends_with_function_or_class(["", "#"]) def test_pep8_lines_between_cells(): prev_lines = """a = a_long_instruction( over_two_lines=True)""".splitlines() next_lines = """def f(x): return x""".splitlines() assert cell_ends_with_code(prev_lines) assert next_instruction_is_function_or_class(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 def test_pep8_lines_between_cells_bis(): prev_lines = """def f(x): return x""".splitlines() next_lines = """# A markdown cell # An instruction a = 5 """.splitlines() assert cell_ends_with_function_or_class(prev_lines) assert cell_has_code(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 next_lines = """# A markdown cell # Only markdown here # And here """.splitlines() assert cell_ends_with_function_or_class(prev_lines) assert not cell_has_code(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 1 def test_pep8_lines_between_cells_ter(): prev_lines = ["from jupytext.cell_to_text import RMarkdownCellExporter"] next_lines = '''@pytest.mark.parametrize( "lines", [ "# text", """# # %%R # # comment # 1 + 1 # 2 + 2 """, ], ) def test_paragraph_is_fully_commented(lines): assert paragraph_is_fully_commented( lines.splitlines(), comment="#", main_language="python" )'''.splitlines() assert cell_ends_with_code(prev_lines) assert next_instruction_is_function_or_class(next_lines) assert pep8_lines_between_cells(prev_lines, next_lines, ".py") == 2 def test_pep8(): text = """import os path = os.path # code cell #1, with a comment on f def f(x): return x + 1 # markdown cell #1 # code cell #2 - an instruction a = 4 # markdown cell #2 # code cell #3 with a comment on g def g(x): return x + 1 # markdown cell #3 # the two lines are: # - right below the function/class # - below the last python paragraph (i.e. NOT ABOVE g) # code cell #4 x = 4 """ nb = reads(text, "py") for cell in nb.cells: assert not cell.metadata text2 = writes(nb, "py") compare(text2, text) def test_pep8_bis(): text = """# This is a markdown cell # a code cell def f(x): return x + 1 # And another markdown cell # Separated from f by just one line # As there is no code here """ nb = reads(text, "py") for cell in nb.cells: assert not cell.metadata text2 = writes(nb, "py") compare(text2, text) @pytest.mark.parametrize( "py_file", [ py_file for py_file in list_notebooks("../jupytext") + list_notebooks(".") if py_file.endswith(".py") and "folding_markers" not in py_file ], ) def test_no_metadata_when_py_is_pep8(py_file): """This test assumes that all Python files in the jupytext folder follow PEP8 rules""" nb = read(py_file) for i, cell in enumerate(nb.cells): if "title" in cell.metadata: cell.metadata.pop("title") # pragma: no cover if i == 0 and not cell.source: assert cell.metadata == { "lines_to_next_cell": 0 }, py_file # pragma: no cover else: assert not cell.metadata, (py_file, cell.source) def test_notebook_ends_with_exactly_one_empty_line_682(): """(Issue #682) Steps to reproduce: Have a notebook that ends in a python code cell (with no empty lines at the end of the cell). run jupytext --to py:percent notebookWithCodeCell.ipynb. See that the generated python code file has two empty lines at the end. I would expect there to just be one new line.""" nb = new_notebook( cells=[new_code_cell("1+1")], metadata={"jupytext": {"main_language": "python"}} ) py = writes(nb, "py:percent") assert py.endswith("1+1\n")
en
0.664204
@pytest.mark.parametrize('py_file', [py_file for py_file in list_notebooks('../jupytext') + list_notebooks('.') if py_file.endswith('.py')]) def test_no_metadata_when_py_is_pep8(py_file): pass class A: __init__(): '''A docstring with two lines or more''' self.a = 0 # two blank line after this class class A: pass # so we do not need to insert two blank lines below this cell # All lines # are commented # Two blank lines after function def f(x): return x # And a comment here a = a_long_instruction( over_two_lines=True) def f(x): return x def f(x): return x # A markdown cell # An instruction a = 5 # A markdown cell # Only markdown here # And here @pytest.mark.parametrize( "lines", [ "# text", """# # %%R # # comment # 1 + 1 # 2 + 2 """, ], ) def test_paragraph_is_fully_commented(lines): assert paragraph_is_fully_commented( lines.splitlines(), comment="#", main_language="python" ) import os path = os.path # code cell #1, with a comment on f def f(x): return x + 1 # markdown cell #1 # code cell #2 - an instruction a = 4 # markdown cell #2 # code cell #3 with a comment on g def g(x): return x + 1 # markdown cell #3 # the two lines are: # - right below the function/class # - below the last python paragraph (i.e. NOT ABOVE g) # code cell #4 x = 4 # This is a markdown cell # a code cell def f(x): return x + 1 # And another markdown cell # Separated from f by just one line # As there is no code here This test assumes that all Python files in the jupytext folder follow PEP8 rules # pragma: no cover # pragma: no cover (Issue #682) Steps to reproduce: Have a notebook that ends in a python code cell (with no empty lines at the end of the cell). run jupytext --to py:percent notebookWithCodeCell.ipynb. See that the generated python code file has two empty lines at the end. I would expect there to just be one new line.
2.723639
3
Module/dnsrecon/lib/gooenum.py
vishnudxb/Yuki-Chan-The-Auto-Pentest
655
6630527
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010 <NAME> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; Applies version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import urllib import re import time try: url_opener = urllib.FancyURLopener except AttributeError: import urllib.request url_opener = urllib.request.FancyURLopener class AppURLopener(url_opener): version = 'Mozilla/5.0 (compatible; Googlebot/2.1; + http://www.google.com/bot.html)' def scrape_google(dom): """ Function for enumerating sub-domains and hosts by scrapping Google. It returns a unique list if host name extracted from the HREF entries from the Google search. """ results = [] filtered = [] searches = ["100", "200", "300", "400", "500"] data = "" urllib._urlopener = AppURLopener() user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' headers = {'User-Agent': user_agent, } #opener.addheaders = [('User-Agent','Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')] for n in searches: url = "http://google.com/search?hl=en&lr=&ie=UTF-8&q=%2B" + dom + "&start=" + n + "&sa=N&filter=0&num=100" try: sock = urllib.urlopen(url) data += sock.read() sock.close() except AttributeError: request = urllib.request.Request(url, None, headers) response = urllib.request.urlopen(request) data += str(response.read()) results.extend(unique(re.findall("href=\"htt\w{1,2}:\/\/([^:?]*[a-b0-9]*[^:?]*\." + dom + ")\/", data))) # Make sure we are only getting the host for f in results: filtered.extend(re.findall("^([a-z.0-9^]*" + dom + ")", f)) time.sleep(2) return unique(filtered) def unique(seq, idfun=repr): """ Function to remove duplicates in an array. Returns array with duplicates removed. """ seen = {} return [seen.setdefault(idfun(e), e) for e in seq if idfun(e) not in seen]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010 <NAME> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; Applies version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import urllib import re import time try: url_opener = urllib.FancyURLopener except AttributeError: import urllib.request url_opener = urllib.request.FancyURLopener class AppURLopener(url_opener): version = 'Mozilla/5.0 (compatible; Googlebot/2.1; + http://www.google.com/bot.html)' def scrape_google(dom): """ Function for enumerating sub-domains and hosts by scrapping Google. It returns a unique list if host name extracted from the HREF entries from the Google search. """ results = [] filtered = [] searches = ["100", "200", "300", "400", "500"] data = "" urllib._urlopener = AppURLopener() user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7' headers = {'User-Agent': user_agent, } #opener.addheaders = [('User-Agent','Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')] for n in searches: url = "http://google.com/search?hl=en&lr=&ie=UTF-8&q=%2B" + dom + "&start=" + n + "&sa=N&filter=0&num=100" try: sock = urllib.urlopen(url) data += sock.read() sock.close() except AttributeError: request = urllib.request.Request(url, None, headers) response = urllib.request.urlopen(request) data += str(response.read()) results.extend(unique(re.findall("href=\"htt\w{1,2}:\/\/([^:?]*[a-b0-9]*[^:?]*\." + dom + ")\/", data))) # Make sure we are only getting the host for f in results: filtered.extend(re.findall("^([a-z.0-9^]*" + dom + ")", f)) time.sleep(2) return unique(filtered) def unique(seq, idfun=repr): """ Function to remove duplicates in an array. Returns array with duplicates removed. """ seen = {} return [seen.setdefault(idfun(e), e) for e in seq if idfun(e) not in seen]
en
0.814775
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010 <NAME> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; Applies version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Function for enumerating sub-domains and hosts by scrapping Google. It returns a unique list if host name extracted from the HREF entries from the Google search. #opener.addheaders = [('User-Agent','Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')] # Make sure we are only getting the host Function to remove duplicates in an array. Returns array with duplicates removed.
2.7092
3
scripts/house_contacts.py
jeffgeee/congress-legislators
0
6630528
<gh_stars>0 #!/usr/bin/env python # Update current congressmember's contact info from clerk XML feed import requests import lxml import re from datetime import datetime from utils import load_data, save_data, parse_date def run(): today = datetime.now().date() y = load_data("legislators-current.yaml") # TODO use download util? xml = requests.get("http://clerk.house.gov/xml/lists/MemberData.xml") root=lxml.etree.fromstring(xml.content) for moc in y: try: term = moc["terms"][-1] except IndexError: print("Member has no terms", moc) continue if term["type"] != "rep": continue if today < parse_date(term["start"]) or today > parse_date(term["end"]): print("Member's last listed term is not current", moc, term["start"]) continue if "class" in term: del term["class"] ssdd = "%s%02d" % (term["state"], term["district"]) query_str = "./members/member/[statedistrict='%s']" % ssdd # TODO: Follow up query_str = query_str.replace("AS00", "AQ00") #print(query_str) mi = root.findall(query_str)[0].find('member-info') if (mi.find('bioguideID').text != moc['id'].get('bioguide')): print("Warning: Bioguide ID did not match for %s%02d (%s != %s)" % ( term["state"], term["district"], mi.find('bioguideID').text, moc['id']['bioguide'])) # for now, no automatic name updates since there is disagremeent on how to handle # firstname = mi.find('firstname').text # middlename = mi.find('middlename').text #could be empty # lastname = mi.find('lastname').text #TODO: follow up, why no official name? if mi.find('official-name') is None or mi.find('official-name').text is None: print("Warning: No official-name tag for %s" % ssdd) officialname = None else: officialname = re.sub("'", "’", mi.find('official-name').text) office_room = mi.find('office-room').text office_building = mi.find('office-building').text office_building_full = office_building.replace("RHOB", "Rayburn House Office Building") office_building_full = office_building_full.replace("CHOB", "Cannon House Office Building") office_building_full = office_building_full.replace("LHOB", "Longworth House Office Building") office_zip = mi.find('office-zip').text office_zip_suffix = mi.find('office-zip-suffix').text office = "{} {}".format(office_room, office_building_full) address = "{} {} Washington DC {}-{}".format(office_room, office_building_full, office_zip, office_zip_suffix) phone = mi.find('phone').text phone_parsed = re.sub("^\((\d\d\d)\) ", lambda m : m.group(1) + "-", phone) # replace (XXX) area code with XXX- for compatibility w/ existing format #for now, no automatic name updates since there is disagremeent on how to handle # moc["name"]["first"] = firstname # if (middlename): # moc["name"]["middle"] = middlename # else: # if ("middle" in moc["name"]): # del moc["name"]["middle"] # moc["name"]["last"] = lastname # TODO: leave if none? if (officialname): moc["name"]["official_full"] = officialname term["address"] = address term["office"] = office term["phone"] = phone_parsed save_data(y, "legislators-current.yaml") if __name__ == '__main__': run()
#!/usr/bin/env python # Update current congressmember's contact info from clerk XML feed import requests import lxml import re from datetime import datetime from utils import load_data, save_data, parse_date def run(): today = datetime.now().date() y = load_data("legislators-current.yaml") # TODO use download util? xml = requests.get("http://clerk.house.gov/xml/lists/MemberData.xml") root=lxml.etree.fromstring(xml.content) for moc in y: try: term = moc["terms"][-1] except IndexError: print("Member has no terms", moc) continue if term["type"] != "rep": continue if today < parse_date(term["start"]) or today > parse_date(term["end"]): print("Member's last listed term is not current", moc, term["start"]) continue if "class" in term: del term["class"] ssdd = "%s%02d" % (term["state"], term["district"]) query_str = "./members/member/[statedistrict='%s']" % ssdd # TODO: Follow up query_str = query_str.replace("AS00", "AQ00") #print(query_str) mi = root.findall(query_str)[0].find('member-info') if (mi.find('bioguideID').text != moc['id'].get('bioguide')): print("Warning: Bioguide ID did not match for %s%02d (%s != %s)" % ( term["state"], term["district"], mi.find('bioguideID').text, moc['id']['bioguide'])) # for now, no automatic name updates since there is disagremeent on how to handle # firstname = mi.find('firstname').text # middlename = mi.find('middlename').text #could be empty # lastname = mi.find('lastname').text #TODO: follow up, why no official name? if mi.find('official-name') is None or mi.find('official-name').text is None: print("Warning: No official-name tag for %s" % ssdd) officialname = None else: officialname = re.sub("'", "’", mi.find('official-name').text) office_room = mi.find('office-room').text office_building = mi.find('office-building').text office_building_full = office_building.replace("RHOB", "Rayburn House Office Building") office_building_full = office_building_full.replace("CHOB", "Cannon House Office Building") office_building_full = office_building_full.replace("LHOB", "Longworth House Office Building") office_zip = mi.find('office-zip').text office_zip_suffix = mi.find('office-zip-suffix').text office = "{} {}".format(office_room, office_building_full) address = "{} {} Washington DC {}-{}".format(office_room, office_building_full, office_zip, office_zip_suffix) phone = mi.find('phone').text phone_parsed = re.sub("^\((\d\d\d)\) ", lambda m : m.group(1) + "-", phone) # replace (XXX) area code with XXX- for compatibility w/ existing format #for now, no automatic name updates since there is disagremeent on how to handle # moc["name"]["first"] = firstname # if (middlename): # moc["name"]["middle"] = middlename # else: # if ("middle" in moc["name"]): # del moc["name"]["middle"] # moc["name"]["last"] = lastname # TODO: leave if none? if (officialname): moc["name"]["official_full"] = officialname term["address"] = address term["office"] = office term["phone"] = phone_parsed save_data(y, "legislators-current.yaml") if __name__ == '__main__': run()
en
0.538497
#!/usr/bin/env python # Update current congressmember's contact info from clerk XML feed # TODO use download util? # TODO: Follow up #print(query_str) # for now, no automatic name updates since there is disagremeent on how to handle # firstname = mi.find('firstname').text # middlename = mi.find('middlename').text #could be empty # lastname = mi.find('lastname').text #TODO: follow up, why no official name? # replace (XXX) area code with XXX- for compatibility w/ existing format #for now, no automatic name updates since there is disagremeent on how to handle # moc["name"]["first"] = firstname # if (middlename): # moc["name"]["middle"] = middlename # else: # if ("middle" in moc["name"]): # del moc["name"]["middle"] # moc["name"]["last"] = lastname # TODO: leave if none?
2.831433
3
ScopusScrapus/ScopusSearch.py
neoflex/ScopusScrapus
1
6630529
<reponame>neoflex/ScopusScrapus import requests as r import urllib.parse as purl import json def StartScopusSearch(key, params): ssq = ScopusSearchQuery(key, params) return ssq class ScopusSearchQuery: _defaultParams = {'count': 100, 'view': 'COMPLETE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/search/scopus?" _support_pagination = True _root_key = 'search-results' def __init__(self, key, params, timeout=60, apikey_return=False): self._apiKey = key self._keys = None if isinstance(key, list): self._keys = key self._keyCount = 0 self._apiKey = key[0] self._state = "empty" self._params = params self._data = [] self._nextUrl = None self._i = 0 self._count = 0 self._timeout = timeout self._apikey_return = apikey_return # Return (self._data[self._i-1], self._apiKey) instead of self._data[self._i-1] def _make_search_url(self): params = self._params defParams = self._defaultParams pSet = set(params.keys()).union(set(defParams.keys())) parameters = {key: params[key] if key in params else defParams[key] for key in pSet} querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._baseUrl, querystring, '&', apiKeyString) return url def _manageQuotaExcess(self, raiseOnQE=False): print("Managing quota exess...") if raiseOnQE or self._keys is None: raise Exception("QuotaExceeded - You must wait 7 days until quotas are reset") self._nextUrl = None self._keyCount = self._keyCount + 1 print("Key was: "+self._apiKey) try: self._apiKey = self._keys[self._keyCount] print("Key is: "+self._apiKey) return self._run_search() except IndexError: return self._run_search(True) # If we fail again, we surrender def _run_search(self, raiseOnQE=False): url = self._nextUrl if url is None: url = self._make_search_url() if url == "done": raise StopIteration() qRes = r.get(url,timeout=self._timeout) if qRes.status_code in [429, 401]: # If Invalid API Key or exceeding quota for the API Key, change it return self._manageQuotaExcess(raiseOnQE) dta = qRes.json() if qRes.status_code != 200: raise Exception("{} {} {} {}".format("Error: ", dta['service-error']['status']['statusText'], "URL is:", url)) # Fix this # KeyError hazard: If no 'next' url is available, we need to error out anyway nxtLink = [ln for ln in dta[self._root_key]['link'] if ln['@ref'] == 'next'] if len(nxtLink) > 0: self._nextUrl = nxtLink[0]['@href'] else: self._nextUrl = "done" # Nasty? Sorry : ) return dta[self._root_key]['entry'] # Returning only the obtained results def __iter__(self): return self def next(self): return self.__next__() def __next__(self): if self._i == len(self._data): self._data = self._run_search() self._i = 0 self._i += 1 if self._apikey_return: return self._data[self._i-1], self._apiKey elif not self.apikey_return: return self._data[self._i-1] class ScopusSerialTitle(ScopusSearchQuery): _defaultParams = {'count': 100, 'view': 'CITESCORE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/serial/title" _support_pagination = False _root_key = 'serial-metadata-response' def _make_search_url(self): params = self._params defParams = self._defaultParams pSet = set(params.keys()).union(set(defParams.keys())) parameters = {key: params[key] if key in params else defParams[key] for key in pSet} if "issn" in parameters: base_url = self._baseUrl + '/issn/' + parameters['issn'] + '?' if 'title' in parameters: parameters.pop('title') parameters.pop('issn') else: base_url = self._baseUrl + '?' querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._baseUrl, querystring, '&', apiKeyString) return url class SerialTitleQuery: # Serial title search _defaultParams = {'count': 200, 'view': 'CITESCORE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/serial/title?" _support_pagination = False _root_key = 'serial-metadata-response' def __init__(self, key, params, timeout=60): self._apiKey = key self._keys = None if isinstance(key, list): self._keys = key self._keyCount = 0 self._apiKey = key[0] self._state = "empty" self._params = params self._data = [] self._nextUrl = None self._i = 0 self._count = 0 self._timeout = timeout def _make_search_url(self): params = self._params pset = set(params.keys()).union(set(self._defaultParams.keys())) parameters = {key: params[key] if key in params else self._defaultParams[key] for key in pset} # make query querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._base_url, querystring, '&', apiKeyString) return url def _manageQuotaExcess(self, raiseOnQE=False): print("Managing quota exess...") if raiseOnQE or self._keys is None: raise Exception("QuotaExceeded - You must wait 7 days until quotas are reset") self._nextUrl = None self._keyCount = self._keyCount + 1 print("Key was: " + self._apiKey) try: self._apiKey = self._keys[self._keyCount] print("Key is: " + self._apiKey) return self._run_search() except IndexError: return self._run_search(True) # If we fail again, we surrender def _run_search(self, raiseOnQE=False): url = self._nextUrl if url is None: url = self._make_search_url() if url == "done": raise StopIteration() qRes = r.get(url, timeout=self._timeout) if qRes.status_code in [429, 401]: # If Invalid API Key or exceeding quota for the API Key, change it return self._manageQuotaExcess(raiseOnQE) dta = qRes.json() if qRes.status_code != 200: logger.info("{} {} {} {}".format("Error: ", dta['service-error']['status']['statusText'], "URL is:", url)) raise StopIteration() if 'entry' not in dta[self._root_key]: raise StopIteration() if _defaultParams['count'] <= len(dta[self._root_key]['entry']): next_url = dta[self._root_key]['link'][0]['@href'] parsed = urlparse.urlparse(next_url) parsed_query = urlparse.parse_qs(parsed.query) start = int(parsed_query['start'][0]) + int(parsed_query['count'][0]) self._nextUrl = "{0}&{1}={2}".format(self._make_search_url(), 'start', start) if start >= 10000: self._nextUrl = "done" else: self._nextUrl = "done" return dta[self._root_key]['entry'] def __iter__(self): return self def next(self): return self.__next__() def __next__(self): if self._i == len(self._data): self._data = self._run_search() self._i = 0 if len(self._data) == self._i: pass # Raise error self._i += 1 return self._data[self._i - 1]
import requests as r import urllib.parse as purl import json def StartScopusSearch(key, params): ssq = ScopusSearchQuery(key, params) return ssq class ScopusSearchQuery: _defaultParams = {'count': 100, 'view': 'COMPLETE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/search/scopus?" _support_pagination = True _root_key = 'search-results' def __init__(self, key, params, timeout=60, apikey_return=False): self._apiKey = key self._keys = None if isinstance(key, list): self._keys = key self._keyCount = 0 self._apiKey = key[0] self._state = "empty" self._params = params self._data = [] self._nextUrl = None self._i = 0 self._count = 0 self._timeout = timeout self._apikey_return = apikey_return # Return (self._data[self._i-1], self._apiKey) instead of self._data[self._i-1] def _make_search_url(self): params = self._params defParams = self._defaultParams pSet = set(params.keys()).union(set(defParams.keys())) parameters = {key: params[key] if key in params else defParams[key] for key in pSet} querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._baseUrl, querystring, '&', apiKeyString) return url def _manageQuotaExcess(self, raiseOnQE=False): print("Managing quota exess...") if raiseOnQE or self._keys is None: raise Exception("QuotaExceeded - You must wait 7 days until quotas are reset") self._nextUrl = None self._keyCount = self._keyCount + 1 print("Key was: "+self._apiKey) try: self._apiKey = self._keys[self._keyCount] print("Key is: "+self._apiKey) return self._run_search() except IndexError: return self._run_search(True) # If we fail again, we surrender def _run_search(self, raiseOnQE=False): url = self._nextUrl if url is None: url = self._make_search_url() if url == "done": raise StopIteration() qRes = r.get(url,timeout=self._timeout) if qRes.status_code in [429, 401]: # If Invalid API Key or exceeding quota for the API Key, change it return self._manageQuotaExcess(raiseOnQE) dta = qRes.json() if qRes.status_code != 200: raise Exception("{} {} {} {}".format("Error: ", dta['service-error']['status']['statusText'], "URL is:", url)) # Fix this # KeyError hazard: If no 'next' url is available, we need to error out anyway nxtLink = [ln for ln in dta[self._root_key]['link'] if ln['@ref'] == 'next'] if len(nxtLink) > 0: self._nextUrl = nxtLink[0]['@href'] else: self._nextUrl = "done" # Nasty? Sorry : ) return dta[self._root_key]['entry'] # Returning only the obtained results def __iter__(self): return self def next(self): return self.__next__() def __next__(self): if self._i == len(self._data): self._data = self._run_search() self._i = 0 self._i += 1 if self._apikey_return: return self._data[self._i-1], self._apiKey elif not self.apikey_return: return self._data[self._i-1] class ScopusSerialTitle(ScopusSearchQuery): _defaultParams = {'count': 100, 'view': 'CITESCORE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/serial/title" _support_pagination = False _root_key = 'serial-metadata-response' def _make_search_url(self): params = self._params defParams = self._defaultParams pSet = set(params.keys()).union(set(defParams.keys())) parameters = {key: params[key] if key in params else defParams[key] for key in pSet} if "issn" in parameters: base_url = self._baseUrl + '/issn/' + parameters['issn'] + '?' if 'title' in parameters: parameters.pop('title') parameters.pop('issn') else: base_url = self._baseUrl + '?' querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._baseUrl, querystring, '&', apiKeyString) return url class SerialTitleQuery: # Serial title search _defaultParams = {'count': 200, 'view': 'CITESCORE', 'httpAccept': 'application/json'} _baseUrl = "http://api.elsevier.com/content/serial/title?" _support_pagination = False _root_key = 'serial-metadata-response' def __init__(self, key, params, timeout=60): self._apiKey = key self._keys = None if isinstance(key, list): self._keys = key self._keyCount = 0 self._apiKey = key[0] self._state = "empty" self._params = params self._data = [] self._nextUrl = None self._i = 0 self._count = 0 self._timeout = timeout def _make_search_url(self): params = self._params pset = set(params.keys()).union(set(self._defaultParams.keys())) parameters = {key: params[key] if key in params else self._defaultParams[key] for key in pset} # make query querystring = purl.urlencode(parameters) apiKeyString = purl.urlencode({'apiKey': self._apiKey}) url = "{}{}{}{}".format(self._base_url, querystring, '&', apiKeyString) return url def _manageQuotaExcess(self, raiseOnQE=False): print("Managing quota exess...") if raiseOnQE or self._keys is None: raise Exception("QuotaExceeded - You must wait 7 days until quotas are reset") self._nextUrl = None self._keyCount = self._keyCount + 1 print("Key was: " + self._apiKey) try: self._apiKey = self._keys[self._keyCount] print("Key is: " + self._apiKey) return self._run_search() except IndexError: return self._run_search(True) # If we fail again, we surrender def _run_search(self, raiseOnQE=False): url = self._nextUrl if url is None: url = self._make_search_url() if url == "done": raise StopIteration() qRes = r.get(url, timeout=self._timeout) if qRes.status_code in [429, 401]: # If Invalid API Key or exceeding quota for the API Key, change it return self._manageQuotaExcess(raiseOnQE) dta = qRes.json() if qRes.status_code != 200: logger.info("{} {} {} {}".format("Error: ", dta['service-error']['status']['statusText'], "URL is:", url)) raise StopIteration() if 'entry' not in dta[self._root_key]: raise StopIteration() if _defaultParams['count'] <= len(dta[self._root_key]['entry']): next_url = dta[self._root_key]['link'][0]['@href'] parsed = urlparse.urlparse(next_url) parsed_query = urlparse.parse_qs(parsed.query) start = int(parsed_query['start'][0]) + int(parsed_query['count'][0]) self._nextUrl = "{0}&{1}={2}".format(self._make_search_url(), 'start', start) if start >= 10000: self._nextUrl = "done" else: self._nextUrl = "done" return dta[self._root_key]['entry'] def __iter__(self): return self def next(self): return self.__next__() def __next__(self): if self._i == len(self._data): self._data = self._run_search() self._i = 0 if len(self._data) == self._i: pass # Raise error self._i += 1 return self._data[self._i - 1]
en
0.476615
# Return (self._data[self._i-1], self._apiKey) instead of self._data[self._i-1] # If we fail again, we surrender # If Invalid API Key or exceeding quota for the API Key, change it # Fix this # KeyError hazard: If no 'next' url is available, we need to error out anyway # Nasty? Sorry : ) # Returning only the obtained results # Serial title search # make query # If we fail again, we surrender # If Invalid API Key or exceeding quota for the API Key, change it # Raise error
2.937572
3
django_smartfarm_git/main/migrations/0006_remove_temp_date.py
jyjy318/smartfarm
0
6630530
# Generated by Django 2.0.13 on 2020-09-03 13:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200903_2215'), ] operations = [ migrations.RemoveField( model_name='temp', name='date', ), ]
# Generated by Django 2.0.13 on 2020-09-03 13:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200903_2215'), ] operations = [ migrations.RemoveField( model_name='temp', name='date', ), ]
en
0.831999
# Generated by Django 2.0.13 on 2020-09-03 13:19
1.302781
1
server/grade_view/blue_prints/register.py
jw3329/grade-view
0
6630531
<filename>server/grade_view/blue_prints/register.py from flask import Blueprint, request, jsonify from flask_login import login_required, current_user from grade_view import db, app from grade_view.models import User, Course, GPA, Major register = Blueprint('register', __name__) @register.route('/gpa',methods=['GET','POST']) @login_required def profile(): if request.method == 'GET': gpas = GPA.query.filter_by(user_id=current_user.id).all() json = { 'status': True, 'info': [] } for gpa in gpas: course = gpa.course json['info'].append({ 'course': course.major.major, 'course_number': course.course_number, 'gpa': gpa.gpa }) return jsonify(json) elif request.method == 'POST': registered_data = request.get_json() print(registered_data) try: course = registered_data['course'] course_number = registered_data['course_number'] # handle course number if it is more than 3 digits if len(course_number) > 3: raise Exception('Invalid course number') gpa = registered_data['gpa'] major_id = Major.query.filter_by(major=course).first().id course_data = Course.query.filter_by(major_id=major_id).filter_by(course_number=course_number).first() # if there's no filter result, then add it if not course_data: course_data = Course(major_id,course_number) db.session.add(course_data) db.session.commit() # after commit, add gpa data grade_map = { 'A+/A': 4.00, 'A-': 3.67, 'B+': 3.33, 'B': 3.00, 'B-': 2.67, 'C+': 2.33, 'C': 2.00, 'C-': 1.67, 'D+': 1.33, 'D': 1.00, 'D-': 0.67, 'F': 0.00, } # handle error case if the grade does not belong to the category if gpa not in grade_map: raise Exception('Given grade does not belong to the grade map') gpa_data = GPA(current_user.id, course_data.id, grade_map[gpa]) db.session.add(gpa_data) db.session.commit() status = True message = 'Successfully registered gpa information' except Exception as e: status = False message = str(e) return jsonify({ 'status':status, 'message':message }) app.register_blueprint(register, url_prefix='/register')
<filename>server/grade_view/blue_prints/register.py from flask import Blueprint, request, jsonify from flask_login import login_required, current_user from grade_view import db, app from grade_view.models import User, Course, GPA, Major register = Blueprint('register', __name__) @register.route('/gpa',methods=['GET','POST']) @login_required def profile(): if request.method == 'GET': gpas = GPA.query.filter_by(user_id=current_user.id).all() json = { 'status': True, 'info': [] } for gpa in gpas: course = gpa.course json['info'].append({ 'course': course.major.major, 'course_number': course.course_number, 'gpa': gpa.gpa }) return jsonify(json) elif request.method == 'POST': registered_data = request.get_json() print(registered_data) try: course = registered_data['course'] course_number = registered_data['course_number'] # handle course number if it is more than 3 digits if len(course_number) > 3: raise Exception('Invalid course number') gpa = registered_data['gpa'] major_id = Major.query.filter_by(major=course).first().id course_data = Course.query.filter_by(major_id=major_id).filter_by(course_number=course_number).first() # if there's no filter result, then add it if not course_data: course_data = Course(major_id,course_number) db.session.add(course_data) db.session.commit() # after commit, add gpa data grade_map = { 'A+/A': 4.00, 'A-': 3.67, 'B+': 3.33, 'B': 3.00, 'B-': 2.67, 'C+': 2.33, 'C': 2.00, 'C-': 1.67, 'D+': 1.33, 'D': 1.00, 'D-': 0.67, 'F': 0.00, } # handle error case if the grade does not belong to the category if gpa not in grade_map: raise Exception('Given grade does not belong to the grade map') gpa_data = GPA(current_user.id, course_data.id, grade_map[gpa]) db.session.add(gpa_data) db.session.commit() status = True message = 'Successfully registered gpa information' except Exception as e: status = False message = str(e) return jsonify({ 'status':status, 'message':message }) app.register_blueprint(register, url_prefix='/register')
en
0.735311
# handle course number if it is more than 3 digits # if there's no filter result, then add it # after commit, add gpa data # handle error case if the grade does not belong to the category
2.915622
3
tests/beacon/test_aggregation.py
Bhargavasomu/py-evm
0
6630532
<reponame>Bhargavasomu/py-evm import pytest from hypothesis import ( given, settings, strategies as st, ) from eth._utils import bls from eth._utils.bitfield import ( get_empty_bitfield, has_voted, ) from eth.beacon.aggregation import ( aggregate_votes, verify_votes, ) @settings(max_examples=1) @given(random=st.randoms()) @pytest.mark.parametrize( ( 'votes_count' ), [ (0), (9), ], ) def test_aggregate_votes(votes_count, random, privkeys, pubkeys): bit_count = 10 pre_bitfield = get_empty_bitfield(bit_count) pre_sigs = () domain = 0 random_votes = random.sample(range(bit_count), votes_count) message = b'hello' # Get votes: (committee_index, sig, public_key) votes = [ ( committee_index, bls.sign(message, privkeys[committee_index], domain), pubkeys[committee_index], ) for committee_index in random_votes ] # Verify sigs, committee_indices = verify_votes(message, votes, domain) # Aggregate the votes bitfield, sigs = aggregate_votes( bitfield=pre_bitfield, sigs=pre_sigs, voting_sigs=sigs, voting_committee_indices=committee_indices ) try: _, _, pubs = zip(*votes) except ValueError: pubs = () voted_index = [ committee_index for committee_index in random_votes if has_voted(bitfield, committee_index) ] assert len(voted_index) == len(votes) aggregated_pubs = bls.aggregate_pubkeys(pubs) assert bls.verify(message, aggregated_pubs, sigs, domain)
import pytest from hypothesis import ( given, settings, strategies as st, ) from eth._utils import bls from eth._utils.bitfield import ( get_empty_bitfield, has_voted, ) from eth.beacon.aggregation import ( aggregate_votes, verify_votes, ) @settings(max_examples=1) @given(random=st.randoms()) @pytest.mark.parametrize( ( 'votes_count' ), [ (0), (9), ], ) def test_aggregate_votes(votes_count, random, privkeys, pubkeys): bit_count = 10 pre_bitfield = get_empty_bitfield(bit_count) pre_sigs = () domain = 0 random_votes = random.sample(range(bit_count), votes_count) message = b'hello' # Get votes: (committee_index, sig, public_key) votes = [ ( committee_index, bls.sign(message, privkeys[committee_index], domain), pubkeys[committee_index], ) for committee_index in random_votes ] # Verify sigs, committee_indices = verify_votes(message, votes, domain) # Aggregate the votes bitfield, sigs = aggregate_votes( bitfield=pre_bitfield, sigs=pre_sigs, voting_sigs=sigs, voting_committee_indices=committee_indices ) try: _, _, pubs = zip(*votes) except ValueError: pubs = () voted_index = [ committee_index for committee_index in random_votes if has_voted(bitfield, committee_index) ] assert len(voted_index) == len(votes) aggregated_pubs = bls.aggregate_pubkeys(pubs) assert bls.verify(message, aggregated_pubs, sigs, domain)
en
0.649237
# Get votes: (committee_index, sig, public_key) # Verify # Aggregate the votes
2.248288
2
problem0055.py
kmarcini/Project-Euler-Python
0
6630533
########################### # # #55 Lychrel numbers - Project Euler # https://projecteuler.net/problem=55 # # Code by <NAME> # ###########################
########################### # # #55 Lychrel numbers - Project Euler # https://projecteuler.net/problem=55 # # Code by <NAME> # ###########################
de
0.362785
########################### # # #55 Lychrel numbers - Project Euler # https://projecteuler.net/problem=55 # # Code by <NAME> # ###########################
1.126742
1
migrations/versions/e9f614a8dce6_.py
Ahmad-Zaky/fuyyr_udacity_proj
0
6630534
"""empty message Revision ID: e9f614a8dce6 Revises: <PASSWORD> Create Date: 2021-02-28 05:23:44.254402 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e9f614a8dce6' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('shows', sa.Column('venue_id', sa.Integer(), nullable=False), sa.Column('artist_id', sa.Integer(), nullable=False), sa.Column('start_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True), sa.ForeignKeyConstraint(['artist_id'], ['artists.id'], ), sa.ForeignKeyConstraint(['venue_id'], ['venues.id'], ), sa.PrimaryKeyConstraint('venue_id', 'artist_id') ) op.add_column('artists', sa.Column('created_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('artists', sa.Column('modified_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('venues', sa.Column('created_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('venues', sa.Column('modified_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('venues', 'modified_time') op.drop_column('venues', 'created_time') op.drop_column('artists', 'modified_time') op.drop_column('artists', 'created_time') op.drop_table('shows') # ### end Alembic commands ###
"""empty message Revision ID: e9f614a8dce6 Revises: <PASSWORD> Create Date: 2021-02-28 05:23:44.254402 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e9f614a8dce6' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('shows', sa.Column('venue_id', sa.Integer(), nullable=False), sa.Column('artist_id', sa.Integer(), nullable=False), sa.Column('start_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True), sa.ForeignKeyConstraint(['artist_id'], ['artists.id'], ), sa.ForeignKeyConstraint(['venue_id'], ['venues.id'], ), sa.PrimaryKeyConstraint('venue_id', 'artist_id') ) op.add_column('artists', sa.Column('created_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('artists', sa.Column('modified_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('venues', sa.Column('created_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) op.add_column('venues', sa.Column('modified_time', sa.DateTime(), server_default=sa.text('now()'), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('venues', 'modified_time') op.drop_column('venues', 'created_time') op.drop_column('artists', 'modified_time') op.drop_column('artists', 'created_time') op.drop_table('shows') # ### end Alembic commands ###
en
0.472817
empty message Revision ID: e9f614a8dce6 Revises: <PASSWORD> Create Date: 2021-02-28 05:23:44.254402 # revision identifiers, used by Alembic. # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ### # ### commands auto generated by Alembic - please adjust! ### # ### end Alembic commands ###
1.847127
2
test_flood.py
henrywall56/Lab-Group-1-U-H
0
6630535
<reponame>henrywall56/Lab-Group-1-U-H from numpy import float32 from floodsystem.flood import stations_level_over_threshold, stations_highest_rel_level from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.station import MonitoringStation def test_stations_level_over_threshold(): #checking the output of the function is as intended stations = build_station_list() update_water_levels(stations) over_threshold_list = stations_level_over_threshold(stations, tol=0.8) assert isinstance(over_threshold_list, list) for i in over_threshold_list: assert isinstance(i, tuple) assert isinstance(i[0], MonitoringStation) assert isinstance(i[1], float) def test_stations_highest_rel_level(): stations = build_station_list() update_water_levels(stations) N=10 first_10_stations = stations_highest_rel_level(stations, N) assert isinstance(first_10_stations, list) assert len(first_10_stations) == 10 for i in first_10_stations: assert isinstance(i, tuple) assert isinstance(i[0], MonitoringStation) assert isinstance(i[1], float)
from numpy import float32 from floodsystem.flood import stations_level_over_threshold, stations_highest_rel_level from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.station import MonitoringStation def test_stations_level_over_threshold(): #checking the output of the function is as intended stations = build_station_list() update_water_levels(stations) over_threshold_list = stations_level_over_threshold(stations, tol=0.8) assert isinstance(over_threshold_list, list) for i in over_threshold_list: assert isinstance(i, tuple) assert isinstance(i[0], MonitoringStation) assert isinstance(i[1], float) def test_stations_highest_rel_level(): stations = build_station_list() update_water_levels(stations) N=10 first_10_stations = stations_highest_rel_level(stations, N) assert isinstance(first_10_stations, list) assert len(first_10_stations) == 10 for i in first_10_stations: assert isinstance(i, tuple) assert isinstance(i[0], MonitoringStation) assert isinstance(i[1], float)
en
0.909578
#checking the output of the function is as intended
2.844965
3
binstar_client/inspect_package/tests/test_pypi.py
rpk101/anaconda-client
98
6630536
from __future__ import print_function, unicode_literals import os import shutil import tempfile import unittest from pprint import pprint from binstar_client.inspect_package import pypi from binstar_client.utils.test.utils import data_dir expected_package_data = {'name': 'test-package34', 'license': 'custom', 'summary': 'Python test package for binstar client'} expected_version_data = {'home_page': 'http://github.com/binstar/binstar_pypi', 'version': '0.3.1', 'description':'longer description of the package'} expected_dependencies = {'depends': [ {'name': u'python-dateutil', 'specs': []}, {'name': u'pytz', 'specs': []}, {'name': u'pyyaml', 'specs': []}, {'name': u'requests', 'specs': [(u'>=', u'2.0'), (u'<=', u'3.0')]}, ], 'extras': [{'depends': [{'name': u'argparse', 'specs': []}], 'name': u':python_version=="2.6"'}, {'depends': [{'name': u'reportlab', 'specs': [(u'>=', u'1.2')]}, {'name': u'rxp', 'specs': []}], 'name': u'PDF'}, {'depends': [{'name': u'docutils', 'specs': [(u'>=', u'0.3')]}], 'name': u'reST'}], 'has_dep_errors': False} expected_whl_dependencies = {u'depends': [{u'name': u'python-dateutil', u'specs': []}, {u'name': u'pytz', u'specs': []}, {u'name': u'pyyaml', u'specs': []}, {u'name': u'requests', u'specs': [(u'>=', u'2.0'), (u'<=', u'3.0')]}], u'environments': [{u'depends': [{u'name': u'argparse', u'specs': []}], u'name': u'python_version=="2.6"'}], u'extras': [{u'depends': [{u'name': u'reportlab', u'specs': [(u'>=', u'1.2')]}, {u'name': u'rxp', u'specs': []}, ], u'name': u'PDF'}, {u'depends': [{u'name': u'docutils', u'specs': [(u'>=', u'0.3')]}], u'name': u'reST'}], u'has_dep_errors': False} expected_egg_file_data = {'attrs': {'packagetype': 'bdist_egg', 'python_version': 'source'}, 'basename': 'test_package34-0.3.1-py2.7.egg', 'dependencies': expected_dependencies, 'platform': None} class Test(unittest.TestCase): maxDiff = None def test_sdist(self): filename = data_dir('test_package34-0.3.1.tar.gz') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'}, 'basename': 'test_package34-0.3.1.tar.gz', 'dependencies': expected_dependencies} self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_wheel(self): filename = data_dir('test_package34-0.3.1-py2-none-any.whl') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'abi': None, 'build_no': 0, 'packagetype': 'bdist_wheel', 'python_version': 'py2'}, 'basename': 'test_package34-0.3.1-py2-none-any.whl', 'dependencies': expected_whl_dependencies, 'platform': None} self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_wheel_newer_version(self): filename_whl = 'azure_cli_extension-0.2.1-py2.py3-none-any.whl' filename = data_dir(filename_whl) with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = { 'platform': None, 'basename': filename_whl, 'dependencies': { u'depends': [ {u'name': u'azure-cli-command-modules-nspkg', u'specs': [(u'>=', u'2.0.0')]}, {u'name': u'azure-cli-core', u'specs': []}, {u'name': u'pip', u'specs': []}, {u'name': u'wheel', u'specs': [(u'==', u'0.30.0')]} ], u'extras': [], u'has_dep_errors': False, u'environments': []}, u'attrs': { 'abi': None, 'packagetype': u'bdist_wheel', 'python_version': u'py2.py3', 'build_no': 0 } } expected_package_data = { u'name': 'azure-cli-extension', u'license': 'MIT', u'summary': 'Microsoft Azure Command-Line Tools Extension Command Module', } expected_version_data = { u'home_page': 'https://github.com/Azure/azure-cli', u'version': '0.2.1', u'description': u"Microsoft Azure CLI 'extension' Command Module", } self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_egg(self): filename = data_dir('test_package34-0.3.1-py2.7.egg') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_egg_file_data), set(file_data)) for key in expected_egg_file_data: self.assertEqual(expected_egg_file_data[key], file_data[key]) def test_bdist_egg_dashed_path(self): filename = data_dir('test_package34-0.3.1-py2.7.egg') tmpdir = tempfile.gettempdir() dash_count = tmpdir.count('-') if dash_count == 0: tmpdir = os.path.join(tmpdir, 'has-dash') try: os.mkdir(tmpdir) except (IOError, OSError): raise unittest.SkipTest('Cannot create temporary directory %r' % tmpdir) elif dash_count > 1: raise unittest.SkipTest('Too many dashes in temporary directory path %r' % tmpdir) try: shutil.copy(filename, tmpdir) except (IOError, OSError): raise unittest.SkipTest('Cannot copy package to temporary directory') tmpfilename = os.path.join(tmpdir, 'test_package34-0.3.1-py2.7.egg') with open(tmpfilename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(tmpfilename, fd) # If we could create this file, we ought to be able to delete it os.remove(tmpfilename) if dash_count == 0: # We created a temporary directory like /tmp/has-dash, delete it os.rmdir(tmpdir) self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_egg_file_data), set(file_data)) self.assertEqual(expected_egg_file_data['platform'], file_data['platform']) self.assertEqual(expected_egg_file_data['attrs']['python_version'], file_data['attrs']['python_version']) def test_sdist_distutils(self): filename = data_dir('test_package34-distutils-0.3.1.tar.gz') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'}, 'basename': 'test_package34-distutils-0.3.1.tar.gz', 'dependencies': {'depends': [{'name': 'requests', 'specs': [('>=', '2.0'), ('<=', '3.0')]}, {'name': 'pyyaml', 'specs': [('==', '2.0')]}, {'name': 'pytz', 'specs': []}], 'extras': [], 'has_dep_errors': False}} dexpected_package_data = expected_package_data.copy() dexpected_package_data['name'] = dexpected_package_data['name'].replace('-', '_') self.assertEqual(dexpected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
from __future__ import print_function, unicode_literals import os import shutil import tempfile import unittest from pprint import pprint from binstar_client.inspect_package import pypi from binstar_client.utils.test.utils import data_dir expected_package_data = {'name': 'test-package34', 'license': 'custom', 'summary': 'Python test package for binstar client'} expected_version_data = {'home_page': 'http://github.com/binstar/binstar_pypi', 'version': '0.3.1', 'description':'longer description of the package'} expected_dependencies = {'depends': [ {'name': u'python-dateutil', 'specs': []}, {'name': u'pytz', 'specs': []}, {'name': u'pyyaml', 'specs': []}, {'name': u'requests', 'specs': [(u'>=', u'2.0'), (u'<=', u'3.0')]}, ], 'extras': [{'depends': [{'name': u'argparse', 'specs': []}], 'name': u':python_version=="2.6"'}, {'depends': [{'name': u'reportlab', 'specs': [(u'>=', u'1.2')]}, {'name': u'rxp', 'specs': []}], 'name': u'PDF'}, {'depends': [{'name': u'docutils', 'specs': [(u'>=', u'0.3')]}], 'name': u'reST'}], 'has_dep_errors': False} expected_whl_dependencies = {u'depends': [{u'name': u'python-dateutil', u'specs': []}, {u'name': u'pytz', u'specs': []}, {u'name': u'pyyaml', u'specs': []}, {u'name': u'requests', u'specs': [(u'>=', u'2.0'), (u'<=', u'3.0')]}], u'environments': [{u'depends': [{u'name': u'argparse', u'specs': []}], u'name': u'python_version=="2.6"'}], u'extras': [{u'depends': [{u'name': u'reportlab', u'specs': [(u'>=', u'1.2')]}, {u'name': u'rxp', u'specs': []}, ], u'name': u'PDF'}, {u'depends': [{u'name': u'docutils', u'specs': [(u'>=', u'0.3')]}], u'name': u'reST'}], u'has_dep_errors': False} expected_egg_file_data = {'attrs': {'packagetype': 'bdist_egg', 'python_version': 'source'}, 'basename': 'test_package34-0.3.1-py2.7.egg', 'dependencies': expected_dependencies, 'platform': None} class Test(unittest.TestCase): maxDiff = None def test_sdist(self): filename = data_dir('test_package34-0.3.1.tar.gz') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'}, 'basename': 'test_package34-0.3.1.tar.gz', 'dependencies': expected_dependencies} self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_wheel(self): filename = data_dir('test_package34-0.3.1-py2-none-any.whl') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'abi': None, 'build_no': 0, 'packagetype': 'bdist_wheel', 'python_version': 'py2'}, 'basename': 'test_package34-0.3.1-py2-none-any.whl', 'dependencies': expected_whl_dependencies, 'platform': None} self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_wheel_newer_version(self): filename_whl = 'azure_cli_extension-0.2.1-py2.py3-none-any.whl' filename = data_dir(filename_whl) with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = { 'platform': None, 'basename': filename_whl, 'dependencies': { u'depends': [ {u'name': u'azure-cli-command-modules-nspkg', u'specs': [(u'>=', u'2.0.0')]}, {u'name': u'azure-cli-core', u'specs': []}, {u'name': u'pip', u'specs': []}, {u'name': u'wheel', u'specs': [(u'==', u'0.30.0')]} ], u'extras': [], u'has_dep_errors': False, u'environments': []}, u'attrs': { 'abi': None, 'packagetype': u'bdist_wheel', 'python_version': u'py2.py3', 'build_no': 0 } } expected_package_data = { u'name': 'azure-cli-extension', u'license': 'MIT', u'summary': 'Microsoft Azure Command-Line Tools Extension Command Module', } expected_version_data = { u'home_page': 'https://github.com/Azure/azure-cli', u'version': '0.2.1', u'description': u"Microsoft Azure CLI 'extension' Command Module", } self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) def test_bdist_egg(self): filename = data_dir('test_package34-0.3.1-py2.7.egg') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_egg_file_data), set(file_data)) for key in expected_egg_file_data: self.assertEqual(expected_egg_file_data[key], file_data[key]) def test_bdist_egg_dashed_path(self): filename = data_dir('test_package34-0.3.1-py2.7.egg') tmpdir = tempfile.gettempdir() dash_count = tmpdir.count('-') if dash_count == 0: tmpdir = os.path.join(tmpdir, 'has-dash') try: os.mkdir(tmpdir) except (IOError, OSError): raise unittest.SkipTest('Cannot create temporary directory %r' % tmpdir) elif dash_count > 1: raise unittest.SkipTest('Too many dashes in temporary directory path %r' % tmpdir) try: shutil.copy(filename, tmpdir) except (IOError, OSError): raise unittest.SkipTest('Cannot copy package to temporary directory') tmpfilename = os.path.join(tmpdir, 'test_package34-0.3.1-py2.7.egg') with open(tmpfilename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(tmpfilename, fd) # If we could create this file, we ought to be able to delete it os.remove(tmpfilename) if dash_count == 0: # We created a temporary directory like /tmp/has-dash, delete it os.rmdir(tmpdir) self.assertEqual(expected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_egg_file_data), set(file_data)) self.assertEqual(expected_egg_file_data['platform'], file_data['platform']) self.assertEqual(expected_egg_file_data['attrs']['python_version'], file_data['attrs']['python_version']) def test_sdist_distutils(self): filename = data_dir('test_package34-distutils-0.3.1.tar.gz') with open(filename, 'rb') as fd: package_data, version_data, file_data = pypi.inspect_pypi_package(filename, fd) expected_file_data = {'attrs': {'packagetype': 'sdist', 'python_version': 'source'}, 'basename': 'test_package34-distutils-0.3.1.tar.gz', 'dependencies': {'depends': [{'name': 'requests', 'specs': [('>=', '2.0'), ('<=', '3.0')]}, {'name': 'pyyaml', 'specs': [('==', '2.0')]}, {'name': 'pytz', 'specs': []}], 'extras': [], 'has_dep_errors': False}} dexpected_package_data = expected_package_data.copy() dexpected_package_data['name'] = dexpected_package_data['name'].replace('-', '_') self.assertEqual(dexpected_package_data, package_data) self.assertEqual(expected_version_data, version_data) self.assertEqual(set(expected_file_data), set(file_data)) for key in expected_file_data: print(expected_file_data[key]) print(file_data[key]) self.assertEqual(expected_file_data[key], file_data[key]) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
en
0.897283
# If we could create this file, we ought to be able to delete it # We created a temporary directory like /tmp/has-dash, delete it # import sys;sys.argv = ['', 'Test.testName']
1.909
2
uspto_tools/parse/__init__.py
clicumu/uspto-tools
0
6630537
<reponame>clicumu/uspto-tools from . import aps, patent, patft_html, sgml, xml
from . import aps, patent, patft_html, sgml, xml
none
1
1.057074
1
src/tools.py/mapKeyboard.py
Mambix/Keyduino
3
6630538
<filename>src/tools.py/mapKeyboard.py #!/usr/bin/env python # Filename: mapKeyboard.py ''' Created on 24 Jul 2016 @author: <EMAIL> ''' import serial import json keys = {} if __name__ == '__main__': ser = serial.Serial('COM9', 115200) cnt = 0 try: if ser.is_open == False: ser.open() while cnt<100: ln1 = ser.readline() ln2 = ser.readline() # ln3 = ser.readline() # ln4 = ser.readline() keys['KEY_%0.2X' % cnt] = [ln1, ln2] # , ln3, ln4] cnt = cnt + 1 except Exception as msg: print(msg) if ser.is_open == True: ser.close() with open('%s_decoded.json' % 'PK1306R1A08', 'w') as f: f.write(json.dumps(keys, indent=2, sort_keys=True))
<filename>src/tools.py/mapKeyboard.py #!/usr/bin/env python # Filename: mapKeyboard.py ''' Created on 24 Jul 2016 @author: <EMAIL> ''' import serial import json keys = {} if __name__ == '__main__': ser = serial.Serial('COM9', 115200) cnt = 0 try: if ser.is_open == False: ser.open() while cnt<100: ln1 = ser.readline() ln2 = ser.readline() # ln3 = ser.readline() # ln4 = ser.readline() keys['KEY_%0.2X' % cnt] = [ln1, ln2] # , ln3, ln4] cnt = cnt + 1 except Exception as msg: print(msg) if ser.is_open == True: ser.close() with open('%s_decoded.json' % 'PK1306R1A08', 'w') as f: f.write(json.dumps(keys, indent=2, sort_keys=True))
en
0.29883
#!/usr/bin/env python # Filename: mapKeyboard.py Created on 24 Jul 2016 @author: <EMAIL> # ln3 = ser.readline() # ln4 = ser.readline() # , ln3, ln4]
2.597744
3
test_pypasshash.py
NeverMine17/pypasshash
0
6630539
<gh_stars>0 import unittest import pypasshash tests_version_1 = [ ['test123', 'asd', 'w9XHj6TXSSC4'], ['qwerty', 'qwerty', 't8BvIfZIqw8i'], ['123', '123', 'd7JCE8mdIksv'], ['12345', '12345', 'f8Ew2fPdXNDB'], ['5agRrdKKPFWkT3pj5dwNddyA', 'jbuHzWA4ch7h73KugVHtqv6r', 'q1RjFnRTw2gq'], ['3VaY2WPxpfZU6z25MWhdexsK', 'V<KEY>', 'h3CUKhIANOS3'], ['NT2Sv5q7Ne4JVVyB4J8X3epX', 'bzBsz5LMtYdjK8Sv7Ntw72KS', 'b5FbaC4bCT5a'], ['eXsAeVTEBf9ZdqCnyfSfZYSy', '3afGM8nZpafjQxyFYS4bZjaG', 'w7JNYoywZIlS'] ] tests_version_2 = [ ['test123', 'asd', 'u8NFNm8i4y0I'], ['qwerty', 'qwerty', 'n7XKKsaXAYnk'], ['123', '123', 'j8CC1DMjHpuJ'], ['12345', '12345', 'v6ZawS4UvMTr'], ['5agRrdKKPFWkT3pj5dwNddyA', 'jbuHzWA4ch7h73KugVHtqv6r', 'l9Q920XQlkk9'], ['3VaY2WPxpfZU6z25MWhdexsK', '<KEY>', 'j9HCjIiJYUoE'], ['NT2Sv5q7Ne4JVVyB4J8X3epX', 'bzBsz5LMtYdjK8Sv7Ntw72KS', 'n0PATXNeKgnG'], ['eXsAeVTEBf9ZdqCnyfSfZYSy', '3afGM8nZpafjQxyFYS4bZjaG', 'v5Nd1kEo4yvR'] ] class PassHashTest(unittest.TestCase): def test_version_2(self): for test in tests_version_2: self.assertEqual(pypasshash.get_pass(test[0], test[1], 2), test[2]) def test_version_1(self): for test in tests_version_1: self.assertEqual(pypasshash.get_pass(test[0], test[1], 1), test[2]) if __name__ == '__main__': unittest.main()
import unittest import pypasshash tests_version_1 = [ ['test123', 'asd', 'w9XHj6TXSSC4'], ['qwerty', 'qwerty', 't8BvIfZIqw8i'], ['123', '123', 'd7JCE8mdIksv'], ['12345', '12345', 'f8Ew2fPdXNDB'], ['5agRrdKKPFWkT3pj5dwNddyA', 'jbuHzWA4ch7h73KugVHtqv6r', 'q1RjFnRTw2gq'], ['3VaY2WPxpfZU6z25MWhdexsK', 'V<KEY>', 'h3CUKhIANOS3'], ['NT2Sv5q7Ne4JVVyB4J8X3epX', 'bzBsz5LMtYdjK8Sv7Ntw72KS', 'b5FbaC4bCT5a'], ['eXsAeVTEBf9ZdqCnyfSfZYSy', '3afGM8nZpafjQxyFYS4bZjaG', 'w7JNYoywZIlS'] ] tests_version_2 = [ ['test123', 'asd', 'u8NFNm8i4y0I'], ['qwerty', 'qwerty', 'n7XKKsaXAYnk'], ['123', '123', 'j8CC1DMjHpuJ'], ['12345', '12345', 'v6ZawS4UvMTr'], ['5agRrdKKPFWkT3pj5dwNddyA', 'jbuHzWA4ch7h73KugVHtqv6r', 'l9Q920XQlkk9'], ['3VaY2WPxpfZU6z25MWhdexsK', '<KEY>', 'j9HCjIiJYUoE'], ['NT2Sv5q7Ne4JVVyB4J8X3epX', 'bzBsz5LMtYdjK8Sv7Ntw72KS', 'n0PATXNeKgnG'], ['eXsAeVTEBf9ZdqCnyfSfZYSy', '3afGM8nZpafjQxyFYS4bZjaG', 'v5Nd1kEo4yvR'] ] class PassHashTest(unittest.TestCase): def test_version_2(self): for test in tests_version_2: self.assertEqual(pypasshash.get_pass(test[0], test[1], 2), test[2]) def test_version_1(self): for test in tests_version_1: self.assertEqual(pypasshash.get_pass(test[0], test[1], 1), test[2]) if __name__ == '__main__': unittest.main()
none
1
1.867559
2
VelodyneHDL/python/veloview/applogic.py
yajin1126/C-Users-yajin-Documents-veloview
0
6630540
<filename>VelodyneHDL/python/veloview/applogic.py # Copyright 2013 Velodyne Acoustics, 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 os import csv import datetime import time import math import paraview.simple as smp from paraview import servermanager from paraview import vtk import PythonQt from PythonQt import QtCore, QtGui from vtkIOXMLPython import vtkXMLPolyDataWriter import kiwiviewerExporter import gridAdjustmentDialog import planefit from PythonQt.paraview import vvCalibrationDialog, vvCropReturnsDialog, vvSelectFramesDialog from VelodyneHDLPluginPython import vtkVelodyneHDLReader _repCache = {} SAMPLE_PROCESSING_MODE = False def cachedGetRepresentation(src, view): try: return _repCache[(src, view)] except KeyError: rep = smp.GetRepresentation(src, view) _repCache[(src, view)] = rep return rep class AppLogic(object): def __init__(self): self.playing = False self.playDirection = 1 self.seekPlayDirection = 1 self.seekPlay = False self.targetFps = 30 self.renderIsPending = False self.createStatusBarWidgets() self.setupTimers() self.mousePressed = False mainView = smp.GetActiveView() views = smp.GetRenderViews() otherViews = [v for v in views if v != mainView] assert len(otherViews) == 1 overheadView = otherViews[0] self.mainView = mainView self.overheadView = overheadView self.transformMode = 0 self.relativeTransform = False self.reader = None self.position = (None, None, None) self.sensor = None self.fps = [0,0] def setupTimers(self): self.playTimer = QtCore.QTimer() self.playTimer.setSingleShot(True) self.playTimer.connect('timeout()', onPlayTimer) self.seekTimer = QtCore.QTimer() self.seekTimer.setSingleShot(True) self.seekTimer.connect('timeout()', seekPressTimeout) self.renderTimer = QtCore.QTimer() self.renderTimer.setSingleShot(True) self.renderTimer.connect('timeout()', forceRender) def createStatusBarWidgets(self): self.logoLabel = QtGui.QLabel() self.logoLabel.setPixmap(QtGui.QPixmap(":/VelodyneHDLPlugin/velodyne_logo.png")) self.logoLabel.setScaledContents(True) self.filenameLabel = QtGui.QLabel() self.statusLabel = QtGui.QLabel() self.timeLabel = QtGui.QLabel() class IconPaths(object): trailingFrames = ':/VelodyneHDLPlugin/trailingframes.png' play = ':/VelodyneHDLPlugin/media-playback-start.png' pause =':/VelodyneHDLPlugin/media-playback-pause.png' seekForward = ':/VelodyneHDLPlugin/media-seek-forward.png' seekForward2x = ':/VelodyneHDLPlugin/media-seek-forward-2x.png' seekForwardHalfx = ':/VelodyneHDLPlugin/media-seek-forward-0.5x.png' seekForwardQuarterx = ':/VelodyneHDLPlugin/media-seek-forward-0.25x.png' seekForward3x = ':/VelodyneHDLPlugin/media-seek-forward-3x.png' seekBackward = ':/VelodyneHDLPlugin/media-seek-backward.png' seekBackward2x = ':/VelodyneHDLPlugin/media-seek-backward-2x.png' seekBackward3x = ':/VelodyneHDLPlugin/media-seek-backward-3x.png' seekBackwardHalfx = ':/VelodyneHDLPlugin/media-seek-backward-0.5x.png' seekBackwardQuarterx = ':/VelodyneHDLPlugin/media-seek-backward-0.25x.png' def hasArrayName(sourceProxy, arrayName): ''' Returns True if the data has non-zero points and has a point data attribute with the given arrayName. ''' info = sourceProxy.GetDataInformation().DataInformation if info.GetNumberOfPoints() == 0: return False info = info.GetAttributeInformation(0) for i in xrange(info.GetNumberOfArrays()): if info.GetArrayInformation(i).GetName() == arrayName: return True return False def openData(filename): close() reader = smp.OpenDataFile(filename, guiName='Data') if not reader: return rep = smp.Show(reader) rep.InterpolateScalarsBeforeMapping = 0 setDefaultLookupTables(reader) colorByIntensity(reader) showSourceInSpreadSheet(reader) smp.GetActiveView().ViewTime = 0.0 app.reader = reader app.filenameLabel.setText('File: %s' % os.path.basename(filename)) updateSliderTimeRange() enablePlaybackActions() enableSaveActions() addRecentFile(filename) app.actions['actionSavePCAP'].setEnabled(False) app.actions['actionChoose_Calibration_File'].setEnabled(False) app.actions['actionCropReturns'].setEnabled(False) app.actions['actionRecord'].setEnabled(False) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True resetCamera() def planeFit(): planefit.fitPlane() def setDefaultLookupTables(sourceProxy): # LUT for 'intensity' smp.GetLookupTableForArray( 'intensity', 1, ScalarRangeInitialized=1.0, ColorSpace='HSV', RGBPoints=[0.0, 0.0, 0.0, 1.0, 100.0, 1.0, 1.0, 0.0, 256.0, 1.0, 0.0, 0.0]) # LUT for 'dual_distance' smp.GetLookupTableForArray( 'dual_distance', 1, InterpretValuesAsCategories=True, NumberOfTableValues=3, RGBPoints=[-1.0, 0.1, 0.5, 0.7, 0.0, 0.9, 0.9, 0.9, +1.0, 0.8, 0.2, 0.3], Annotations=['-1', 'near', '0', 'dual', '1', 'far']) # LUT for 'dual_intensity' smp.GetLookupTableForArray( 'dual_intensity', 1, InterpretValuesAsCategories=True, NumberOfTableValues=3, RGBPoints=[-1.0, 0.5, 0.2, 0.8, 0.0, 0.6, 0.6, 0.6, +1.0, 1.0, 0.9, 0.4], Annotations=['-1', 'low', '0', 'dual', '1', 'high']) def colorByIntensity(sourceProxy): if not hasArrayName(sourceProxy, 'intensity'): return False setDefaultLookupTables(sourceProxy) rep = smp.GetDisplayProperties(sourceProxy) rep.ColorArrayName = 'intensity' rep.LookupTable = smp.GetLookupTableForArray('intensity', 1) return True def getTimeStamp(): format = '%Y-%m-%d-%H-%M-%S' return datetime.datetime.now().strftime(format) def getReaderFileName(): filename = getReader().FileName return filename[0] if isinstance(filename, servermanager.FileNameProperty) else filename def getDefaultSaveFileName(extension, suffix='', appendFrameNumber=False): sensor = getSensor() reader = getReader() if sensor: nchannels = sensor.GetPropertyValue('NumberOfChannels') base = 'HDL-' if nchannels <= 16: base = 'VLP-' sensortype = base + str(nchannels) return '%s_Velodyne-%s-Data.%s' % (getTimeStamp(), sensortype, extension) if reader: basename = os.path.splitext(os.path.basename(getReaderFileName()))[0] if appendFrameNumber: suffix = '%s (Frame %04d)' % (suffix, int(app.scene.AnimationTime)) return '%s%s.%s' % (basename, suffix, extension) def chooseCalibration(): class Calibration(object): def __init__(self, dialog): self.calibrationFile = dialog.selectedCalibrationFile() self.gpsYaw = dialog.gpsYaw() self.gpsRoll = dialog.gpsRoll() self.gpsPitch = dialog.gpsPitch() self.sensorTransform = vtk.vtkTransform() qm = dialog.sensorTransform() vm = vtk.vtkMatrix4x4() for row in xrange(4): vm.SetElement(row, 0, qm.row(row).x()) vm.SetElement(row, 1, qm.row(row).y()) vm.SetElement(row, 2, qm.row(row).z()) vm.SetElement(row, 3, qm.row(row).w()) self.sensorTransform.SetMatrix(vm) dialog = vvCalibrationDialog(getMainWindow()) if not dialog.exec_(): return None return Calibration(dialog) def openSensor(): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform close() sensor = smp.VelodyneHDLSource(guiName='Data', CalibrationFile=calibrationFile, CacheSize=100) sensor.GetClientSideObject().SetSensorTransform(sensorTransform) sensor.UpdatePipeline() sensor.Start() if SAMPLE_PROCESSING_MODE: processor = smp.ProcessingSample(sensor) smp.GetActiveView().ViewTime = 0.0 app.sensor = sensor app.colorByInitialized = False app.filenameLabel.setText('Live sensor stream.') enablePlaybackActions() enableSaveActions() onCropReturns(False) # Dont show the dialog just restore settings onLaserSelection(False) rep = smp.Show(sensor) rep.InterpolateScalarsBeforeMapping = 0 if SAMPLE_PROCESSING_MODE: prep = smp.Show(processor) smp.Render() showSourceInSpreadSheet(sensor) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True play() def openPCAP(filename, positionFilename=None): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform close() def onProgressEvent(o, e): PythonQt.QtGui.QApplication.instance().processEvents() progressDialog = QtGui.QProgressDialog('Reading packet file...', '', 0, 0, getMainWindow()) progressDialog.setCancelButton(None) progressDialog.setModal(True) progressDialog.show() handler = servermanager.ActiveConnection.Session.GetProgressHandler() handler.PrepareProgress() freq = handler.GetProgressFrequency() handler.SetProgressFrequency(0.05) tag = handler.AddObserver('ProgressEvent', onProgressEvent) # construct the reader, this calls UpdateInformation on the # reader which scans the pcap file and emits progress events reader = smp.VelodyneHDLReader(guiName='Data', FileName=filename, CalibrationFile=calibrationFile, ApplyTransform=(app.transformMode > 0), NumberOfTrailingFrames=app.trailingFramesSpinBox.value, PointsSkip=app.trailingFramesSpinBox.value) app.reader = reader app.filenameLabel.setText('File: %s' % os.path.basename(filename)) onCropReturns(False) # Dont show the dialog just restore settings onLaserSelection(False) reader.GetClientSideObject().SetSensorTransform(sensorTransform) if SAMPLE_PROCESSING_MODE: processor = smp.ProcessingSample(reader) handler.RemoveObserver(tag) handler.SetProgressFrequency(freq) progressDialog.close() smp.GetActiveView().ViewTime = 0.0 rep = smp.Show(reader) if SAMPLE_PROCESSING_MODE: prep = smp.Show(processor) app.scene.UpdateAnimationUsingDataTimeSteps() # update overhead view smp.SetActiveView(app.overheadView) if positionFilename is None: posreader = smp.VelodyneHDLPositionReader(guiName="Position", FileName=filename) else: posreader = smp.ApplanixPositionReader(guiName="Position", FileName=positionFilename) posreader.BaseYaw = calibration.gpsYaw posreader.BaseRoll = calibration.gpsRoll posreader.BasePitch = calibration.gpsPitch smp.Show(posreader) # Create a sphere glyph g = smp.Sphere() g.Radius = 5.0 smp.Show(g) if posreader.GetClientSideObject().GetOutput().GetNumberOfPoints(): reader.GetClientSideObject().SetInterpolator( posreader.GetClientSideObject().GetInterpolator()) smp.Render(app.overheadView) app.overheadView.ResetCamera() trange = posreader.GetPointDataInformation().GetArray('time').GetRange() # By construction time zero is at position 0,0,0 # Setup scalar bar rep = smp.GetDisplayProperties(posreader) rep.ColorArrayName = 'time' rgbPoints = [trange[0], 0.0, 0.0, 1.0, trange[1], 1.0, 0.0, 0.0] rep.LookupTable = smp.GetLookupTableForArray('time', 1, RGBPoints=rgbPoints, ScalarRangeInitialized=1.0) sb = smp.CreateScalarBar(LookupTable=rep.LookupTable, Title='Time') sb.Orientation = 'Horizontal' sb.Position, sb.Position2 = [.1, .05], [.8, .02] app.overheadView.Representations.append(sb) app.position = (posreader, None, g) smp.Render(app.overheadView) else: if positionFilename is not None: QtGui.QMessageBox.warning(getMainWindow(), 'Georeferncing data invalid', 'File %s is not supported' % positionFilename) smp.Delete(posreader) smp.SetActiveView(app.mainView) smp.SetActiveSource(reader) rep.InterpolateScalarsBeforeMapping = 0 setDefaultLookupTables(reader) colorByIntensity(reader) showSourceInSpreadSheet(reader) updateSliderTimeRange() updatePosition() enablePlaybackActions() enableSaveActions() addRecentFile(filename) app.actions['actionRecord'].setEnabled(False) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True resetCamera() def hideMeasurementGrid(): rep = smp.GetDisplayProperties(app.grid) rep.Visibility = 0 smp.Render() def showMeasurementGrid(): rep = smp.GetDisplayProperties(app.grid) rep.Visibility = 1 smp.Render() # Start Functions related to ruler def createRuler(): pxm = servermanager.ProxyManager() distancerep = pxm.NewProxy('representations', 'DistanceWidgetRepresentation') distancerepeasy = servermanager._getPyProxy(distancerep) smp.GetActiveView().Representations.append(distancerepeasy) distancerepeasy.Visibility = False smp.Render() return distancerepeasy def hideRuler(): app.ruler.Visibility = False smp.Render() def showRuler(): app.ruler.Visibility = True smp.Render() def getPointFromCoordinate(coord, midPlaneDistance = 0.5): assert len(coord) == 2 windowHeight = smp.GetActiveView().ViewSize[1] displayPoint = [coord[0], windowHeight - coord[1], midPlaneDistance] renderer = smp.GetActiveView().GetRenderer() renderer.SetDisplayPoint(displayPoint) renderer.DisplayToWorld() world1 = renderer.GetWorldPoint() return world1[:3] def toggleRulerContext(): measurmentState = app.actions['actionMeasure'].isChecked() mW = getMainWindow() vtkW = mW.findChild('pqQVTKWidget') if measurmentState == True: vtkW.connect('mouseEvent(QMouseEvent*)', setRulerCoordinates) elif measurmentState == False: vtkW.disconnect('mouseEvent(QMouseEvent*)', setRulerCoordinates) app.mousePressed = False hideRuler() def setRulerCoordinates(mouseEvent): pqView = smp.GetActiveView() rW = pqView.GetRenderWindow() windowInteractor = rW.GetInteractor() currentMouseState = mouseEvent.buttons() currentKeyboardState = mouseEvent.modifiers() if currentMouseState == 1: #Left button pressed if app.mousePressed == False: #For the first time if currentKeyboardState == 67108864: #Control key pressed app.mousePressed = True app.ruler.Point1WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) windowInteractor.Disable() elif app.mousePressed == True: #Not for the first time app.ruler.Point2WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) showRuler() smp.Render() elif currentMouseState == 0: #Left button released windowInteractor.Enable() if app.mousePressed == True: #For the first time app.mousePressed = False app.ruler.Point2WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) showRuler() smp.Render() # End Functions related to ruler def rotateCSVFile(filename): # read the csv file, move the last 3 columns to the # front, and then overwrite the file with the result csvFile = open(filename, 'rb') reader = csv.reader(csvFile, quoting=csv.QUOTE_NONNUMERIC) rows = [row[-3:] + row[:-3] for row in reader] csvFile.close() writer = csv.writer(open(filename, 'wb'), quoting=csv.QUOTE_NONNUMERIC, delimiter=',') writer.writerows(rows) def savePositionCSV(filename): w = smp.CreateWriter(filename, getPosition()) w.Precision = 16 w.FieldAssociation = 'Points' w.UpdatePipeline() smp.Delete(w) def saveCSVCurrentFrame(filename): w = smp.CreateWriter(filename, smp.GetActiveSource()) w.Precision = 16 w.FieldAssociation = 'Points' w.UpdatePipeline() smp.Delete(w) rotateCSVFile(filename) def saveLASFrames(filename, first, last, transform): reader = getReader().GetClientSideObject() position = getPosition().GetClientSideObject().GetOutput() PythonQt.paraview.pqVelodyneManager.saveFramesToLAS( reader, position, first, last, filename, transform) def saveLASCurrentFrame(filename, transform): t = app.scene.AnimationTime saveLASFrames(filename, t, t, transform) def saveAllFrames(filename, saveFunction): saveFunction(filename, getCurrentTimesteps()) def saveFrameRange(filename, frameStart, frameStop, saveFunction): timesteps = range(frameStart, frameStop+1) saveFunction(filename, timesteps) def saveCSV(filename, timesteps): tempDir = kiwiviewerExporter.tempfile.mkdtemp() basenameWithoutExtension = os.path.splitext(os.path.basename(filename))[0] outDir = os.path.join(tempDir, basenameWithoutExtension) filenameTemplate = os.path.join(outDir, basenameWithoutExtension + ' (Frame %04d).csv') os.makedirs(outDir) writer = smp.CreateWriter('tmp.csv', getSensor() or getReader()) writer.FieldAssociation = 'Points' writer.Precision = 16 for t in timesteps: app.scene.AnimationTime = t writer.FileName = filenameTemplate % t writer.UpdatePipeline() rotateCSVFile(writer.FileName) smp.Delete(writer) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def saveLAS(filename, timesteps, transform): tempDir = kiwiviewerExporter.tempfile.mkdtemp() basenameWithoutExtension = os.path.splitext(os.path.basename(filename))[0] outDir = os.path.join(tempDir, basenameWithoutExtension) filenameTemplate = os.path.join(outDir, basenameWithoutExtension + ' (Frame %04d).csv') os.makedirs(outDir) for t in sorted(timesteps): saveLASFrames(filenameTemplate % t, t, t, transform) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def getTimeStamp(): format = '%Y-%m-%d-%H-%M-%S' return datetime.datetime.now().strftime(format) def getSaveFileName(title, extension, defaultFileName=None): settings = getPVSettings() defaultDir = settings.value('VelodyneHDLPlugin/OpenData/DefaultDir', QtCore.QDir.homePath()) defaultFileName = defaultDir if not defaultFileName else os.path.join(defaultDir, defaultFileName) nativeDialog = 0 if app.actions['actionNative_File_Dialogs'].isChecked() else QtGui.QFileDialog.DontUseNativeDialog filters = '%s (*.%s)' % (extension, extension) selectedFilter = '*.%s' % extension fileName = QtGui.QFileDialog.getSaveFileName(getMainWindow(), title, defaultFileName, filters, selectedFilter, nativeDialog) if fileName: settings.setValue('VelodyneHDLPlugin/OpenData/DefaultDir', QtCore.QFileInfo(fileName).absoluteDir().absolutePath()) return fileName def restoreNativeFileDialogsAction(): settings = getPVSettings() app.actions['actionNative_File_Dialogs'].setChecked(int(settings.value('VelodyneHDLPlugin/NativeFileDialogs', 1))) def onNativeFileDialogsAction(): settings = getPVSettings() defaultDir = settings.setValue('VelodyneHDLPlugin/NativeFileDialogs', int(app.actions['actionNative_File_Dialogs'].isChecked())) def getFrameSelectionFromUser(frameStrideVisibility=False, framePackVisibility=False, frameTransformVisibility=False): class FrameOptions(object): pass dialog = PythonQt.paraview.vvSelectFramesDialog(getMainWindow()) dialog.frameMinimum = app.scene.StartTime dialog.frameMaximum = app.scene.EndTime dialog.frameStrideVisibility = frameStrideVisibility dialog.framePackVisibility = framePackVisibility dialog.frameTransformVisibility = frameTransformVisibility dialog.restoreState() if not dialog.exec_(): return None frameOptions = FrameOptions() frameOptions.mode = dialog.frameMode frameOptions.start = dialog.frameStart frameOptions.stop = dialog.frameStop frameOptions.stride = dialog.frameStride frameOptions.pack = dialog.framePack frameOptions.transform = dialog.frameTransform dialog.setParent(None) return frameOptions def onSaveCSV(): frameOptions = getFrameSelectionFromUser() if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: fileName = getSaveFileName('Save CSV', 'csv', getDefaultSaveFileName('csv', appendFrameNumber=True)) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveCSVCurrentFrame(fileName) setTransformMode(oldTransform) else: fileName = getSaveFileName('Save CSV (to zip file)', 'zip', getDefaultSaveFileName('zip')) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) if frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: saveAllFrames(fileName, saveCSV) else: start = frameOptions.start stop = frameOptions.stop saveFrameRange(fileName, start, stop, saveCSV) setTransformMode(oldTransform) def onSavePosition(): fileName = getSaveFileName('Save CSV', 'csv', getDefaultSaveFileName('csv', '-position')) if fileName: savePositionCSV(fileName) def onSaveLAS(): frameOptions = getFrameSelectionFromUser(framePackVisibility=True, frameTransformVisibility=False) if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: frameOptions.start = frameOptions.stop = app.scene.AnimationTime elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: frameOptions.start = int(app.scene.StartTime) frameOptions.stop = int(app.scene.EndTime) if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: fileName = getSaveFileName('Save LAS', 'las', getDefaultSaveFileName('las', appendFrameNumber=True)) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveLASCurrentFrame(fileName, frameOptions.transform) setTransformMode(oldTransform) elif frameOptions.pack == vvSelectFramesDialog.FILE_PER_FRAME: fileName = getSaveFileName('Save LAS (to zip file)', 'zip', getDefaultSaveFileName('zip')) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) def saveTransformedLAS(filename, timesteps): saveLAS(filename, timesteps, frameOptions.transform) if frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: saveAllFrames(fileName, saveTransformedLAS) else: start = frameOptions.start stop = frameOptions.stop saveFrameRange(fileName, start, stop, saveTransformedLAS) setTransformMode(oldTransform) else: suffix = ' (Frame %d to %d)' % (frameOptions.start, frameOptions.stop) defaultFileName = getDefaultSaveFileName('las', suffix=suffix) fileName = getSaveFileName('Save LAS', 'las', defaultFileName) if not fileName: return oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveLASFrames(fileName, frameOptions.start, frameOptions.stop, frameOptions.transform) setTransformMode(oldTransform) def onSavePCAP(): frameOptions = getFrameSelectionFromUser(frameTransformVisibility=False) if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: frameOptions.start = frameOptions.stop = app.scene.AnimationTime elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: frameOptions.start = int(app.scene.StartTime) frameOptions.stop = int(app.scene.EndTime) defaultFileName = getDefaultSaveFileName('pcap', suffix=' (Frame %d to %d)' % (frameOptions.start, frameOptions.stop)) fileName = getSaveFileName('Save PCAP', 'pcap', defaultFileName) if not fileName: return PythonQt.paraview.pqVelodyneManager.saveFramesToPCAP(getReader().SMProxy, frameOptions.start, frameOptions.stop, fileName) def onSaveScreenshot(): fileName = getSaveFileName('Save Screenshot', 'png', getDefaultSaveFileName('png', appendFrameNumber=True)) if fileName: saveScreenshot(fileName) def onKiwiViewerExport(): frameOptions = getFrameSelectionFromUser(frameStrideVisibility=True, frameTransformVisibility=False) if frameOptions is None: return defaultFileName = getDefaultSaveFileName('zip', suffix=' (KiwiViewer)') fileName = getSaveFileName('Export To KiwiViewer', 'zip', defaultFileName) if not fileName: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: timesteps = [app.scene.AnimationTime] elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: timesteps = range(int(app.scene.StartTime), int(app.scene.EndTime) + 1, frameOptions.stride) else: timesteps = range(frameOptions.start, frameOptions.stop+1, frameOptions.stride) saveToKiwiViewer(fileName, timesteps) def saveToKiwiViewer(filename, timesteps): tempDir = kiwiviewerExporter.tempfile.mkdtemp() outDir = os.path.join(tempDir, os.path.splitext(os.path.basename(filename))[0]) os.makedirs(outDir) filenames = exportToDirectory(outDir, timesteps) kiwiviewerExporter.writeJsonData(outDir, smp.GetActiveView(), smp.GetDisplayProperties(), filenames) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def exportToDirectory(outDir, timesteps): filenames = [] alg = smp.GetActiveSource().GetClientSideObject() writer = vtkXMLPolyDataWriter() writer.SetDataModeToAppended() writer.EncodeAppendedDataOff() writer.SetCompressorTypeToZLib() for t in timesteps: filename = 'frame_%04d.vtp' % t filenames.append(filename) app.scene.AnimationTime = t polyData = vtk.vtkPolyData() polyData.ShallowCopy(alg.GetOutput()) writer.SetInputData(polyData) writer.SetFileName(os.path.join(outDir, filename)) writer.Update() return filenames def getVersionString(): return QtGui.QApplication.instance().applicationVersion def onDeveloperGuide(): basePath = PythonQt.QtGui.QApplication.instance().applicationDirPath() paths = ['../Resources/VeloView_Developer_Guide.pdf'] for path in paths: filename = os.path.join(basePath, path) if os.path.isfile(filename): QtGui.QDesktopServices.openUrl(QtCore.QUrl('file:///%s' % filename, QtCore.QUrl.TolerantMode)) def onUserGuide(): basePath = PythonQt.QtGui.QApplication.instance().applicationDirPath() paths = ['../Resources/VeloView_User_Guide.pdf'] for path in paths: filename = os.path.join(basePath, path) if os.path.isfile(filename): QtGui.QDesktopServices.openUrl(QtCore.QUrl('file:///%s' % filename, QtCore.QUrl.TolerantMode)) def onAbout(): title = 'About VeloView' text = '''<h1>VeloView %s</h1><br/>Copyright (c) 2013, <NAME><br /> Sample Data Repository: <a href=http://midas3.kitware.com/midas/community/29>http://midas3.kitware.com/midas/community/29</a>'''% getVersionString() QtGui.QMessageBox.about(getMainWindow(), title, text) def close(): stop() hideRuler() unloadData() smp.Render(app.overheadView) app.scene.AnimationTime = 0 app.reader = None app.sensor = None smp.HideUnusedScalarBars() resetCameraToForwardView() app.filenameLabel.setText('') app.statusLabel.setText('') app.timeLabel.setText('') updateSliderTimeRange() disablePlaybackActions() disableSaveActions() app.actions['actionRecord'].setChecked(False) app.actions['actionDualReturnModeDual'].setChecked(True) app.actions['actionDualReturnModeDual'].enabled = False app.actions['actionDualReturnDistanceNear'].enabled = False app.actions['actionDualReturnDistanceFar'].enabled = False app.actions['actionDualReturnIntensityHigh'].enabled = False app.actions['actionDualReturnIntensityLow'].enabled = False def seekForward(): if app.playing: if app.playDirection < 0 or app.playDirection == 5: app.playDirection = 0 app.playDirection += 1 updateSeekButtons() else: gotoNext() def seekBackward(): if app.playing: if app.playDirection > 0 or app.playDirection == -5: app.playDirection = 0 app.playDirection -= 1 updateSeekButtons() else: gotoPrevious() def seekPressTimeout(): app.seekPlay = True onPlayTimer() def seekForwardPressed(): app.seekPlayDirection = 1 if not app.playing: app.seekTimer.start(500) def seekForwardReleased(): app.seekTimer.stop() app.seekPlay = False def seekBackwardPressed(): app.seekPlayDirection = -1 if not app.playing: app.seekTimer.start(500) def seekBackwardReleased(): seekForwardReleased() def updateSeekButtons(): icons = { -5 : IconPaths.seekBackwardQuarterx, -4 : IconPaths.seekBackwardHalfx, -3 : IconPaths.seekBackward3x, -2 : IconPaths.seekBackward2x, -1 : IconPaths.seekBackward, 1 : IconPaths.seekForward, 2 : IconPaths.seekForward2x, 3 : IconPaths.seekForward3x, 4 : IconPaths.seekForwardHalfx, 5 : IconPaths.seekForwardQuarterx, } setActionIcon('actionSeek_Backward', icons[app.playDirection] if app.playDirection < 0 else IconPaths.seekBackward) setActionIcon('actionSeek_Forward', icons[app.playDirection] if app.playDirection > 0 else IconPaths.seekForward) fpsMap = {-5:5, 5:5, -4:11, 4:11} fpsDefault = 30 app.targetFps = fpsMap.get(app.playDirection, fpsDefault) def setPlaybackActionsEnabled(enabled): for action in ('Play', 'Record', 'Seek_Forward', 'Seek_Backward', 'Go_To_Start', 'Go_To_End'): app.actions['action'+action].setEnabled(enabled) def enablePlaybackActions(): setPlaybackActionsEnabled(True) def disablePlaybackActions(): setPlaybackActionsEnabled(False) def _setSaveActionsEnabled(enabled): for action in ('SaveCSV', 'SavePCAP', 'SaveLAS', 'Export_To_KiwiViewer', 'Close', 'Choose_Calibration_File', 'CropReturns'): app.actions['action'+action].setEnabled(enabled) getMainWindow().findChild('QMenu', 'menuSaveAs').enabled = enabled def enableSaveActions(): _setSaveActionsEnabled(True) if getPosition(): app.actions['actionSavePositionCSV'].setEnabled(True) def disableSaveActions(): _setSaveActionsEnabled(False) app.actions['actionSavePositionCSV'].setEnabled(False) def recordFile(filename): sensor = getSensor() if sensor: stopStream() sensor.OutputFile = filename app.statusLabel.setText(' Recording file: %s.' % os.path.basename(filename)) if app.playing: startStream() def onRecord(): recordAction = app.actions['actionRecord'] if not recordAction.isChecked(): stopRecording() else: fileName = getSaveFileName('Choose Output File', 'pcap', getDefaultSaveFileName('pcap')) if not fileName: recordAction.setChecked(False) return recordFile(fileName) def stopRecording(): app.statusLabel.setText('') sensor = getSensor() if sensor: stopStream() sensor.OutputFile = '' if app.playing: startStream() def startStream(): sensor = getSensor() if sensor: sensor.Start() def stopStream(): sensor = getSensor() if sensor: sensor.Stop() def pollSource(): source = getSensor() reader = getReader() if source is not None: source.Poll() source.UpdatePipelineInformation() return source or reader def getPointCloudData(attribute=None): if attribute is not None: data = getPointCloudData() if data: if attribute == 'points': return data.GetPoints().GetData() else: return data.GetPointData().GetArray(attribute) else: source = getSensor() or getReader() if source: return source.GetClientSideObject().GetOutput() def getCurrentTimesteps(): source = pollSource() return list(source.TimestepValues) if source is not None else [] def getNumberOfTimesteps(): return getTimeKeeper().getNumberOfTimeStepValues() def togglePlay(): setPlayMode(not app.playing) def play(): setPlayMode(True) def stop(): setPlayMode(False) def onPlayTimer(): if app.playing or app.seekPlay: startTime = vtk.vtkTimerLog.GetUniversalTime() playbackTick() fpsDelayMilliseconds = int(1000.0 / app.targetFps) elapsedMilliseconds = int((vtk.vtkTimerLog.GetUniversalTime() - startTime)*1000.0) if elapsedMilliseconds > 0: fps = 1000.0/elapsedMilliseconds app.fps[0] += fps app.fps[1] += 1 waitMilliseconds = fpsDelayMilliseconds - elapsedMilliseconds app.playTimer.start(max(waitMilliseconds,0)) def setPlayMode(mode): if not getReader() and not getSensor(): return app.playing = mode if mode: startStream() setActionIcon('actionPlay', IconPaths.pause) app.playTimer.start(33) if app.scene.AnimationTime == app.scene.EndTime: app.scene.AnimationTime = app.scene.StartTime else: stopStream() setActionIcon('actionPlay', IconPaths.play) app.playDirection = 1 updateSeekButtons() def gotoStart(): pollSource() app.scene.GoToFirst() updatePosition() def gotoEnd(): pollSource() app.scene.GoToLast() updatePosition() def gotoNext(): pollSource() app.scene.GoToNext() updatePosition() def gotoPrevious(): pollSource() app.scene.GoToPrevious() updatePosition() def updatePosition(): reader = getReader() pos = getPosition() if reader and pos: pointcloud = reader.GetClientSideObject().GetOutput() if pointcloud.GetNumberOfPoints(): # Update the overhead view # TODO: Approximate time, just grabbing the last t = pointcloud.GetPointData().GetScalars('adjustedtime') #currentTime = t.GetTuple1(t.GetNumberOfTuples() - 1) currentTime = t.GetTuple1(0) * 1e-6 interp = getPosition().GetClientSideObject().GetInterpolator() trange = [interp.GetMinimumT(), interp.GetMaximumT()] # Clamp currentTime = min(max(currentTime, trange[0]+1.0e-1), trange[1]-1.0e-1) position = [0.0] * 3 transform = vtk.vtkTransform() interp.InterpolateTransform(currentTime, transform) transform.TransformPoint(position, position) rep = cachedGetRepresentation(reader, view=app.mainView) if app.relativeTransform: rep.Position = transform.GetInverse().GetPosition() rep.Orientation = transform.GetInverse().GetOrientation() else: rep.Position = [0.0, 0.0, 0.0] rep.Orientation = [0.0, 0.0, 0.0] g = getGlyph() rep = cachedGetRepresentation(g, view=app.overheadView) rep.Position = position[:3] def playbackTick(): sensor = getSensor() reader = getReader() view = smp.GetActiveView() if sensor is not None: timesteps = getCurrentTimesteps() if not timesteps: return if view.ViewTime == timesteps[-1]: return if not app.colorByInitialized: sensor.UpdatePipeline() if colorByIntensity(sensor): app.colorByInitialized = True resetCamera() app.scene.GoToLast() elif reader is not None: numberOfTimesteps = getNumberOfTimesteps() if not numberOfTimesteps: return step = app.seekPlayDirection if app.seekPlay else app.playDirection stepMap = {4:1, 5:1, -4:-1, -5:-1} step = stepMap.get(step, step) newTime = app.scene.AnimationTime + step if app.actions['actionLoop'].isChecked(): newTime = newTime % numberOfTimesteps else: newTime = max(app.scene.StartTime, min(newTime, app.scene.EndTime)) # stop playback when it reaches the first or last timestep if newTime in (app.scene.StartTime, app.scene.EndTime): stop() app.scene.AnimationTime = newTime # TODO: For sensor as well? updatePosition() def unloadData(): _repCache.clear() for k, src in smp.GetSources().iteritems(): if src != app.grid: smp.Delete(src) toremove = [x for x in app.overheadView.Representations if type(x) == servermanager.rendering.ScalarBarWidgetRepresentation] for t in toremove: app.overheadView.Representations.remove(t) app.reader = None app.position = (None, None, None) app.sensor = None clearSpreadSheetView() def getReader(): return getattr(app, 'reader', None) def getSensor(): return getattr(app, 'sensor', None) def getPosition(): return getattr(app, 'position', (None, None, None))[0] def getGlyph(): return getattr(app, 'position', (None, None, None))[2] def onChooseCalibrationFile(): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform reader = getReader() sensor = getSensor() if reader is not None: reader.GetClientSideObject().SetSensorTransform(sensorTransform) reader.CalibrationFile = calibrationFile reader.DummyProperty = not reader.DummyProperty smp.Render() elif sensor is not None: sensor.GetClientSideObject().SetSensorTransform(sensorTransform) sensor.CalibrationFile = calibrationFile # no need to render now, calibration file will be used on the next frame def onCropReturns(show = True): dialog = vvCropReturnsDialog(getMainWindow()) cropEnabled = False cropInside = False firstCorner = QtGui.QVector3D() secondCorner = QtGui.QVector3D() reader = getReader() sensor = getSensor() if reader is not None: cropEnabled = reader.CropReturns cropInside = reader.CropInside firstCorner = QtGui.QVector3D(reader.CropRegion[0], reader.CropRegion[2], reader.CropRegion[4]) secondCorner = QtGui.QVector3D(reader.CropRegion[1], reader.CropRegion[3], reader.CropRegion[5]) if sensor is not None: cropEnabled = sensor.CropReturns cropInside = sensor.CropInside firstCorner = QtGui.QVector3D(sensor.CropRegion[0], sensor.CropRegion[2], sensor.CropRegion[4]) secondCorner = QtGui.QVector3D(sensor.CropRegion[1], sensor.CropRegion[3], sensor.CropRegion[5]) if show: dialog.croppingEnabled = cropEnabled dialog.cropInside = cropInside dialog.firstCorner = firstCorner dialog.secondCorner = secondCorner if not dialog.exec_(): return if reader is not None: reader.CropReturns = dialog.croppingEnabled reader.CropInside = dialog.cropInside p1 = dialog.firstCorner p2 = dialog.secondCorner reader.CropRegion = [p1.x(), p2.x(), p1.y(), p2.y(), p1.z(), p2.z()] if show: smp.Render() if sensor is not None: sensor.CropReturns = dialog.croppingEnabled sensor.CropInside = dialog.cropInside p1 = dialog.firstCorner p2 = dialog.secondCorner sensor.CropRegion = [p1.x(), p2.x(), p1.y(), p2.y(), p1.z(), p2.z()] if show: smp.Render() def resetCamera(): def subtract(a, b): result = range(3) vtk.vtkMath.Subtract(a, b, result) return result def cross(a, b): result = range(3) vtk.vtkMath.Cross(a, b, result) return result view = smp.GetActiveView() foc = list(view.CenterOfRotation) pos = list(view.CameraPosition) viewDirection = subtract(foc, pos) view.CameraPosition = subtract([0, 0, 0], viewDirection) view.CameraFocalPoint = [0, 0, 0] view.CenterOfRotation = [0, 0, 0] vtk.vtkMath.Normalize(viewDirection) perp = cross(viewDirection, [0, 0, 1]) viewUp = cross(perp, viewDirection) view.CameraViewUp = viewUp view.StillRender() def resetCameraToBirdsEyeView(view=None): view = view or smp.GetActiveView() view.CameraFocalPoint = [0, 0, 0] view.CameraViewUp = [0, 1, 0] view.CameraPosition = [0, 0, 40] view.CenterOfRotation = [0, 0, 0] smp.Render(view) def resetCameraToForwardView(view=None): view = view or smp.GetActiveView() view.CameraFocalPoint = [0,0,0] view.CameraViewUp = [0, 0.27, 0.96] view.CameraPosition = [0, -72, 18.0] view.CenterOfRotation = [0, 0, 0] smp.Render(view) def saveScreenshot(filename): smp.WriteImage(filename) # reload the saved screenshot as a pixmap screenshot = QtGui.QPixmap() screenshot.load(filename) # create a new pixmap with the status bar widget painted at the bottom statusBar = QtGui.QPixmap.grabWidget(getMainWindow().statusBar()) composite = QtGui.QPixmap(screenshot.width(), screenshot.height() + statusBar.height()) painter = QtGui.QPainter() painter.begin(composite) painter.drawPixmap(screenshot.rect(), screenshot, screenshot.rect()) painter.drawPixmap(statusBar.rect().translated(0, screenshot.height()), statusBar, statusBar.rect()) painter.end() # save final screenshot composite.save(filename) def getSpreadSheetViewProxy(): for p in smp.servermanager.ProxyManager(): if p.GetXMLName() == 'SpreadSheetView': return p def clearSpreadSheetView(): view = getSpreadSheetViewProxy() view.Representations = [] def showSourceInSpreadSheet(source): spreadSheetView = getSpreadSheetViewProxy() smp.Show(source, spreadSheetView) # Work around a bug where the 'Showing' combobox doesn't update. # Calling hide and show again will trigger the refresh. smp.Hide(source, spreadSheetView) smp.Show(source, spreadSheetView) def createGrid(view=None): view = view or smp.GetActiveView() grid = smp.VelodyneHDLGridSource(guiName='Measurement Grid') rep = smp.Show(grid, view) rep.DiffuseColor = [0.2, 0.2, 0.2] rep.Pickable = 0 rep.Visibility = 0 smp.SetActiveSource(None) return grid def hideGrid(): smp.GetDisplayProperties(app.grid).Hide() def showGrid(): smp.GetDisplayProperties(app.grid).Show() def getAnimationScene(): '''This function is a workaround because paraview.simple.GetAnimationScene() has an issue where the returned proxy might not have its Cues property initialized''' for proxy in servermanager.ProxyManager().GetProxiesInGroup("animation").values(): if proxy.GetXMLName() == 'AnimationScene' and len(proxy.Cues): return proxy def start(): global app app = AppLogic() app.scene = getAnimationScene() view = smp.GetActiveView() view.Background = [0.0, 0.0, 0.0] view.Background2 = [0.0, 0.0, 0.2] view.UseGradientBackground = True smp._DisableFirstRenderCameraReset() smp.GetActiveView().LODThreshold = 1e100 app.grid = createGrid() app.ruler = createRuler() resetCameraToForwardView() setupActions() disablePlaybackActions() disableSaveActions() app.actions['actionMeasure'].setEnabled(view.CameraParallelProjection) setupStatusBar() setupTimeSliderWidget() hideColorByComponent() restoreNativeFileDialogsAction() updateRecentFiles() getTimeKeeper().connect('timeChanged()', onTimeChanged) def findQObjectByName(widgets, name): for w in widgets: if w.objectName == name: return w def getMainWindow(): return findQObjectByName(QtGui.QApplication.topLevelWidgets(), 'vvMainWindow') def getPVApplicationCore(): return PythonQt.paraview.pqPVApplicationCore.instance() def getPVSettings(): return getPVApplicationCore().settings() def getTimeKeeper(): return getPVApplicationCore().getActiveServer().getTimeKeeper() def getPlaybackToolBar(): return findQObjectByName(getMainWindow().children(), 'playbackToolbar') def quit(): PythonQt.QtGui.QApplication.instance().quit() exit = quit def addShortcuts(keySequenceStr, function): shortcut = PythonQt.QtGui.QShortcut(PythonQt.QtGui.QKeySequence(keySequenceStr), getMainWindow()) shortcut.connect("activated()", function) def onTrailingFramesChanged(numFrames): try: app.reader.NumberOfTrailingFrames = numFrames smp.Render() smp.Render(getSpreadSheetViewProxy()) except AttributeError: pass def onPointsSkipChanged(pr): try: app.reader.PointsSkip = pr smp.Render() smp.Render(getSpreadSheetViewProxy()) except AttributeError: pass def setupTimeSliderWidget(): frame = QtGui.QWidget() layout = QtGui.QHBoxLayout(frame) spinBox = QtGui.QSpinBox() spinBox.setMinimum(0) spinBox.setMaximum(100) spinBox.setValue(0) slider = QtGui.QSlider(QtCore.Qt.Horizontal) slider.setMaximumWidth(160) slider.connect('valueChanged(int)', onTimeSliderChanged) spinBox.connect('valueChanged(int)', onTimeSliderChanged) slider.setEnabled(False) spinBox.setEnabled(False) layout.addWidget(slider) layout.addWidget(spinBox) layout.addStretch() toolbar = getPlaybackToolBar() toolbar.addWidget(frame) app.timeSlider = slider app.timeSpinBox = spinBox def updateSliderTimeRange(): frame = int(app.scene.AnimationTime) lastFrame = int(app.scene.EndTime) for widget in (app.timeSlider, app.timeSpinBox): widget.setMinimum(0) widget.setMaximum(lastFrame) widget.setSingleStep(1) if hasattr(widget, 'setPageStep'): widget.setPageStep(10) widget.setValue(frame) widget.setEnabled(getNumberOfTimesteps()) def scheduleRender(): if not app.renderIsPending: app.renderIsPending = True app.renderTimer.start(33) def forceRender(): smp.Render() app.renderIsPending = False def onTimeSliderChanged(frame): app.scene.AnimationTime = frame updatePosition() def setupStatusBar(): statusBar = getMainWindow().statusBar() statusBar.addPermanentWidget(app.logoLabel) statusBar.addWidget(app.filenameLabel) statusBar.addWidget(app.statusLabel) statusBar.addWidget(app.timeLabel) def setActionIcon(actionName, iconPath): app.actions[actionName].setIcon(QtGui.QIcon(QtGui.QPixmap(iconPath))) def onTimeChanged(): frame = int(getTimeKeeper().getTime()) app.timeLabel.setText(' Frame: %s' % frame) for widget in (app.timeSlider, app.timeSpinBox): widget.blockSignals(True) widget.setValue(frame) widget.blockSignals(False) def onGridProperties(): if gridAdjustmentDialog.showDialog(getMainWindow(), app.grid): smp.Render() def onLaserSelection(show = True): oldmask = [1] * 64 reader = getReader() sensor = getSensor() corrections = [0] * 64 nchannels = 32 if reader: reader.GetClientSideObject().GetLaserSelection(oldmask) reader.GetClientSideObject().GetVerticalCorrections(corrections) nchannels = reader.GetPropertyValue('NumberOfChannels') elif sensor: sensor.GetClientSideObject().GetLaserSelection(oldmask) sensor.GetClientSideObject().GetVerticalCorrections(corrections) nchannels = sensor.GetPropertyValue('NumberOfChannels') # Need a way to initialize the mask dialog = PythonQt.paraview.vvLaserSelectionDialog(getMainWindow()) if show: dialog.setLaserSelectionSelector(oldmask) dialog.setVerticalCorrections(corrections, nchannels) if not dialog.exec_(): return mask = dialog.getLaserSelectionSelector() if reader: reader.GetClientSideObject().SetLaserSelection(mask) reader.DummyProperty = not reader.DummyProperty if show: smp.Render() smp.Render(getSpreadSheetViewProxy()) if sensor: sensor.GetClientSideObject().SetLaserSelection(mask) sensor.DummyProperty = not sensor.DummyProperty if show: smp.Render() smp.Render(getSpreadSheetViewProxy()) def hideColorByComponent(): getMainWindow().findChild('vvColorToolbar').findChild('pqDisplayColorWidget').findChildren('QComboBox')[1].hide() def addRecentFile(filename): recentFiles = getRecentFiles() try: recentFiles.remove(filename) except ValueError: pass recentFiles = recentFiles[:4] recentFiles.insert(0, filename) getPVSettings().setValue('VelodyneHDLPlugin/RecentFiles', recentFiles) updateRecentFiles() def openRecentFile(filename): if not os.path.isfile(filename): QtGui.QMessageBox.warning(getMainWindow(), 'File not found', 'File not found: %s' % filename) return if os.path.splitext(filename)[1].lower() == '.pcap': openPCAP(filename) else: openData(filename) def getRecentFiles(): return list(getPVSettings().value('VelodyneHDLPlugin/RecentFiles', []) or []) def updateRecentFiles(): settings = getPVSettings() recentFiles = getRecentFiles() recentFilesMenu = findQObjectByName(findQObjectByName(getMainWindow().menuBar().children(), 'menu_File').children(), 'menuRecent_Files') clearMenuAction = app.actions['actionClear_Menu'] for action in recentFilesMenu.actions()[:-2]: recentFilesMenu.removeAction(action) def createActionFunction(filename): def f(): openRecentFile(filename) return f actions = [] for filename in recentFiles: actions.append(QtGui.QAction(os.path.basename(filename), recentFilesMenu)) actions[-1].connect('triggered()', createActionFunction(filename)) recentFilesMenu.insertActions(recentFilesMenu.actions()[0], actions) def onClearMenu(): settings = getPVSettings() settings.setValue('VelodyneHDLPlugin/RecentFiles', []) updateRecentFiles() def toggleProjectionType(): view = smp.GetActiveView() view.CameraParallelProjection = not view.CameraParallelProjection if app.actions['actionMeasure'].isChecked(): app.actions['actionMeasure'].trigger() app.actions['actionMeasure'].toggle() app.actions['actionMeasure'].setEnabled(view.CameraParallelProjection) smp.Render() def setViewTo(axis,sign): view = smp.GetActiveView() viewUp = view.CameraViewUp position = view.CameraPosition norm = math.sqrt(math.pow(position[0],2) + math.pow(position[1],2) + math.pow(position[2],2)) if axis == 'X': view.CameraViewUp = [0,0,1] view.CameraPosition = [-1*sign*norm,0,0] elif axis == 'Y': view.CameraViewUp = [0,0,1] view.CameraPosition = [0,-1*sign*norm,0] elif axis == 'Z': view.CameraViewUp = [0,1,0] view.CameraPosition = [0,0,-1*sign*norm] view.CameraFocalPoint = [0,0,0] view.CenterOfRotation = [0,0,0] view.ResetCamera() smp.Render() def setViewToXPlus(): setViewTo('X',1) def setViewToXMinus(): setViewTo('X',-1) def setViewToYPlus(): setViewTo('Y',1) def setViewToYMinus(): setViewTo('Y',-1) def setViewToZPlus(): setViewTo('Z',1) def setViewToZMinus(): setViewTo('Z',-1) def setFilterToDual(): setFilterTo(0) def setFilterToDistanceNear(): setFilterTo(vtkVelodyneHDLReader.DUAL_DISTANCE_NEAR) def setFilterToDistanceFar(): setFilterTo(vtkVelodyneHDLReader.DUAL_DISTANCE_FAR) def setFilterToIntensityHigh(): setFilterTo(vtkVelodyneHDLReader.DUAL_INTENSITY_HIGH) def setFilterToIntensityLow(): setFilterTo(vtkVelodyneHDLReader.DUAL_INTENSITY_LOW) def setFilterTo(mask): reader = getReader() if reader: reader.DualReturnFilter = mask smp.Render() smp.Render(getSpreadSheetViewProxy()) sensor = getSensor() if sensor: sensor.DualReturnFilter = mask smp.Render() smp.Render(getSpreadSheetViewProxy()) def transformMode(): reader = getReader() if not reader: return None if reader.ApplyTransform: if app.relativeTransform: return 2 # relative else: return 1 # absolute return 0 # raw def setTransformMode(mode): # 0 - raw # 1 - absolute # 2 - relative reader = getReader() if reader: reader.ApplyTransform = (mode > 0) app.transformMode = mode app.relativeTransform = (mode == 2) def geolocationChanged(setting): setTransformMode(setting) updatePosition() smp.Render(view=app.mainView) def setupActions(): mW = getMainWindow() actions = mW.findChildren('QAction') app.actions = {} for a in actions: app.actions[a.objectName] = a app.actions['actionPlaneFit'].connect('triggered()', planeFit) app.actions['actionClose'].connect('triggered()', close) app.actions['actionPlay'].connect('triggered()', togglePlay) app.actions['actionRecord'].connect('triggered()', onRecord) app.actions['actionSaveCSV'].connect('triggered()', onSaveCSV) app.actions['actionSavePositionCSV'].connect('triggered()', onSavePosition) app.actions['actionSaveLAS'].connect('triggered()', onSaveLAS) app.actions['actionSavePCAP'].connect('triggered()', onSavePCAP) app.actions['actionSaveScreenshot'].connect('triggered()', onSaveScreenshot) app.actions['actionExport_To_KiwiViewer'].connect('triggered()', onKiwiViewerExport) app.actions['actionReset_Camera'].connect('triggered()', resetCamera) app.actions['actionGrid_Properties'].connect('triggered()', onGridProperties) app.actions['actionLaserSelection'].connect('triggered()', onLaserSelection) app.actions['actionChoose_Calibration_File'].connect('triggered()', onChooseCalibrationFile) app.actions['actionCropReturns'].connect('triggered()', onCropReturns) app.actions['actionSeek_Forward'].connect('triggered()', seekForward) app.actions['actionSeek_Backward'].connect('triggered()', seekBackward) app.actions['actionGo_To_End'].connect('triggered()', gotoEnd) app.actions['actionGo_To_Start'].connect('triggered()', gotoStart) app.actions['actionNative_File_Dialogs'].connect('triggered()', onNativeFileDialogsAction) app.actions['actionAbout_VeloView'].connect('triggered()', onAbout) app.actions['actionVeloViewDeveloperGuide'].connect('triggered()', onDeveloperGuide) app.actions['actionClear_Menu'].connect('triggered()', onClearMenu) app.actions['actionToggleProjection'].connect('triggered()', toggleProjectionType) app.actions['actionMeasure'].connect('triggered()', toggleRulerContext) app.actions['actionSetViewXPlus'].connect('triggered()', setViewToXPlus) app.actions['actionSetViewXMinus'].connect('triggered()', setViewToXMinus) app.actions['actionSetViewYPlus'].connect('triggered()', setViewToYPlus) app.actions['actionSetViewYMinus'].connect('triggered()', setViewToYMinus) app.actions['actionSetViewZPlus'].connect('triggered()', setViewToZPlus) app.actions['actionSetViewZMinus'].connect('triggered()', setViewToZMinus) app.actions['actionDualReturnModeDual'].connect('triggered()', setFilterToDual) app.actions['actionDualReturnDistanceNear'].connect('triggered()', setFilterToDistanceNear) app.actions['actionDualReturnDistanceFar'].connect('triggered()', setFilterToDistanceFar) app.actions['actionDualReturnIntensityHigh'].connect('triggered()', setFilterToIntensityHigh) app.actions['actionDualReturnIntensityLow'].connect('triggered()', setFilterToIntensityLow) # Action created # timeToolBar = mW.findChild('QToolBar','playbackToolbar') geolocationToolBar = mW.findChild('QToolBar', 'geolocationToolbar') comboBox = QtGui.QComboBox() comboBox.addItem('Relative RAW') comboBox.addItem('Absolute Geolocation') comboBox.addItem('Relative Geolocation') comboBox.connect('currentIndexChanged(int)', geolocationChanged) geolocationToolBar.addWidget(comboBox) spinBoxLabel = QtGui.QLabel('TF:') spinBoxLabel.toolTip = "Number of trailing frames" timeToolBar.addWidget(spinBoxLabel) spinBox = QtGui.QSpinBox() spinBox.toolTip = "Number of trailing frames" spinBox.setMinimum(0) spinBox.setMaximum(100) spinBox.connect('valueChanged(int)', onTrailingFramesChanged) app.trailingFramesSpinBox = spinBox app.actions['actionTrailingFramesSelector'] = timeToolBar.addWidget(spinBox) app.actions['actionTrailingFramesSelector'].setVisible(True) pointsSkipLabel = QtGui.QLabel('Skip:') pointsSkipLabel.toolTip = "Number of Points to Skip" timeToolBar.addWidget(pointsSkipLabel) pointsSkipBox = QtGui.QSpinBox() pointsSkipBox.toolTip = "Number of Points to Skip" pointsSkipBox.setMinimum(0) pointsSkipBox.setMaximum(100) pointsSkipBox.connect('valueChanged(int)', onPointsSkipChanged) app.pointsSkipSpinBox = pointsSkipBox app.actions['actionPointsSkipSelector'] = timeToolBar.addWidget(pointsSkipBox) app.actions['actionPointsSkipSelector'].setVisible(True) buttons = {} for button in getPlaybackToolBar().findChildren('QToolButton'): buttons[button.text] = button buttons['Seek Forward'].connect('pressed()', seekForwardPressed) buttons['Seek Forward'].connect('released()', seekForwardReleased) buttons['Seek Backward'].connect('pressed()', seekBackwardPressed) buttons['Seek Backward'].connect('released()', seekBackwardReleased)
<filename>VelodyneHDL/python/veloview/applogic.py # Copyright 2013 Velodyne Acoustics, 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 os import csv import datetime import time import math import paraview.simple as smp from paraview import servermanager from paraview import vtk import PythonQt from PythonQt import QtCore, QtGui from vtkIOXMLPython import vtkXMLPolyDataWriter import kiwiviewerExporter import gridAdjustmentDialog import planefit from PythonQt.paraview import vvCalibrationDialog, vvCropReturnsDialog, vvSelectFramesDialog from VelodyneHDLPluginPython import vtkVelodyneHDLReader _repCache = {} SAMPLE_PROCESSING_MODE = False def cachedGetRepresentation(src, view): try: return _repCache[(src, view)] except KeyError: rep = smp.GetRepresentation(src, view) _repCache[(src, view)] = rep return rep class AppLogic(object): def __init__(self): self.playing = False self.playDirection = 1 self.seekPlayDirection = 1 self.seekPlay = False self.targetFps = 30 self.renderIsPending = False self.createStatusBarWidgets() self.setupTimers() self.mousePressed = False mainView = smp.GetActiveView() views = smp.GetRenderViews() otherViews = [v for v in views if v != mainView] assert len(otherViews) == 1 overheadView = otherViews[0] self.mainView = mainView self.overheadView = overheadView self.transformMode = 0 self.relativeTransform = False self.reader = None self.position = (None, None, None) self.sensor = None self.fps = [0,0] def setupTimers(self): self.playTimer = QtCore.QTimer() self.playTimer.setSingleShot(True) self.playTimer.connect('timeout()', onPlayTimer) self.seekTimer = QtCore.QTimer() self.seekTimer.setSingleShot(True) self.seekTimer.connect('timeout()', seekPressTimeout) self.renderTimer = QtCore.QTimer() self.renderTimer.setSingleShot(True) self.renderTimer.connect('timeout()', forceRender) def createStatusBarWidgets(self): self.logoLabel = QtGui.QLabel() self.logoLabel.setPixmap(QtGui.QPixmap(":/VelodyneHDLPlugin/velodyne_logo.png")) self.logoLabel.setScaledContents(True) self.filenameLabel = QtGui.QLabel() self.statusLabel = QtGui.QLabel() self.timeLabel = QtGui.QLabel() class IconPaths(object): trailingFrames = ':/VelodyneHDLPlugin/trailingframes.png' play = ':/VelodyneHDLPlugin/media-playback-start.png' pause =':/VelodyneHDLPlugin/media-playback-pause.png' seekForward = ':/VelodyneHDLPlugin/media-seek-forward.png' seekForward2x = ':/VelodyneHDLPlugin/media-seek-forward-2x.png' seekForwardHalfx = ':/VelodyneHDLPlugin/media-seek-forward-0.5x.png' seekForwardQuarterx = ':/VelodyneHDLPlugin/media-seek-forward-0.25x.png' seekForward3x = ':/VelodyneHDLPlugin/media-seek-forward-3x.png' seekBackward = ':/VelodyneHDLPlugin/media-seek-backward.png' seekBackward2x = ':/VelodyneHDLPlugin/media-seek-backward-2x.png' seekBackward3x = ':/VelodyneHDLPlugin/media-seek-backward-3x.png' seekBackwardHalfx = ':/VelodyneHDLPlugin/media-seek-backward-0.5x.png' seekBackwardQuarterx = ':/VelodyneHDLPlugin/media-seek-backward-0.25x.png' def hasArrayName(sourceProxy, arrayName): ''' Returns True if the data has non-zero points and has a point data attribute with the given arrayName. ''' info = sourceProxy.GetDataInformation().DataInformation if info.GetNumberOfPoints() == 0: return False info = info.GetAttributeInformation(0) for i in xrange(info.GetNumberOfArrays()): if info.GetArrayInformation(i).GetName() == arrayName: return True return False def openData(filename): close() reader = smp.OpenDataFile(filename, guiName='Data') if not reader: return rep = smp.Show(reader) rep.InterpolateScalarsBeforeMapping = 0 setDefaultLookupTables(reader) colorByIntensity(reader) showSourceInSpreadSheet(reader) smp.GetActiveView().ViewTime = 0.0 app.reader = reader app.filenameLabel.setText('File: %s' % os.path.basename(filename)) updateSliderTimeRange() enablePlaybackActions() enableSaveActions() addRecentFile(filename) app.actions['actionSavePCAP'].setEnabled(False) app.actions['actionChoose_Calibration_File'].setEnabled(False) app.actions['actionCropReturns'].setEnabled(False) app.actions['actionRecord'].setEnabled(False) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True resetCamera() def planeFit(): planefit.fitPlane() def setDefaultLookupTables(sourceProxy): # LUT for 'intensity' smp.GetLookupTableForArray( 'intensity', 1, ScalarRangeInitialized=1.0, ColorSpace='HSV', RGBPoints=[0.0, 0.0, 0.0, 1.0, 100.0, 1.0, 1.0, 0.0, 256.0, 1.0, 0.0, 0.0]) # LUT for 'dual_distance' smp.GetLookupTableForArray( 'dual_distance', 1, InterpretValuesAsCategories=True, NumberOfTableValues=3, RGBPoints=[-1.0, 0.1, 0.5, 0.7, 0.0, 0.9, 0.9, 0.9, +1.0, 0.8, 0.2, 0.3], Annotations=['-1', 'near', '0', 'dual', '1', 'far']) # LUT for 'dual_intensity' smp.GetLookupTableForArray( 'dual_intensity', 1, InterpretValuesAsCategories=True, NumberOfTableValues=3, RGBPoints=[-1.0, 0.5, 0.2, 0.8, 0.0, 0.6, 0.6, 0.6, +1.0, 1.0, 0.9, 0.4], Annotations=['-1', 'low', '0', 'dual', '1', 'high']) def colorByIntensity(sourceProxy): if not hasArrayName(sourceProxy, 'intensity'): return False setDefaultLookupTables(sourceProxy) rep = smp.GetDisplayProperties(sourceProxy) rep.ColorArrayName = 'intensity' rep.LookupTable = smp.GetLookupTableForArray('intensity', 1) return True def getTimeStamp(): format = '%Y-%m-%d-%H-%M-%S' return datetime.datetime.now().strftime(format) def getReaderFileName(): filename = getReader().FileName return filename[0] if isinstance(filename, servermanager.FileNameProperty) else filename def getDefaultSaveFileName(extension, suffix='', appendFrameNumber=False): sensor = getSensor() reader = getReader() if sensor: nchannels = sensor.GetPropertyValue('NumberOfChannels') base = 'HDL-' if nchannels <= 16: base = 'VLP-' sensortype = base + str(nchannels) return '%s_Velodyne-%s-Data.%s' % (getTimeStamp(), sensortype, extension) if reader: basename = os.path.splitext(os.path.basename(getReaderFileName()))[0] if appendFrameNumber: suffix = '%s (Frame %04d)' % (suffix, int(app.scene.AnimationTime)) return '%s%s.%s' % (basename, suffix, extension) def chooseCalibration(): class Calibration(object): def __init__(self, dialog): self.calibrationFile = dialog.selectedCalibrationFile() self.gpsYaw = dialog.gpsYaw() self.gpsRoll = dialog.gpsRoll() self.gpsPitch = dialog.gpsPitch() self.sensorTransform = vtk.vtkTransform() qm = dialog.sensorTransform() vm = vtk.vtkMatrix4x4() for row in xrange(4): vm.SetElement(row, 0, qm.row(row).x()) vm.SetElement(row, 1, qm.row(row).y()) vm.SetElement(row, 2, qm.row(row).z()) vm.SetElement(row, 3, qm.row(row).w()) self.sensorTransform.SetMatrix(vm) dialog = vvCalibrationDialog(getMainWindow()) if not dialog.exec_(): return None return Calibration(dialog) def openSensor(): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform close() sensor = smp.VelodyneHDLSource(guiName='Data', CalibrationFile=calibrationFile, CacheSize=100) sensor.GetClientSideObject().SetSensorTransform(sensorTransform) sensor.UpdatePipeline() sensor.Start() if SAMPLE_PROCESSING_MODE: processor = smp.ProcessingSample(sensor) smp.GetActiveView().ViewTime = 0.0 app.sensor = sensor app.colorByInitialized = False app.filenameLabel.setText('Live sensor stream.') enablePlaybackActions() enableSaveActions() onCropReturns(False) # Dont show the dialog just restore settings onLaserSelection(False) rep = smp.Show(sensor) rep.InterpolateScalarsBeforeMapping = 0 if SAMPLE_PROCESSING_MODE: prep = smp.Show(processor) smp.Render() showSourceInSpreadSheet(sensor) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True play() def openPCAP(filename, positionFilename=None): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform close() def onProgressEvent(o, e): PythonQt.QtGui.QApplication.instance().processEvents() progressDialog = QtGui.QProgressDialog('Reading packet file...', '', 0, 0, getMainWindow()) progressDialog.setCancelButton(None) progressDialog.setModal(True) progressDialog.show() handler = servermanager.ActiveConnection.Session.GetProgressHandler() handler.PrepareProgress() freq = handler.GetProgressFrequency() handler.SetProgressFrequency(0.05) tag = handler.AddObserver('ProgressEvent', onProgressEvent) # construct the reader, this calls UpdateInformation on the # reader which scans the pcap file and emits progress events reader = smp.VelodyneHDLReader(guiName='Data', FileName=filename, CalibrationFile=calibrationFile, ApplyTransform=(app.transformMode > 0), NumberOfTrailingFrames=app.trailingFramesSpinBox.value, PointsSkip=app.trailingFramesSpinBox.value) app.reader = reader app.filenameLabel.setText('File: %s' % os.path.basename(filename)) onCropReturns(False) # Dont show the dialog just restore settings onLaserSelection(False) reader.GetClientSideObject().SetSensorTransform(sensorTransform) if SAMPLE_PROCESSING_MODE: processor = smp.ProcessingSample(reader) handler.RemoveObserver(tag) handler.SetProgressFrequency(freq) progressDialog.close() smp.GetActiveView().ViewTime = 0.0 rep = smp.Show(reader) if SAMPLE_PROCESSING_MODE: prep = smp.Show(processor) app.scene.UpdateAnimationUsingDataTimeSteps() # update overhead view smp.SetActiveView(app.overheadView) if positionFilename is None: posreader = smp.VelodyneHDLPositionReader(guiName="Position", FileName=filename) else: posreader = smp.ApplanixPositionReader(guiName="Position", FileName=positionFilename) posreader.BaseYaw = calibration.gpsYaw posreader.BaseRoll = calibration.gpsRoll posreader.BasePitch = calibration.gpsPitch smp.Show(posreader) # Create a sphere glyph g = smp.Sphere() g.Radius = 5.0 smp.Show(g) if posreader.GetClientSideObject().GetOutput().GetNumberOfPoints(): reader.GetClientSideObject().SetInterpolator( posreader.GetClientSideObject().GetInterpolator()) smp.Render(app.overheadView) app.overheadView.ResetCamera() trange = posreader.GetPointDataInformation().GetArray('time').GetRange() # By construction time zero is at position 0,0,0 # Setup scalar bar rep = smp.GetDisplayProperties(posreader) rep.ColorArrayName = 'time' rgbPoints = [trange[0], 0.0, 0.0, 1.0, trange[1], 1.0, 0.0, 0.0] rep.LookupTable = smp.GetLookupTableForArray('time', 1, RGBPoints=rgbPoints, ScalarRangeInitialized=1.0) sb = smp.CreateScalarBar(LookupTable=rep.LookupTable, Title='Time') sb.Orientation = 'Horizontal' sb.Position, sb.Position2 = [.1, .05], [.8, .02] app.overheadView.Representations.append(sb) app.position = (posreader, None, g) smp.Render(app.overheadView) else: if positionFilename is not None: QtGui.QMessageBox.warning(getMainWindow(), 'Georeferncing data invalid', 'File %s is not supported' % positionFilename) smp.Delete(posreader) smp.SetActiveView(app.mainView) smp.SetActiveSource(reader) rep.InterpolateScalarsBeforeMapping = 0 setDefaultLookupTables(reader) colorByIntensity(reader) showSourceInSpreadSheet(reader) updateSliderTimeRange() updatePosition() enablePlaybackActions() enableSaveActions() addRecentFile(filename) app.actions['actionRecord'].setEnabled(False) app.actions['actionDualReturnModeDual'].enabled = True app.actions['actionDualReturnDistanceNear'].enabled = True app.actions['actionDualReturnDistanceFar'].enabled = True app.actions['actionDualReturnIntensityHigh'].enabled = True app.actions['actionDualReturnIntensityLow'].enabled = True resetCamera() def hideMeasurementGrid(): rep = smp.GetDisplayProperties(app.grid) rep.Visibility = 0 smp.Render() def showMeasurementGrid(): rep = smp.GetDisplayProperties(app.grid) rep.Visibility = 1 smp.Render() # Start Functions related to ruler def createRuler(): pxm = servermanager.ProxyManager() distancerep = pxm.NewProxy('representations', 'DistanceWidgetRepresentation') distancerepeasy = servermanager._getPyProxy(distancerep) smp.GetActiveView().Representations.append(distancerepeasy) distancerepeasy.Visibility = False smp.Render() return distancerepeasy def hideRuler(): app.ruler.Visibility = False smp.Render() def showRuler(): app.ruler.Visibility = True smp.Render() def getPointFromCoordinate(coord, midPlaneDistance = 0.5): assert len(coord) == 2 windowHeight = smp.GetActiveView().ViewSize[1] displayPoint = [coord[0], windowHeight - coord[1], midPlaneDistance] renderer = smp.GetActiveView().GetRenderer() renderer.SetDisplayPoint(displayPoint) renderer.DisplayToWorld() world1 = renderer.GetWorldPoint() return world1[:3] def toggleRulerContext(): measurmentState = app.actions['actionMeasure'].isChecked() mW = getMainWindow() vtkW = mW.findChild('pqQVTKWidget') if measurmentState == True: vtkW.connect('mouseEvent(QMouseEvent*)', setRulerCoordinates) elif measurmentState == False: vtkW.disconnect('mouseEvent(QMouseEvent*)', setRulerCoordinates) app.mousePressed = False hideRuler() def setRulerCoordinates(mouseEvent): pqView = smp.GetActiveView() rW = pqView.GetRenderWindow() windowInteractor = rW.GetInteractor() currentMouseState = mouseEvent.buttons() currentKeyboardState = mouseEvent.modifiers() if currentMouseState == 1: #Left button pressed if app.mousePressed == False: #For the first time if currentKeyboardState == 67108864: #Control key pressed app.mousePressed = True app.ruler.Point1WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) windowInteractor.Disable() elif app.mousePressed == True: #Not for the first time app.ruler.Point2WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) showRuler() smp.Render() elif currentMouseState == 0: #Left button released windowInteractor.Enable() if app.mousePressed == True: #For the first time app.mousePressed = False app.ruler.Point2WorldPosition = getPointFromCoordinate([mouseEvent.x(),mouseEvent.y()]) showRuler() smp.Render() # End Functions related to ruler def rotateCSVFile(filename): # read the csv file, move the last 3 columns to the # front, and then overwrite the file with the result csvFile = open(filename, 'rb') reader = csv.reader(csvFile, quoting=csv.QUOTE_NONNUMERIC) rows = [row[-3:] + row[:-3] for row in reader] csvFile.close() writer = csv.writer(open(filename, 'wb'), quoting=csv.QUOTE_NONNUMERIC, delimiter=',') writer.writerows(rows) def savePositionCSV(filename): w = smp.CreateWriter(filename, getPosition()) w.Precision = 16 w.FieldAssociation = 'Points' w.UpdatePipeline() smp.Delete(w) def saveCSVCurrentFrame(filename): w = smp.CreateWriter(filename, smp.GetActiveSource()) w.Precision = 16 w.FieldAssociation = 'Points' w.UpdatePipeline() smp.Delete(w) rotateCSVFile(filename) def saveLASFrames(filename, first, last, transform): reader = getReader().GetClientSideObject() position = getPosition().GetClientSideObject().GetOutput() PythonQt.paraview.pqVelodyneManager.saveFramesToLAS( reader, position, first, last, filename, transform) def saveLASCurrentFrame(filename, transform): t = app.scene.AnimationTime saveLASFrames(filename, t, t, transform) def saveAllFrames(filename, saveFunction): saveFunction(filename, getCurrentTimesteps()) def saveFrameRange(filename, frameStart, frameStop, saveFunction): timesteps = range(frameStart, frameStop+1) saveFunction(filename, timesteps) def saveCSV(filename, timesteps): tempDir = kiwiviewerExporter.tempfile.mkdtemp() basenameWithoutExtension = os.path.splitext(os.path.basename(filename))[0] outDir = os.path.join(tempDir, basenameWithoutExtension) filenameTemplate = os.path.join(outDir, basenameWithoutExtension + ' (Frame %04d).csv') os.makedirs(outDir) writer = smp.CreateWriter('tmp.csv', getSensor() or getReader()) writer.FieldAssociation = 'Points' writer.Precision = 16 for t in timesteps: app.scene.AnimationTime = t writer.FileName = filenameTemplate % t writer.UpdatePipeline() rotateCSVFile(writer.FileName) smp.Delete(writer) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def saveLAS(filename, timesteps, transform): tempDir = kiwiviewerExporter.tempfile.mkdtemp() basenameWithoutExtension = os.path.splitext(os.path.basename(filename))[0] outDir = os.path.join(tempDir, basenameWithoutExtension) filenameTemplate = os.path.join(outDir, basenameWithoutExtension + ' (Frame %04d).csv') os.makedirs(outDir) for t in sorted(timesteps): saveLASFrames(filenameTemplate % t, t, t, transform) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def getTimeStamp(): format = '%Y-%m-%d-%H-%M-%S' return datetime.datetime.now().strftime(format) def getSaveFileName(title, extension, defaultFileName=None): settings = getPVSettings() defaultDir = settings.value('VelodyneHDLPlugin/OpenData/DefaultDir', QtCore.QDir.homePath()) defaultFileName = defaultDir if not defaultFileName else os.path.join(defaultDir, defaultFileName) nativeDialog = 0 if app.actions['actionNative_File_Dialogs'].isChecked() else QtGui.QFileDialog.DontUseNativeDialog filters = '%s (*.%s)' % (extension, extension) selectedFilter = '*.%s' % extension fileName = QtGui.QFileDialog.getSaveFileName(getMainWindow(), title, defaultFileName, filters, selectedFilter, nativeDialog) if fileName: settings.setValue('VelodyneHDLPlugin/OpenData/DefaultDir', QtCore.QFileInfo(fileName).absoluteDir().absolutePath()) return fileName def restoreNativeFileDialogsAction(): settings = getPVSettings() app.actions['actionNative_File_Dialogs'].setChecked(int(settings.value('VelodyneHDLPlugin/NativeFileDialogs', 1))) def onNativeFileDialogsAction(): settings = getPVSettings() defaultDir = settings.setValue('VelodyneHDLPlugin/NativeFileDialogs', int(app.actions['actionNative_File_Dialogs'].isChecked())) def getFrameSelectionFromUser(frameStrideVisibility=False, framePackVisibility=False, frameTransformVisibility=False): class FrameOptions(object): pass dialog = PythonQt.paraview.vvSelectFramesDialog(getMainWindow()) dialog.frameMinimum = app.scene.StartTime dialog.frameMaximum = app.scene.EndTime dialog.frameStrideVisibility = frameStrideVisibility dialog.framePackVisibility = framePackVisibility dialog.frameTransformVisibility = frameTransformVisibility dialog.restoreState() if not dialog.exec_(): return None frameOptions = FrameOptions() frameOptions.mode = dialog.frameMode frameOptions.start = dialog.frameStart frameOptions.stop = dialog.frameStop frameOptions.stride = dialog.frameStride frameOptions.pack = dialog.framePack frameOptions.transform = dialog.frameTransform dialog.setParent(None) return frameOptions def onSaveCSV(): frameOptions = getFrameSelectionFromUser() if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: fileName = getSaveFileName('Save CSV', 'csv', getDefaultSaveFileName('csv', appendFrameNumber=True)) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveCSVCurrentFrame(fileName) setTransformMode(oldTransform) else: fileName = getSaveFileName('Save CSV (to zip file)', 'zip', getDefaultSaveFileName('zip')) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) if frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: saveAllFrames(fileName, saveCSV) else: start = frameOptions.start stop = frameOptions.stop saveFrameRange(fileName, start, stop, saveCSV) setTransformMode(oldTransform) def onSavePosition(): fileName = getSaveFileName('Save CSV', 'csv', getDefaultSaveFileName('csv', '-position')) if fileName: savePositionCSV(fileName) def onSaveLAS(): frameOptions = getFrameSelectionFromUser(framePackVisibility=True, frameTransformVisibility=False) if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: frameOptions.start = frameOptions.stop = app.scene.AnimationTime elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: frameOptions.start = int(app.scene.StartTime) frameOptions.stop = int(app.scene.EndTime) if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: fileName = getSaveFileName('Save LAS', 'las', getDefaultSaveFileName('las', appendFrameNumber=True)) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveLASCurrentFrame(fileName, frameOptions.transform) setTransformMode(oldTransform) elif frameOptions.pack == vvSelectFramesDialog.FILE_PER_FRAME: fileName = getSaveFileName('Save LAS (to zip file)', 'zip', getDefaultSaveFileName('zip')) if fileName: oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) def saveTransformedLAS(filename, timesteps): saveLAS(filename, timesteps, frameOptions.transform) if frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: saveAllFrames(fileName, saveTransformedLAS) else: start = frameOptions.start stop = frameOptions.stop saveFrameRange(fileName, start, stop, saveTransformedLAS) setTransformMode(oldTransform) else: suffix = ' (Frame %d to %d)' % (frameOptions.start, frameOptions.stop) defaultFileName = getDefaultSaveFileName('las', suffix=suffix) fileName = getSaveFileName('Save LAS', 'las', defaultFileName) if not fileName: return oldTransform = transformMode() setTransformMode(1 if frameOptions.transform else 0) saveLASFrames(fileName, frameOptions.start, frameOptions.stop, frameOptions.transform) setTransformMode(oldTransform) def onSavePCAP(): frameOptions = getFrameSelectionFromUser(frameTransformVisibility=False) if frameOptions is None: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: frameOptions.start = frameOptions.stop = app.scene.AnimationTime elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: frameOptions.start = int(app.scene.StartTime) frameOptions.stop = int(app.scene.EndTime) defaultFileName = getDefaultSaveFileName('pcap', suffix=' (Frame %d to %d)' % (frameOptions.start, frameOptions.stop)) fileName = getSaveFileName('Save PCAP', 'pcap', defaultFileName) if not fileName: return PythonQt.paraview.pqVelodyneManager.saveFramesToPCAP(getReader().SMProxy, frameOptions.start, frameOptions.stop, fileName) def onSaveScreenshot(): fileName = getSaveFileName('Save Screenshot', 'png', getDefaultSaveFileName('png', appendFrameNumber=True)) if fileName: saveScreenshot(fileName) def onKiwiViewerExport(): frameOptions = getFrameSelectionFromUser(frameStrideVisibility=True, frameTransformVisibility=False) if frameOptions is None: return defaultFileName = getDefaultSaveFileName('zip', suffix=' (KiwiViewer)') fileName = getSaveFileName('Export To KiwiViewer', 'zip', defaultFileName) if not fileName: return if frameOptions.mode == vvSelectFramesDialog.CURRENT_FRAME: timesteps = [app.scene.AnimationTime] elif frameOptions.mode == vvSelectFramesDialog.ALL_FRAMES: timesteps = range(int(app.scene.StartTime), int(app.scene.EndTime) + 1, frameOptions.stride) else: timesteps = range(frameOptions.start, frameOptions.stop+1, frameOptions.stride) saveToKiwiViewer(fileName, timesteps) def saveToKiwiViewer(filename, timesteps): tempDir = kiwiviewerExporter.tempfile.mkdtemp() outDir = os.path.join(tempDir, os.path.splitext(os.path.basename(filename))[0]) os.makedirs(outDir) filenames = exportToDirectory(outDir, timesteps) kiwiviewerExporter.writeJsonData(outDir, smp.GetActiveView(), smp.GetDisplayProperties(), filenames) kiwiviewerExporter.zipDir(outDir, filename) kiwiviewerExporter.shutil.rmtree(tempDir) def exportToDirectory(outDir, timesteps): filenames = [] alg = smp.GetActiveSource().GetClientSideObject() writer = vtkXMLPolyDataWriter() writer.SetDataModeToAppended() writer.EncodeAppendedDataOff() writer.SetCompressorTypeToZLib() for t in timesteps: filename = 'frame_%04d.vtp' % t filenames.append(filename) app.scene.AnimationTime = t polyData = vtk.vtkPolyData() polyData.ShallowCopy(alg.GetOutput()) writer.SetInputData(polyData) writer.SetFileName(os.path.join(outDir, filename)) writer.Update() return filenames def getVersionString(): return QtGui.QApplication.instance().applicationVersion def onDeveloperGuide(): basePath = PythonQt.QtGui.QApplication.instance().applicationDirPath() paths = ['../Resources/VeloView_Developer_Guide.pdf'] for path in paths: filename = os.path.join(basePath, path) if os.path.isfile(filename): QtGui.QDesktopServices.openUrl(QtCore.QUrl('file:///%s' % filename, QtCore.QUrl.TolerantMode)) def onUserGuide(): basePath = PythonQt.QtGui.QApplication.instance().applicationDirPath() paths = ['../Resources/VeloView_User_Guide.pdf'] for path in paths: filename = os.path.join(basePath, path) if os.path.isfile(filename): QtGui.QDesktopServices.openUrl(QtCore.QUrl('file:///%s' % filename, QtCore.QUrl.TolerantMode)) def onAbout(): title = 'About VeloView' text = '''<h1>VeloView %s</h1><br/>Copyright (c) 2013, <NAME><br /> Sample Data Repository: <a href=http://midas3.kitware.com/midas/community/29>http://midas3.kitware.com/midas/community/29</a>'''% getVersionString() QtGui.QMessageBox.about(getMainWindow(), title, text) def close(): stop() hideRuler() unloadData() smp.Render(app.overheadView) app.scene.AnimationTime = 0 app.reader = None app.sensor = None smp.HideUnusedScalarBars() resetCameraToForwardView() app.filenameLabel.setText('') app.statusLabel.setText('') app.timeLabel.setText('') updateSliderTimeRange() disablePlaybackActions() disableSaveActions() app.actions['actionRecord'].setChecked(False) app.actions['actionDualReturnModeDual'].setChecked(True) app.actions['actionDualReturnModeDual'].enabled = False app.actions['actionDualReturnDistanceNear'].enabled = False app.actions['actionDualReturnDistanceFar'].enabled = False app.actions['actionDualReturnIntensityHigh'].enabled = False app.actions['actionDualReturnIntensityLow'].enabled = False def seekForward(): if app.playing: if app.playDirection < 0 or app.playDirection == 5: app.playDirection = 0 app.playDirection += 1 updateSeekButtons() else: gotoNext() def seekBackward(): if app.playing: if app.playDirection > 0 or app.playDirection == -5: app.playDirection = 0 app.playDirection -= 1 updateSeekButtons() else: gotoPrevious() def seekPressTimeout(): app.seekPlay = True onPlayTimer() def seekForwardPressed(): app.seekPlayDirection = 1 if not app.playing: app.seekTimer.start(500) def seekForwardReleased(): app.seekTimer.stop() app.seekPlay = False def seekBackwardPressed(): app.seekPlayDirection = -1 if not app.playing: app.seekTimer.start(500) def seekBackwardReleased(): seekForwardReleased() def updateSeekButtons(): icons = { -5 : IconPaths.seekBackwardQuarterx, -4 : IconPaths.seekBackwardHalfx, -3 : IconPaths.seekBackward3x, -2 : IconPaths.seekBackward2x, -1 : IconPaths.seekBackward, 1 : IconPaths.seekForward, 2 : IconPaths.seekForward2x, 3 : IconPaths.seekForward3x, 4 : IconPaths.seekForwardHalfx, 5 : IconPaths.seekForwardQuarterx, } setActionIcon('actionSeek_Backward', icons[app.playDirection] if app.playDirection < 0 else IconPaths.seekBackward) setActionIcon('actionSeek_Forward', icons[app.playDirection] if app.playDirection > 0 else IconPaths.seekForward) fpsMap = {-5:5, 5:5, -4:11, 4:11} fpsDefault = 30 app.targetFps = fpsMap.get(app.playDirection, fpsDefault) def setPlaybackActionsEnabled(enabled): for action in ('Play', 'Record', 'Seek_Forward', 'Seek_Backward', 'Go_To_Start', 'Go_To_End'): app.actions['action'+action].setEnabled(enabled) def enablePlaybackActions(): setPlaybackActionsEnabled(True) def disablePlaybackActions(): setPlaybackActionsEnabled(False) def _setSaveActionsEnabled(enabled): for action in ('SaveCSV', 'SavePCAP', 'SaveLAS', 'Export_To_KiwiViewer', 'Close', 'Choose_Calibration_File', 'CropReturns'): app.actions['action'+action].setEnabled(enabled) getMainWindow().findChild('QMenu', 'menuSaveAs').enabled = enabled def enableSaveActions(): _setSaveActionsEnabled(True) if getPosition(): app.actions['actionSavePositionCSV'].setEnabled(True) def disableSaveActions(): _setSaveActionsEnabled(False) app.actions['actionSavePositionCSV'].setEnabled(False) def recordFile(filename): sensor = getSensor() if sensor: stopStream() sensor.OutputFile = filename app.statusLabel.setText(' Recording file: %s.' % os.path.basename(filename)) if app.playing: startStream() def onRecord(): recordAction = app.actions['actionRecord'] if not recordAction.isChecked(): stopRecording() else: fileName = getSaveFileName('Choose Output File', 'pcap', getDefaultSaveFileName('pcap')) if not fileName: recordAction.setChecked(False) return recordFile(fileName) def stopRecording(): app.statusLabel.setText('') sensor = getSensor() if sensor: stopStream() sensor.OutputFile = '' if app.playing: startStream() def startStream(): sensor = getSensor() if sensor: sensor.Start() def stopStream(): sensor = getSensor() if sensor: sensor.Stop() def pollSource(): source = getSensor() reader = getReader() if source is not None: source.Poll() source.UpdatePipelineInformation() return source or reader def getPointCloudData(attribute=None): if attribute is not None: data = getPointCloudData() if data: if attribute == 'points': return data.GetPoints().GetData() else: return data.GetPointData().GetArray(attribute) else: source = getSensor() or getReader() if source: return source.GetClientSideObject().GetOutput() def getCurrentTimesteps(): source = pollSource() return list(source.TimestepValues) if source is not None else [] def getNumberOfTimesteps(): return getTimeKeeper().getNumberOfTimeStepValues() def togglePlay(): setPlayMode(not app.playing) def play(): setPlayMode(True) def stop(): setPlayMode(False) def onPlayTimer(): if app.playing or app.seekPlay: startTime = vtk.vtkTimerLog.GetUniversalTime() playbackTick() fpsDelayMilliseconds = int(1000.0 / app.targetFps) elapsedMilliseconds = int((vtk.vtkTimerLog.GetUniversalTime() - startTime)*1000.0) if elapsedMilliseconds > 0: fps = 1000.0/elapsedMilliseconds app.fps[0] += fps app.fps[1] += 1 waitMilliseconds = fpsDelayMilliseconds - elapsedMilliseconds app.playTimer.start(max(waitMilliseconds,0)) def setPlayMode(mode): if not getReader() and not getSensor(): return app.playing = mode if mode: startStream() setActionIcon('actionPlay', IconPaths.pause) app.playTimer.start(33) if app.scene.AnimationTime == app.scene.EndTime: app.scene.AnimationTime = app.scene.StartTime else: stopStream() setActionIcon('actionPlay', IconPaths.play) app.playDirection = 1 updateSeekButtons() def gotoStart(): pollSource() app.scene.GoToFirst() updatePosition() def gotoEnd(): pollSource() app.scene.GoToLast() updatePosition() def gotoNext(): pollSource() app.scene.GoToNext() updatePosition() def gotoPrevious(): pollSource() app.scene.GoToPrevious() updatePosition() def updatePosition(): reader = getReader() pos = getPosition() if reader and pos: pointcloud = reader.GetClientSideObject().GetOutput() if pointcloud.GetNumberOfPoints(): # Update the overhead view # TODO: Approximate time, just grabbing the last t = pointcloud.GetPointData().GetScalars('adjustedtime') #currentTime = t.GetTuple1(t.GetNumberOfTuples() - 1) currentTime = t.GetTuple1(0) * 1e-6 interp = getPosition().GetClientSideObject().GetInterpolator() trange = [interp.GetMinimumT(), interp.GetMaximumT()] # Clamp currentTime = min(max(currentTime, trange[0]+1.0e-1), trange[1]-1.0e-1) position = [0.0] * 3 transform = vtk.vtkTransform() interp.InterpolateTransform(currentTime, transform) transform.TransformPoint(position, position) rep = cachedGetRepresentation(reader, view=app.mainView) if app.relativeTransform: rep.Position = transform.GetInverse().GetPosition() rep.Orientation = transform.GetInverse().GetOrientation() else: rep.Position = [0.0, 0.0, 0.0] rep.Orientation = [0.0, 0.0, 0.0] g = getGlyph() rep = cachedGetRepresentation(g, view=app.overheadView) rep.Position = position[:3] def playbackTick(): sensor = getSensor() reader = getReader() view = smp.GetActiveView() if sensor is not None: timesteps = getCurrentTimesteps() if not timesteps: return if view.ViewTime == timesteps[-1]: return if not app.colorByInitialized: sensor.UpdatePipeline() if colorByIntensity(sensor): app.colorByInitialized = True resetCamera() app.scene.GoToLast() elif reader is not None: numberOfTimesteps = getNumberOfTimesteps() if not numberOfTimesteps: return step = app.seekPlayDirection if app.seekPlay else app.playDirection stepMap = {4:1, 5:1, -4:-1, -5:-1} step = stepMap.get(step, step) newTime = app.scene.AnimationTime + step if app.actions['actionLoop'].isChecked(): newTime = newTime % numberOfTimesteps else: newTime = max(app.scene.StartTime, min(newTime, app.scene.EndTime)) # stop playback when it reaches the first or last timestep if newTime in (app.scene.StartTime, app.scene.EndTime): stop() app.scene.AnimationTime = newTime # TODO: For sensor as well? updatePosition() def unloadData(): _repCache.clear() for k, src in smp.GetSources().iteritems(): if src != app.grid: smp.Delete(src) toremove = [x for x in app.overheadView.Representations if type(x) == servermanager.rendering.ScalarBarWidgetRepresentation] for t in toremove: app.overheadView.Representations.remove(t) app.reader = None app.position = (None, None, None) app.sensor = None clearSpreadSheetView() def getReader(): return getattr(app, 'reader', None) def getSensor(): return getattr(app, 'sensor', None) def getPosition(): return getattr(app, 'position', (None, None, None))[0] def getGlyph(): return getattr(app, 'position', (None, None, None))[2] def onChooseCalibrationFile(): calibration = chooseCalibration() if not calibration: return calibrationFile = calibration.calibrationFile sensorTransform = calibration.sensorTransform reader = getReader() sensor = getSensor() if reader is not None: reader.GetClientSideObject().SetSensorTransform(sensorTransform) reader.CalibrationFile = calibrationFile reader.DummyProperty = not reader.DummyProperty smp.Render() elif sensor is not None: sensor.GetClientSideObject().SetSensorTransform(sensorTransform) sensor.CalibrationFile = calibrationFile # no need to render now, calibration file will be used on the next frame def onCropReturns(show = True): dialog = vvCropReturnsDialog(getMainWindow()) cropEnabled = False cropInside = False firstCorner = QtGui.QVector3D() secondCorner = QtGui.QVector3D() reader = getReader() sensor = getSensor() if reader is not None: cropEnabled = reader.CropReturns cropInside = reader.CropInside firstCorner = QtGui.QVector3D(reader.CropRegion[0], reader.CropRegion[2], reader.CropRegion[4]) secondCorner = QtGui.QVector3D(reader.CropRegion[1], reader.CropRegion[3], reader.CropRegion[5]) if sensor is not None: cropEnabled = sensor.CropReturns cropInside = sensor.CropInside firstCorner = QtGui.QVector3D(sensor.CropRegion[0], sensor.CropRegion[2], sensor.CropRegion[4]) secondCorner = QtGui.QVector3D(sensor.CropRegion[1], sensor.CropRegion[3], sensor.CropRegion[5]) if show: dialog.croppingEnabled = cropEnabled dialog.cropInside = cropInside dialog.firstCorner = firstCorner dialog.secondCorner = secondCorner if not dialog.exec_(): return if reader is not None: reader.CropReturns = dialog.croppingEnabled reader.CropInside = dialog.cropInside p1 = dialog.firstCorner p2 = dialog.secondCorner reader.CropRegion = [p1.x(), p2.x(), p1.y(), p2.y(), p1.z(), p2.z()] if show: smp.Render() if sensor is not None: sensor.CropReturns = dialog.croppingEnabled sensor.CropInside = dialog.cropInside p1 = dialog.firstCorner p2 = dialog.secondCorner sensor.CropRegion = [p1.x(), p2.x(), p1.y(), p2.y(), p1.z(), p2.z()] if show: smp.Render() def resetCamera(): def subtract(a, b): result = range(3) vtk.vtkMath.Subtract(a, b, result) return result def cross(a, b): result = range(3) vtk.vtkMath.Cross(a, b, result) return result view = smp.GetActiveView() foc = list(view.CenterOfRotation) pos = list(view.CameraPosition) viewDirection = subtract(foc, pos) view.CameraPosition = subtract([0, 0, 0], viewDirection) view.CameraFocalPoint = [0, 0, 0] view.CenterOfRotation = [0, 0, 0] vtk.vtkMath.Normalize(viewDirection) perp = cross(viewDirection, [0, 0, 1]) viewUp = cross(perp, viewDirection) view.CameraViewUp = viewUp view.StillRender() def resetCameraToBirdsEyeView(view=None): view = view or smp.GetActiveView() view.CameraFocalPoint = [0, 0, 0] view.CameraViewUp = [0, 1, 0] view.CameraPosition = [0, 0, 40] view.CenterOfRotation = [0, 0, 0] smp.Render(view) def resetCameraToForwardView(view=None): view = view or smp.GetActiveView() view.CameraFocalPoint = [0,0,0] view.CameraViewUp = [0, 0.27, 0.96] view.CameraPosition = [0, -72, 18.0] view.CenterOfRotation = [0, 0, 0] smp.Render(view) def saveScreenshot(filename): smp.WriteImage(filename) # reload the saved screenshot as a pixmap screenshot = QtGui.QPixmap() screenshot.load(filename) # create a new pixmap with the status bar widget painted at the bottom statusBar = QtGui.QPixmap.grabWidget(getMainWindow().statusBar()) composite = QtGui.QPixmap(screenshot.width(), screenshot.height() + statusBar.height()) painter = QtGui.QPainter() painter.begin(composite) painter.drawPixmap(screenshot.rect(), screenshot, screenshot.rect()) painter.drawPixmap(statusBar.rect().translated(0, screenshot.height()), statusBar, statusBar.rect()) painter.end() # save final screenshot composite.save(filename) def getSpreadSheetViewProxy(): for p in smp.servermanager.ProxyManager(): if p.GetXMLName() == 'SpreadSheetView': return p def clearSpreadSheetView(): view = getSpreadSheetViewProxy() view.Representations = [] def showSourceInSpreadSheet(source): spreadSheetView = getSpreadSheetViewProxy() smp.Show(source, spreadSheetView) # Work around a bug where the 'Showing' combobox doesn't update. # Calling hide and show again will trigger the refresh. smp.Hide(source, spreadSheetView) smp.Show(source, spreadSheetView) def createGrid(view=None): view = view or smp.GetActiveView() grid = smp.VelodyneHDLGridSource(guiName='Measurement Grid') rep = smp.Show(grid, view) rep.DiffuseColor = [0.2, 0.2, 0.2] rep.Pickable = 0 rep.Visibility = 0 smp.SetActiveSource(None) return grid def hideGrid(): smp.GetDisplayProperties(app.grid).Hide() def showGrid(): smp.GetDisplayProperties(app.grid).Show() def getAnimationScene(): '''This function is a workaround because paraview.simple.GetAnimationScene() has an issue where the returned proxy might not have its Cues property initialized''' for proxy in servermanager.ProxyManager().GetProxiesInGroup("animation").values(): if proxy.GetXMLName() == 'AnimationScene' and len(proxy.Cues): return proxy def start(): global app app = AppLogic() app.scene = getAnimationScene() view = smp.GetActiveView() view.Background = [0.0, 0.0, 0.0] view.Background2 = [0.0, 0.0, 0.2] view.UseGradientBackground = True smp._DisableFirstRenderCameraReset() smp.GetActiveView().LODThreshold = 1e100 app.grid = createGrid() app.ruler = createRuler() resetCameraToForwardView() setupActions() disablePlaybackActions() disableSaveActions() app.actions['actionMeasure'].setEnabled(view.CameraParallelProjection) setupStatusBar() setupTimeSliderWidget() hideColorByComponent() restoreNativeFileDialogsAction() updateRecentFiles() getTimeKeeper().connect('timeChanged()', onTimeChanged) def findQObjectByName(widgets, name): for w in widgets: if w.objectName == name: return w def getMainWindow(): return findQObjectByName(QtGui.QApplication.topLevelWidgets(), 'vvMainWindow') def getPVApplicationCore(): return PythonQt.paraview.pqPVApplicationCore.instance() def getPVSettings(): return getPVApplicationCore().settings() def getTimeKeeper(): return getPVApplicationCore().getActiveServer().getTimeKeeper() def getPlaybackToolBar(): return findQObjectByName(getMainWindow().children(), 'playbackToolbar') def quit(): PythonQt.QtGui.QApplication.instance().quit() exit = quit def addShortcuts(keySequenceStr, function): shortcut = PythonQt.QtGui.QShortcut(PythonQt.QtGui.QKeySequence(keySequenceStr), getMainWindow()) shortcut.connect("activated()", function) def onTrailingFramesChanged(numFrames): try: app.reader.NumberOfTrailingFrames = numFrames smp.Render() smp.Render(getSpreadSheetViewProxy()) except AttributeError: pass def onPointsSkipChanged(pr): try: app.reader.PointsSkip = pr smp.Render() smp.Render(getSpreadSheetViewProxy()) except AttributeError: pass def setupTimeSliderWidget(): frame = QtGui.QWidget() layout = QtGui.QHBoxLayout(frame) spinBox = QtGui.QSpinBox() spinBox.setMinimum(0) spinBox.setMaximum(100) spinBox.setValue(0) slider = QtGui.QSlider(QtCore.Qt.Horizontal) slider.setMaximumWidth(160) slider.connect('valueChanged(int)', onTimeSliderChanged) spinBox.connect('valueChanged(int)', onTimeSliderChanged) slider.setEnabled(False) spinBox.setEnabled(False) layout.addWidget(slider) layout.addWidget(spinBox) layout.addStretch() toolbar = getPlaybackToolBar() toolbar.addWidget(frame) app.timeSlider = slider app.timeSpinBox = spinBox def updateSliderTimeRange(): frame = int(app.scene.AnimationTime) lastFrame = int(app.scene.EndTime) for widget in (app.timeSlider, app.timeSpinBox): widget.setMinimum(0) widget.setMaximum(lastFrame) widget.setSingleStep(1) if hasattr(widget, 'setPageStep'): widget.setPageStep(10) widget.setValue(frame) widget.setEnabled(getNumberOfTimesteps()) def scheduleRender(): if not app.renderIsPending: app.renderIsPending = True app.renderTimer.start(33) def forceRender(): smp.Render() app.renderIsPending = False def onTimeSliderChanged(frame): app.scene.AnimationTime = frame updatePosition() def setupStatusBar(): statusBar = getMainWindow().statusBar() statusBar.addPermanentWidget(app.logoLabel) statusBar.addWidget(app.filenameLabel) statusBar.addWidget(app.statusLabel) statusBar.addWidget(app.timeLabel) def setActionIcon(actionName, iconPath): app.actions[actionName].setIcon(QtGui.QIcon(QtGui.QPixmap(iconPath))) def onTimeChanged(): frame = int(getTimeKeeper().getTime()) app.timeLabel.setText(' Frame: %s' % frame) for widget in (app.timeSlider, app.timeSpinBox): widget.blockSignals(True) widget.setValue(frame) widget.blockSignals(False) def onGridProperties(): if gridAdjustmentDialog.showDialog(getMainWindow(), app.grid): smp.Render() def onLaserSelection(show = True): oldmask = [1] * 64 reader = getReader() sensor = getSensor() corrections = [0] * 64 nchannels = 32 if reader: reader.GetClientSideObject().GetLaserSelection(oldmask) reader.GetClientSideObject().GetVerticalCorrections(corrections) nchannels = reader.GetPropertyValue('NumberOfChannels') elif sensor: sensor.GetClientSideObject().GetLaserSelection(oldmask) sensor.GetClientSideObject().GetVerticalCorrections(corrections) nchannels = sensor.GetPropertyValue('NumberOfChannels') # Need a way to initialize the mask dialog = PythonQt.paraview.vvLaserSelectionDialog(getMainWindow()) if show: dialog.setLaserSelectionSelector(oldmask) dialog.setVerticalCorrections(corrections, nchannels) if not dialog.exec_(): return mask = dialog.getLaserSelectionSelector() if reader: reader.GetClientSideObject().SetLaserSelection(mask) reader.DummyProperty = not reader.DummyProperty if show: smp.Render() smp.Render(getSpreadSheetViewProxy()) if sensor: sensor.GetClientSideObject().SetLaserSelection(mask) sensor.DummyProperty = not sensor.DummyProperty if show: smp.Render() smp.Render(getSpreadSheetViewProxy()) def hideColorByComponent(): getMainWindow().findChild('vvColorToolbar').findChild('pqDisplayColorWidget').findChildren('QComboBox')[1].hide() def addRecentFile(filename): recentFiles = getRecentFiles() try: recentFiles.remove(filename) except ValueError: pass recentFiles = recentFiles[:4] recentFiles.insert(0, filename) getPVSettings().setValue('VelodyneHDLPlugin/RecentFiles', recentFiles) updateRecentFiles() def openRecentFile(filename): if not os.path.isfile(filename): QtGui.QMessageBox.warning(getMainWindow(), 'File not found', 'File not found: %s' % filename) return if os.path.splitext(filename)[1].lower() == '.pcap': openPCAP(filename) else: openData(filename) def getRecentFiles(): return list(getPVSettings().value('VelodyneHDLPlugin/RecentFiles', []) or []) def updateRecentFiles(): settings = getPVSettings() recentFiles = getRecentFiles() recentFilesMenu = findQObjectByName(findQObjectByName(getMainWindow().menuBar().children(), 'menu_File').children(), 'menuRecent_Files') clearMenuAction = app.actions['actionClear_Menu'] for action in recentFilesMenu.actions()[:-2]: recentFilesMenu.removeAction(action) def createActionFunction(filename): def f(): openRecentFile(filename) return f actions = [] for filename in recentFiles: actions.append(QtGui.QAction(os.path.basename(filename), recentFilesMenu)) actions[-1].connect('triggered()', createActionFunction(filename)) recentFilesMenu.insertActions(recentFilesMenu.actions()[0], actions) def onClearMenu(): settings = getPVSettings() settings.setValue('VelodyneHDLPlugin/RecentFiles', []) updateRecentFiles() def toggleProjectionType(): view = smp.GetActiveView() view.CameraParallelProjection = not view.CameraParallelProjection if app.actions['actionMeasure'].isChecked(): app.actions['actionMeasure'].trigger() app.actions['actionMeasure'].toggle() app.actions['actionMeasure'].setEnabled(view.CameraParallelProjection) smp.Render() def setViewTo(axis,sign): view = smp.GetActiveView() viewUp = view.CameraViewUp position = view.CameraPosition norm = math.sqrt(math.pow(position[0],2) + math.pow(position[1],2) + math.pow(position[2],2)) if axis == 'X': view.CameraViewUp = [0,0,1] view.CameraPosition = [-1*sign*norm,0,0] elif axis == 'Y': view.CameraViewUp = [0,0,1] view.CameraPosition = [0,-1*sign*norm,0] elif axis == 'Z': view.CameraViewUp = [0,1,0] view.CameraPosition = [0,0,-1*sign*norm] view.CameraFocalPoint = [0,0,0] view.CenterOfRotation = [0,0,0] view.ResetCamera() smp.Render() def setViewToXPlus(): setViewTo('X',1) def setViewToXMinus(): setViewTo('X',-1) def setViewToYPlus(): setViewTo('Y',1) def setViewToYMinus(): setViewTo('Y',-1) def setViewToZPlus(): setViewTo('Z',1) def setViewToZMinus(): setViewTo('Z',-1) def setFilterToDual(): setFilterTo(0) def setFilterToDistanceNear(): setFilterTo(vtkVelodyneHDLReader.DUAL_DISTANCE_NEAR) def setFilterToDistanceFar(): setFilterTo(vtkVelodyneHDLReader.DUAL_DISTANCE_FAR) def setFilterToIntensityHigh(): setFilterTo(vtkVelodyneHDLReader.DUAL_INTENSITY_HIGH) def setFilterToIntensityLow(): setFilterTo(vtkVelodyneHDLReader.DUAL_INTENSITY_LOW) def setFilterTo(mask): reader = getReader() if reader: reader.DualReturnFilter = mask smp.Render() smp.Render(getSpreadSheetViewProxy()) sensor = getSensor() if sensor: sensor.DualReturnFilter = mask smp.Render() smp.Render(getSpreadSheetViewProxy()) def transformMode(): reader = getReader() if not reader: return None if reader.ApplyTransform: if app.relativeTransform: return 2 # relative else: return 1 # absolute return 0 # raw def setTransformMode(mode): # 0 - raw # 1 - absolute # 2 - relative reader = getReader() if reader: reader.ApplyTransform = (mode > 0) app.transformMode = mode app.relativeTransform = (mode == 2) def geolocationChanged(setting): setTransformMode(setting) updatePosition() smp.Render(view=app.mainView) def setupActions(): mW = getMainWindow() actions = mW.findChildren('QAction') app.actions = {} for a in actions: app.actions[a.objectName] = a app.actions['actionPlaneFit'].connect('triggered()', planeFit) app.actions['actionClose'].connect('triggered()', close) app.actions['actionPlay'].connect('triggered()', togglePlay) app.actions['actionRecord'].connect('triggered()', onRecord) app.actions['actionSaveCSV'].connect('triggered()', onSaveCSV) app.actions['actionSavePositionCSV'].connect('triggered()', onSavePosition) app.actions['actionSaveLAS'].connect('triggered()', onSaveLAS) app.actions['actionSavePCAP'].connect('triggered()', onSavePCAP) app.actions['actionSaveScreenshot'].connect('triggered()', onSaveScreenshot) app.actions['actionExport_To_KiwiViewer'].connect('triggered()', onKiwiViewerExport) app.actions['actionReset_Camera'].connect('triggered()', resetCamera) app.actions['actionGrid_Properties'].connect('triggered()', onGridProperties) app.actions['actionLaserSelection'].connect('triggered()', onLaserSelection) app.actions['actionChoose_Calibration_File'].connect('triggered()', onChooseCalibrationFile) app.actions['actionCropReturns'].connect('triggered()', onCropReturns) app.actions['actionSeek_Forward'].connect('triggered()', seekForward) app.actions['actionSeek_Backward'].connect('triggered()', seekBackward) app.actions['actionGo_To_End'].connect('triggered()', gotoEnd) app.actions['actionGo_To_Start'].connect('triggered()', gotoStart) app.actions['actionNative_File_Dialogs'].connect('triggered()', onNativeFileDialogsAction) app.actions['actionAbout_VeloView'].connect('triggered()', onAbout) app.actions['actionVeloViewDeveloperGuide'].connect('triggered()', onDeveloperGuide) app.actions['actionClear_Menu'].connect('triggered()', onClearMenu) app.actions['actionToggleProjection'].connect('triggered()', toggleProjectionType) app.actions['actionMeasure'].connect('triggered()', toggleRulerContext) app.actions['actionSetViewXPlus'].connect('triggered()', setViewToXPlus) app.actions['actionSetViewXMinus'].connect('triggered()', setViewToXMinus) app.actions['actionSetViewYPlus'].connect('triggered()', setViewToYPlus) app.actions['actionSetViewYMinus'].connect('triggered()', setViewToYMinus) app.actions['actionSetViewZPlus'].connect('triggered()', setViewToZPlus) app.actions['actionSetViewZMinus'].connect('triggered()', setViewToZMinus) app.actions['actionDualReturnModeDual'].connect('triggered()', setFilterToDual) app.actions['actionDualReturnDistanceNear'].connect('triggered()', setFilterToDistanceNear) app.actions['actionDualReturnDistanceFar'].connect('triggered()', setFilterToDistanceFar) app.actions['actionDualReturnIntensityHigh'].connect('triggered()', setFilterToIntensityHigh) app.actions['actionDualReturnIntensityLow'].connect('triggered()', setFilterToIntensityLow) # Action created # timeToolBar = mW.findChild('QToolBar','playbackToolbar') geolocationToolBar = mW.findChild('QToolBar', 'geolocationToolbar') comboBox = QtGui.QComboBox() comboBox.addItem('Relative RAW') comboBox.addItem('Absolute Geolocation') comboBox.addItem('Relative Geolocation') comboBox.connect('currentIndexChanged(int)', geolocationChanged) geolocationToolBar.addWidget(comboBox) spinBoxLabel = QtGui.QLabel('TF:') spinBoxLabel.toolTip = "Number of trailing frames" timeToolBar.addWidget(spinBoxLabel) spinBox = QtGui.QSpinBox() spinBox.toolTip = "Number of trailing frames" spinBox.setMinimum(0) spinBox.setMaximum(100) spinBox.connect('valueChanged(int)', onTrailingFramesChanged) app.trailingFramesSpinBox = spinBox app.actions['actionTrailingFramesSelector'] = timeToolBar.addWidget(spinBox) app.actions['actionTrailingFramesSelector'].setVisible(True) pointsSkipLabel = QtGui.QLabel('Skip:') pointsSkipLabel.toolTip = "Number of Points to Skip" timeToolBar.addWidget(pointsSkipLabel) pointsSkipBox = QtGui.QSpinBox() pointsSkipBox.toolTip = "Number of Points to Skip" pointsSkipBox.setMinimum(0) pointsSkipBox.setMaximum(100) pointsSkipBox.connect('valueChanged(int)', onPointsSkipChanged) app.pointsSkipSpinBox = pointsSkipBox app.actions['actionPointsSkipSelector'] = timeToolBar.addWidget(pointsSkipBox) app.actions['actionPointsSkipSelector'].setVisible(True) buttons = {} for button in getPlaybackToolBar().findChildren('QToolButton'): buttons[button.text] = button buttons['Seek Forward'].connect('pressed()', seekForwardPressed) buttons['Seek Forward'].connect('released()', seekForwardReleased) buttons['Seek Backward'].connect('pressed()', seekBackwardPressed) buttons['Seek Backward'].connect('released()', seekBackwardReleased)
en
0.791256
# Copyright 2013 Velodyne Acoustics, 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. Returns True if the data has non-zero points and has a point data attribute with the given arrayName. # LUT for 'intensity' # LUT for 'dual_distance' # LUT for 'dual_intensity' # Dont show the dialog just restore settings # construct the reader, this calls UpdateInformation on the # reader which scans the pcap file and emits progress events # Dont show the dialog just restore settings # update overhead view # Create a sphere glyph # By construction time zero is at position 0,0,0 # Setup scalar bar # Start Functions related to ruler #Left button pressed #For the first time #Control key pressed #Not for the first time #Left button released #For the first time # End Functions related to ruler # read the csv file, move the last 3 columns to the # front, and then overwrite the file with the result <h1>VeloView %s</h1><br/>Copyright (c) 2013, <NAME><br /> Sample Data Repository: <a href=http://midas3.kitware.com/midas/community/29>http://midas3.kitware.com/midas/community/29</a> # Update the overhead view # TODO: Approximate time, just grabbing the last #currentTime = t.GetTuple1(t.GetNumberOfTuples() - 1) # Clamp # stop playback when it reaches the first or last timestep # TODO: For sensor as well? # no need to render now, calibration file will be used on the next frame # reload the saved screenshot as a pixmap # create a new pixmap with the status bar widget painted at the bottom # save final screenshot # Work around a bug where the 'Showing' combobox doesn't update. # Calling hide and show again will trigger the refresh. This function is a workaround because paraview.simple.GetAnimationScene() has an issue where the returned proxy might not have its Cues property initialized # Need a way to initialize the mask # relative # absolute # raw # 0 - raw # 1 - absolute # 2 - relative # Action created #
1.860877
2
examples/example_mapping.py
JulienLefevreMars/slam
6
6630541
""" .. _example_mapping: =================================== Mapping example in slam =================================== """ # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD (3-clause) # sphinx_gallery_thumbnail_number = 2 ############################################################################### # Importation of slam modules import slam.generate_parametric_surfaces as sps import numpy as np import slam.topology as stop import slam.plot as splt import slam.mapping as smap import slam.distortion as sdst from vispy.scene import Line from visbrain.objects import VispyObj, SourceObj ############################################################################### # Generation of an open mesh K = [-1, -1] open_mesh = sps.generate_quadric(K, nstep=[5, 5]) open_mesh_boundary = stop.mesh_boundary(open_mesh) # Visualization visb_sc = splt.visbrain_plot(mesh=open_mesh, caption='open mesh') for bound in open_mesh_boundary: points = open_mesh.vertices[bound] s_rad = SourceObj('rad', points, color='red', symbol='square', radius_min=10) visb_sc.add_to_subplot(s_rad) lines = Line(pos=open_mesh.vertices[bound], width=10, color='b') # wrap the vispy object using visbrain l_obj = VispyObj('line', lines) visb_sc.add_to_subplot(l_obj) visb_sc.preview() ############################################################################### # Mapping onto a planar disk disk_mesh = smap.disk_conformal_mapping(open_mesh) # Visualization visb_sc2 = splt.visbrain_plot(mesh=disk_mesh, caption='disk mesh') for bound in open_mesh_boundary: points = disk_mesh.vertices[bound] s_rad = SourceObj('rad', points, color='red', symbol='square', radius_min=10) visb_sc2.add_to_subplot(s_rad) lines = Line(pos=disk_mesh.vertices[bound], width=10, color='b') # wrap the vispy object using visbrain l_obj = VispyObj('line', lines) visb_sc2.add_to_subplot(l_obj) visb_sc2.preview() ############################################################################### # Compute distortion measures between original and planar representations angle_diff = sdst.angle_difference(disk_mesh, open_mesh) area_diff = sdst.area_difference(disk_mesh, open_mesh) edge_diff = sdst.edge_length_difference(disk_mesh, open_mesh) print(np.mean(angle_diff)) print(np.mean(area_diff)) print(np.mean(edge_diff))
""" .. _example_mapping: =================================== Mapping example in slam =================================== """ # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD (3-clause) # sphinx_gallery_thumbnail_number = 2 ############################################################################### # Importation of slam modules import slam.generate_parametric_surfaces as sps import numpy as np import slam.topology as stop import slam.plot as splt import slam.mapping as smap import slam.distortion as sdst from vispy.scene import Line from visbrain.objects import VispyObj, SourceObj ############################################################################### # Generation of an open mesh K = [-1, -1] open_mesh = sps.generate_quadric(K, nstep=[5, 5]) open_mesh_boundary = stop.mesh_boundary(open_mesh) # Visualization visb_sc = splt.visbrain_plot(mesh=open_mesh, caption='open mesh') for bound in open_mesh_boundary: points = open_mesh.vertices[bound] s_rad = SourceObj('rad', points, color='red', symbol='square', radius_min=10) visb_sc.add_to_subplot(s_rad) lines = Line(pos=open_mesh.vertices[bound], width=10, color='b') # wrap the vispy object using visbrain l_obj = VispyObj('line', lines) visb_sc.add_to_subplot(l_obj) visb_sc.preview() ############################################################################### # Mapping onto a planar disk disk_mesh = smap.disk_conformal_mapping(open_mesh) # Visualization visb_sc2 = splt.visbrain_plot(mesh=disk_mesh, caption='disk mesh') for bound in open_mesh_boundary: points = disk_mesh.vertices[bound] s_rad = SourceObj('rad', points, color='red', symbol='square', radius_min=10) visb_sc2.add_to_subplot(s_rad) lines = Line(pos=disk_mesh.vertices[bound], width=10, color='b') # wrap the vispy object using visbrain l_obj = VispyObj('line', lines) visb_sc2.add_to_subplot(l_obj) visb_sc2.preview() ############################################################################### # Compute distortion measures between original and planar representations angle_diff = sdst.angle_difference(disk_mesh, open_mesh) area_diff = sdst.area_difference(disk_mesh, open_mesh) edge_diff = sdst.edge_length_difference(disk_mesh, open_mesh) print(np.mean(angle_diff)) print(np.mean(area_diff)) print(np.mean(edge_diff))
de
0.540745
.. _example_mapping: =================================== Mapping example in slam =================================== # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD (3-clause) # sphinx_gallery_thumbnail_number = 2 ############################################################################### # Importation of slam modules ############################################################################### # Generation of an open mesh # Visualization # wrap the vispy object using visbrain ############################################################################### # Mapping onto a planar disk # Visualization # wrap the vispy object using visbrain ############################################################################### # Compute distortion measures between original and planar representations
2.721205
3
reinforce/jax2.py
gebob19/rl_with_jax
5
6630542
## different implementation version of batch REINFORCE (still works and is 2x faster) #%% import jax import jax.numpy as np import numpy as onp import distrax import optax import gym from functools import partial from jax.config import config config.update("jax_enable_x64", True) config.update("jax_debug_nans", True) # break on nans #%% env_name = 'CartPole-v0' env = gym.make(env_name) n_actions = env.action_space.n obs_dim = env.observation_space.shape[0] print(f'[LOGGER] n_actions: {n_actions} obs_dim: {obs_dim}') #%% import haiku as hk init_final = hk.initializers.RandomUniform(-3e-3, 3e-3) def _policy_fcn(obs): a_probs = hk.Sequential([ hk.Linear(32), jax.nn.relu, hk.Linear(32), jax.nn.relu, hk.Linear(n_actions, w_init=init_final), jax.nn.softmax ])(obs) return a_probs policy_fcn = hk.transform(_policy_fcn) policy_fcn = hk.without_apply_rng(policy_fcn) p_frwd = jax.jit(policy_fcn.apply) @jax.jit def update_step(params, grads, opt_state): grads, opt_state = p_optim.update(grads, opt_state) params = optax.apply_updates(params, grads) return params, opt_state def reward2go(r, gamma=0.99): for i in range(len(r) - 1)[::-1]: r[i] = r[i] + gamma * r[i+1] r = (r - r.mean()) / (r.std() + 1e-8) return r @jax.jit def policy(p_params, obs, rng): a_probs = p_frwd(p_params, obs) dist = distrax.Categorical(probs=a_probs) a = dist.sample(seed=rng) entropy = dist.entropy() return a, entropy def rollout(p_params, rng): global step_count observ, action, rew = [], [], [] obs = env.reset() while True: rng, subkey = jax.random.split(rng, 2) a, entropy = policy(p_params, obs, subkey) a = a.item() writer.add_scalar('policy/entropy', entropy.item(), step_count) obs2, r, done, _ = env.step(a) step_count += 1 pbar.update(1) observ.append(obs) action.append(a) rew.append(r) if done: break obs = obs2 obs = np.stack(observ) a = np.stack(action) r = onp.stack(rew) # return obs, a, r def reinforce_loss(p_params, obs, a, r): a_probs = p_frwd(p_params, obs) log_prob = distrax.Categorical(probs=a_probs).log_prob(a.astype(int)) loss = -(log_prob * r).sum() return loss from functools import partial def batch_reinforce_loss(params, batch): return jax.vmap(partial(reinforce_loss, params))(*batch).sum() # %% seed = onp.random.randint(1e5) policy_lr = 1e-3 batch_size = 32 max_n_steps = 100000 rng = jax.random.PRNGKey(seed) onp.random.seed(seed) env.seed(seed) obs = env.reset() # dummy input p_params = policy_fcn.init(rng, obs) ## optimizers p_optim = optax.sgd(policy_lr) p_opt_state = p_optim.init(p_params) # %% from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter(comment=f'reinforce_{env_name}_seed={seed}') # %% from tqdm import tqdm step_count = 0 epi_i = 0 pbar = tqdm(total=max_n_steps) loss_grad_fcn = jax.jit(jax.value_and_grad(batch_reinforce_loss)) while step_count < max_n_steps: trajs = [] for _ in range(batch_size): rng, subkey = jax.random.split(rng, 2) obs, a, r = rollout(p_params, subkey) writer.add_scalar('rollout/reward', r.sum().item(), epi_i) r = reward2go(r) trajs.append((obs, a, r)) epi_i += 1 trajs = jax.tree_multimap(lambda *x: np.concatenate(x, 0), *trajs) loss, grads = loss_grad_fcn(p_params, trajs) p_params, p_opt_state = update_step(p_params, grads, p_opt_state) writer.add_scalar('loss/loss', loss.item(), step_count) step_count += 1 # %% # %% # %%
## different implementation version of batch REINFORCE (still works and is 2x faster) #%% import jax import jax.numpy as np import numpy as onp import distrax import optax import gym from functools import partial from jax.config import config config.update("jax_enable_x64", True) config.update("jax_debug_nans", True) # break on nans #%% env_name = 'CartPole-v0' env = gym.make(env_name) n_actions = env.action_space.n obs_dim = env.observation_space.shape[0] print(f'[LOGGER] n_actions: {n_actions} obs_dim: {obs_dim}') #%% import haiku as hk init_final = hk.initializers.RandomUniform(-3e-3, 3e-3) def _policy_fcn(obs): a_probs = hk.Sequential([ hk.Linear(32), jax.nn.relu, hk.Linear(32), jax.nn.relu, hk.Linear(n_actions, w_init=init_final), jax.nn.softmax ])(obs) return a_probs policy_fcn = hk.transform(_policy_fcn) policy_fcn = hk.without_apply_rng(policy_fcn) p_frwd = jax.jit(policy_fcn.apply) @jax.jit def update_step(params, grads, opt_state): grads, opt_state = p_optim.update(grads, opt_state) params = optax.apply_updates(params, grads) return params, opt_state def reward2go(r, gamma=0.99): for i in range(len(r) - 1)[::-1]: r[i] = r[i] + gamma * r[i+1] r = (r - r.mean()) / (r.std() + 1e-8) return r @jax.jit def policy(p_params, obs, rng): a_probs = p_frwd(p_params, obs) dist = distrax.Categorical(probs=a_probs) a = dist.sample(seed=rng) entropy = dist.entropy() return a, entropy def rollout(p_params, rng): global step_count observ, action, rew = [], [], [] obs = env.reset() while True: rng, subkey = jax.random.split(rng, 2) a, entropy = policy(p_params, obs, subkey) a = a.item() writer.add_scalar('policy/entropy', entropy.item(), step_count) obs2, r, done, _ = env.step(a) step_count += 1 pbar.update(1) observ.append(obs) action.append(a) rew.append(r) if done: break obs = obs2 obs = np.stack(observ) a = np.stack(action) r = onp.stack(rew) # return obs, a, r def reinforce_loss(p_params, obs, a, r): a_probs = p_frwd(p_params, obs) log_prob = distrax.Categorical(probs=a_probs).log_prob(a.astype(int)) loss = -(log_prob * r).sum() return loss from functools import partial def batch_reinforce_loss(params, batch): return jax.vmap(partial(reinforce_loss, params))(*batch).sum() # %% seed = onp.random.randint(1e5) policy_lr = 1e-3 batch_size = 32 max_n_steps = 100000 rng = jax.random.PRNGKey(seed) onp.random.seed(seed) env.seed(seed) obs = env.reset() # dummy input p_params = policy_fcn.init(rng, obs) ## optimizers p_optim = optax.sgd(policy_lr) p_opt_state = p_optim.init(p_params) # %% from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter(comment=f'reinforce_{env_name}_seed={seed}') # %% from tqdm import tqdm step_count = 0 epi_i = 0 pbar = tqdm(total=max_n_steps) loss_grad_fcn = jax.jit(jax.value_and_grad(batch_reinforce_loss)) while step_count < max_n_steps: trajs = [] for _ in range(batch_size): rng, subkey = jax.random.split(rng, 2) obs, a, r = rollout(p_params, subkey) writer.add_scalar('rollout/reward', r.sum().item(), epi_i) r = reward2go(r) trajs.append((obs, a, r)) epi_i += 1 trajs = jax.tree_multimap(lambda *x: np.concatenate(x, 0), *trajs) loss, grads = loss_grad_fcn(p_params, trajs) p_params, p_opt_state = update_step(p_params, grads, p_opt_state) writer.add_scalar('loss/loss', loss.item(), step_count) step_count += 1 # %% # %% # %%
en
0.448458
## different implementation version of batch REINFORCE (still works and is 2x faster) #%% # break on nans #%% #%% # # %% # dummy input ## optimizers # %% # %% # %% # %% # %%
1.871264
2
env/lib/python3.8/site-packages/faker/providers/internet/ru_RU/__init__.py
avdhari/enigma
258
6630543
<filename>env/lib/python3.8/site-packages/faker/providers/internet/ru_RU/__init__.py # coding=utf-8 from __future__ import unicode_literals from .. import Provider as InternetProvider class Provider(InternetProvider): user_name_formats = ( '{{last_name_female}}.{{first_name_female}}', '{{last_name_male}}.{{first_name_male}}', '{{last_name_male}}.{{first_name_male}}', '{{first_name_male}}.{{last_name_male}}', '{{first_name}}##', '{{first_name}}_##', '?{{last_name}}', '{{first_name}}{{year}}', '{{first_name}}_{{year}}', ) email_formats = ( '{{user_name}}@{{free_email_domain}}', '{{user_name}}@{{domain_name}}') free_email_domains = ( 'gmail.com', 'yahoo.com', 'hotmail.com', 'mail.ru', 'yandex.ru', 'rambler.ru') tlds = ('ru', 'com', 'biz', 'info', 'net', 'org', 'edu') replacements = ( ('А', 'a'), ('Б', 'b'), ('В', 'v'), ('Г', 'g'), ('Д', 'd'), ('Е', 'e'), ('Ё', 'e'), ('Ж', 'zh'), ('З', 'z'), ('И', 'i'), ('Й', ''), ('К', 'k'), ('Л', 'l'), ('М', 'm'), ('Н', 'n'), ('О', 'o'), ('П', 'p'), ('Р', 'r'), ('С', 's'), ('Т', 't'), ('У', 'u'), ('Ф', 'f'), ('Х', 'h'), ('Ц', 'ts'), ('Ч', 'ch'), ('Ш', 'sh'), ('Щ', 'shch'), ('Ъ', ''), ('Ы', 'i'), ('Ь', ''), ('Э', 'e'), ('Ю', 'yu'), ('Я', 'ya'), ('а', 'a'), ('б', 'b'), ('в', 'v'), ('г', 'g'), ('д', 'd'), ('е', 'e'), ('ё', 'e'), ('ж', 'zh'), ('з', 'z'), ('и', 'i'), ('й', ''), ('к', 'k'), ('л', 'l'), ('м', 'm'), ('н', 'n'), ('о', 'o'), ('п', 'p'), ('р', 'r'), ('с', 's'), ('т', 't'), ('у', 'u'), ('ф', 'f'), ('х', 'h'), ('ц', 'ts'), ('ч', 'ch'), ('ш', 'sh'), ('щ', 'shch'), ('ъ', ''), ('ы', 'i'), ('ь', ''), ('э', 'e'), ('ю', 'ju'), ('я', 'ja'), )
<filename>env/lib/python3.8/site-packages/faker/providers/internet/ru_RU/__init__.py # coding=utf-8 from __future__ import unicode_literals from .. import Provider as InternetProvider class Provider(InternetProvider): user_name_formats = ( '{{last_name_female}}.{{first_name_female}}', '{{last_name_male}}.{{first_name_male}}', '{{last_name_male}}.{{first_name_male}}', '{{first_name_male}}.{{last_name_male}}', '{{first_name}}##', '{{first_name}}_##', '?{{last_name}}', '{{first_name}}{{year}}', '{{first_name}}_{{year}}', ) email_formats = ( '{{user_name}}@{{free_email_domain}}', '{{user_name}}@{{domain_name}}') free_email_domains = ( 'gmail.com', 'yahoo.com', 'hotmail.com', 'mail.ru', 'yandex.ru', 'rambler.ru') tlds = ('ru', 'com', 'biz', 'info', 'net', 'org', 'edu') replacements = ( ('А', 'a'), ('Б', 'b'), ('В', 'v'), ('Г', 'g'), ('Д', 'd'), ('Е', 'e'), ('Ё', 'e'), ('Ж', 'zh'), ('З', 'z'), ('И', 'i'), ('Й', ''), ('К', 'k'), ('Л', 'l'), ('М', 'm'), ('Н', 'n'), ('О', 'o'), ('П', 'p'), ('Р', 'r'), ('С', 's'), ('Т', 't'), ('У', 'u'), ('Ф', 'f'), ('Х', 'h'), ('Ц', 'ts'), ('Ч', 'ch'), ('Ш', 'sh'), ('Щ', 'shch'), ('Ъ', ''), ('Ы', 'i'), ('Ь', ''), ('Э', 'e'), ('Ю', 'yu'), ('Я', 'ya'), ('а', 'a'), ('б', 'b'), ('в', 'v'), ('г', 'g'), ('д', 'd'), ('е', 'e'), ('ё', 'e'), ('ж', 'zh'), ('з', 'z'), ('и', 'i'), ('й', ''), ('к', 'k'), ('л', 'l'), ('м', 'm'), ('н', 'n'), ('о', 'o'), ('п', 'p'), ('р', 'r'), ('с', 's'), ('т', 't'), ('у', 'u'), ('ф', 'f'), ('х', 'h'), ('ц', 'ts'), ('ч', 'ch'), ('ш', 'sh'), ('щ', 'shch'), ('ъ', ''), ('ы', 'i'), ('ь', ''), ('э', 'e'), ('ю', 'ju'), ('я', 'ja'), )
zh
0.286321
# coding=utf-8 ##', ##',
1.990412
2
project/test/date_range_test.py
majvazov/martin-ayvazov-employees
0
6630544
import unittest import sys #step back one directory sys.path.append("..") #import all functions in functions.py from packages.functions import (date_range_overlap, find_longest_time_couple, find_all_ranges, read_file) class TestLongestPair(unittest.TestCase): ''' Automated test scripts for functions in functions.py ''' def test_date(self): ''' Unit testing date_range_overlap function used for detecting range in days between two date ranges ''' self.assertEqual(date_range_overlap('2012-03-28', '2016-06-02', '2013-04-02', '2018-10-29'), 1158) self.assertEqual(date_range_overlap('not a date', 'not a date', 'not a date', 'not a date') , 'Wrong date format!') #excepting integer values given as arguments self.assertEqual(date_range_overlap(21, 23, 34, 45) , 'Wrong date format!') def test_longest_couple(self): ''' To do ''' pass def test_file_reading(self): ''' To do ''' pass def test_all_ranges(self): ''' To do ''' pass if __name__ == '__main__': unittest.main()
import unittest import sys #step back one directory sys.path.append("..") #import all functions in functions.py from packages.functions import (date_range_overlap, find_longest_time_couple, find_all_ranges, read_file) class TestLongestPair(unittest.TestCase): ''' Automated test scripts for functions in functions.py ''' def test_date(self): ''' Unit testing date_range_overlap function used for detecting range in days between two date ranges ''' self.assertEqual(date_range_overlap('2012-03-28', '2016-06-02', '2013-04-02', '2018-10-29'), 1158) self.assertEqual(date_range_overlap('not a date', 'not a date', 'not a date', 'not a date') , 'Wrong date format!') #excepting integer values given as arguments self.assertEqual(date_range_overlap(21, 23, 34, 45) , 'Wrong date format!') def test_longest_couple(self): ''' To do ''' pass def test_file_reading(self): ''' To do ''' pass def test_all_ranges(self): ''' To do ''' pass if __name__ == '__main__': unittest.main()
en
0.665933
#step back one directory #import all functions in functions.py Automated test scripts for functions in functions.py Unit testing date_range_overlap function used for detecting range in days between two date ranges #excepting integer values given as arguments To do To do To do
3.218003
3
dxm/lib/DxTable/DxMetaList.py
arunbsar/dxm-toolkit
0
6630545
# # 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. # # Copyright (c) 2018 by Delphix. All rights reserved. # # Author : <NAME> # Date : April 2018 import logging import sys from dxm.lib.DxTable.DxTable import DxTable from dxm.lib.DxTable.DxFile import DxFile from dxm.lib.DxEngine.DxMaskingEngine import DxMaskingEngine from dxm.lib.DxTools.DxTools import get_objref_by_val_and_attribute from dxm.lib.DxTools.DxTools import paginator from dxm.lib.DxLogging import print_error class DxMetaList(object): __tableList = {} __engine = None __logger = None @classmethod def __init__(self): """ Constructor :param engine: DxMaskingEngine object """ self.__engine = DxMaskingEngine self.__logger = logging.getLogger() self.__logger.debug("creating DxTableList object") @classmethod def LoadMeta(self, ruleset_id=None): """ Load list of rule sets Return None if OK """ notable = None nofile = None if (self.__engine.version_ge('6.0.0')): from masking_api_60.api.table_metadata_api import TableMetadataApi from masking_api_60.api.file_metadata_api import FileMetadataApi from masking_api_60.rest import ApiException else: from masking_api_53.api.table_metadata_api import TableMetadataApi from masking_api_53.api.file_metadata_api import FileMetadataApi from masking_api_53.rest import ApiException self.__api = TableMetadataApi self.__fileapi = FileMetadataApi self.__apiexc = ApiException self.__tableList.clear() try: api_instance = self.__api(self.__engine.api_client) if ruleset_id: table_metadata = paginator( api_instance, "get_all_table_metadata", ruleset_id=ruleset_id) else: table_metadata = paginator( api_instance, "get_all_table_metadata") if table_metadata.response_list: for c in table_metadata.response_list: table = DxTable(self.__engine) table.from_table(c) self.__tableList[c.table_metadata_id] = table else: self.__logger.error("No table metadata found") except self.__apiexc as e: if (e.status == 404) and (ruleset_id is not None): notable = 1 else: print_error(e.body) self.__logger.error(e.body) return 1 try: api_instance = self.__fileapi(self.__engine.api_client) if ruleset_id: file_metadata = paginator( api_instance, "get_all_file_metadata", ruleset_id=ruleset_id) else: file_metadata = paginator( api_instance, "get_all_file_metadata") if file_metadata.response_list: for c in file_metadata.response_list: file = DxFile(self.__engine) file.from_file(c) self.__tableList[c.file_metadata_id] = file else: self.__logger.error("No file metadata found") except self.__apiexc as e: if (e.status == 404) and (ruleset_id is not None): nofile = 1 else: print_error(e.body) self.__logger.error(e.body) return 1 if nofile and notable: print_error("Ruleset not found") return 1 else: return None @classmethod def get_by_ref(self, reference): """ return a Table object by refrerence """ try: self.__logger.debug("reference %s" % reference) return self.__tableList[reference] except KeyError as e: self.__logger.debug("can't find Table object" " for reference %s" % reference) self.__logger.debug(e) sys.exit(1) @classmethod def get_allref(self): """ return a list of all references """ return self.__tableList.keys() @classmethod def get_MetadataId_by_name(self, name, skip_out=None): """ Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return ref if OK return None if ruleset not found or not unique """ reflist = self.get_MetadataId_by_name_worker(name, skip_out, 1) # convert list to single value # as there will be only one element in list if reflist: return reflist[0] else: return None @classmethod def get_all_MetadataId_by_name(self, name, skip_out=None): """ Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return list of references if OK return None if ruleset not found """ return self.get_MetadataId_by_name_worker(name, skip_out, None) @classmethod def get_MetadataId_by_name_worker(self, name, skip_out=None, check_uniqueness=1): metalist = get_objref_by_val_and_attribute(name, self, 'meta_name') if len(metalist) == 0: self.__logger.error('Table or file %s not found' % name) if not skip_out: print_error('Table or file %s not found' % name) return None if check_uniqueness: if len(metalist) > 1: self.__logger.error('Table or file %s is not unique' % name) if not skip_out: print_error('Table or file %s is not unique' % name) return None return metalist @classmethod def add(self, metaobj): """ Add an Table/File to a list and Engine :param metaobj: Table/File object to add to Engine and list return None if OK """ if (metaobj.add() == 0): self.__logger.debug("Adding table/file %s to list" % metaobj) self.__tableList[metaobj.meta_id] = metaobj return None else: return 1 @classmethod def delete(self, tableMetadataId): """ Delete a ruleset from a list and Engine :param databaseRulesetId: Ruleset id to delete from Engine and list return None if OK """ table = self.get_by_ref(tableMetadataId) if table is not None: if table.delete() == 0: return None else: return 1 else: print_error("Table or File with id %s not found" % tableMetadataId) return 1 @classmethod def copymeta(self, meta_id, newruleset_id): """ Copy meta data from current RS to new Ruleset :param1 meta_id: Metadata id to copy :param2 newruleset_id: new RS to copy meta to return None if OK """ metaobj = self.get_by_ref(meta_id) if type(metaobj) == DxTable: newmeta = DxTable(self.__engine) newmeta.from_table(metaobj) newmeta.ruleset_id = newruleset_id if self.add(newmeta) is None: return newmeta.table_metadata_id else: return None else: newmeta = DxFile(self.__engine) newmeta.from_file(metaobj) newmeta.ruleset_id = newruleset_id if self.add(newmeta) is None: return newmeta.file_metadata_id else: return None
# # 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. # # Copyright (c) 2018 by Delphix. All rights reserved. # # Author : <NAME> # Date : April 2018 import logging import sys from dxm.lib.DxTable.DxTable import DxTable from dxm.lib.DxTable.DxFile import DxFile from dxm.lib.DxEngine.DxMaskingEngine import DxMaskingEngine from dxm.lib.DxTools.DxTools import get_objref_by_val_and_attribute from dxm.lib.DxTools.DxTools import paginator from dxm.lib.DxLogging import print_error class DxMetaList(object): __tableList = {} __engine = None __logger = None @classmethod def __init__(self): """ Constructor :param engine: DxMaskingEngine object """ self.__engine = DxMaskingEngine self.__logger = logging.getLogger() self.__logger.debug("creating DxTableList object") @classmethod def LoadMeta(self, ruleset_id=None): """ Load list of rule sets Return None if OK """ notable = None nofile = None if (self.__engine.version_ge('6.0.0')): from masking_api_60.api.table_metadata_api import TableMetadataApi from masking_api_60.api.file_metadata_api import FileMetadataApi from masking_api_60.rest import ApiException else: from masking_api_53.api.table_metadata_api import TableMetadataApi from masking_api_53.api.file_metadata_api import FileMetadataApi from masking_api_53.rest import ApiException self.__api = TableMetadataApi self.__fileapi = FileMetadataApi self.__apiexc = ApiException self.__tableList.clear() try: api_instance = self.__api(self.__engine.api_client) if ruleset_id: table_metadata = paginator( api_instance, "get_all_table_metadata", ruleset_id=ruleset_id) else: table_metadata = paginator( api_instance, "get_all_table_metadata") if table_metadata.response_list: for c in table_metadata.response_list: table = DxTable(self.__engine) table.from_table(c) self.__tableList[c.table_metadata_id] = table else: self.__logger.error("No table metadata found") except self.__apiexc as e: if (e.status == 404) and (ruleset_id is not None): notable = 1 else: print_error(e.body) self.__logger.error(e.body) return 1 try: api_instance = self.__fileapi(self.__engine.api_client) if ruleset_id: file_metadata = paginator( api_instance, "get_all_file_metadata", ruleset_id=ruleset_id) else: file_metadata = paginator( api_instance, "get_all_file_metadata") if file_metadata.response_list: for c in file_metadata.response_list: file = DxFile(self.__engine) file.from_file(c) self.__tableList[c.file_metadata_id] = file else: self.__logger.error("No file metadata found") except self.__apiexc as e: if (e.status == 404) and (ruleset_id is not None): nofile = 1 else: print_error(e.body) self.__logger.error(e.body) return 1 if nofile and notable: print_error("Ruleset not found") return 1 else: return None @classmethod def get_by_ref(self, reference): """ return a Table object by refrerence """ try: self.__logger.debug("reference %s" % reference) return self.__tableList[reference] except KeyError as e: self.__logger.debug("can't find Table object" " for reference %s" % reference) self.__logger.debug(e) sys.exit(1) @classmethod def get_allref(self): """ return a list of all references """ return self.__tableList.keys() @classmethod def get_MetadataId_by_name(self, name, skip_out=None): """ Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return ref if OK return None if ruleset not found or not unique """ reflist = self.get_MetadataId_by_name_worker(name, skip_out, 1) # convert list to single value # as there will be only one element in list if reflist: return reflist[0] else: return None @classmethod def get_all_MetadataId_by_name(self, name, skip_out=None): """ Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return list of references if OK return None if ruleset not found """ return self.get_MetadataId_by_name_worker(name, skip_out, None) @classmethod def get_MetadataId_by_name_worker(self, name, skip_out=None, check_uniqueness=1): metalist = get_objref_by_val_and_attribute(name, self, 'meta_name') if len(metalist) == 0: self.__logger.error('Table or file %s not found' % name) if not skip_out: print_error('Table or file %s not found' % name) return None if check_uniqueness: if len(metalist) > 1: self.__logger.error('Table or file %s is not unique' % name) if not skip_out: print_error('Table or file %s is not unique' % name) return None return metalist @classmethod def add(self, metaobj): """ Add an Table/File to a list and Engine :param metaobj: Table/File object to add to Engine and list return None if OK """ if (metaobj.add() == 0): self.__logger.debug("Adding table/file %s to list" % metaobj) self.__tableList[metaobj.meta_id] = metaobj return None else: return 1 @classmethod def delete(self, tableMetadataId): """ Delete a ruleset from a list and Engine :param databaseRulesetId: Ruleset id to delete from Engine and list return None if OK """ table = self.get_by_ref(tableMetadataId) if table is not None: if table.delete() == 0: return None else: return 1 else: print_error("Table or File with id %s not found" % tableMetadataId) return 1 @classmethod def copymeta(self, meta_id, newruleset_id): """ Copy meta data from current RS to new Ruleset :param1 meta_id: Metadata id to copy :param2 newruleset_id: new RS to copy meta to return None if OK """ metaobj = self.get_by_ref(meta_id) if type(metaobj) == DxTable: newmeta = DxTable(self.__engine) newmeta.from_table(metaobj) newmeta.ruleset_id = newruleset_id if self.add(newmeta) is None: return newmeta.table_metadata_id else: return None else: newmeta = DxFile(self.__engine) newmeta.from_file(metaobj) newmeta.ruleset_id = newruleset_id if self.add(newmeta) is None: return newmeta.file_metadata_id else: return None
en
0.750646
# # 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. # # Copyright (c) 2018 by Delphix. All rights reserved. # # Author : <NAME> # Date : April 2018 Constructor :param engine: DxMaskingEngine object Load list of rule sets Return None if OK return a Table object by refrerence return a list of all references Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return ref if OK return None if ruleset not found or not unique # convert list to single value # as there will be only one element in list Return metadata id by name. :param1 name: name of environment :param2 skip_out: disable message printing return list of references if OK return None if ruleset not found Add an Table/File to a list and Engine :param metaobj: Table/File object to add to Engine and list return None if OK Delete a ruleset from a list and Engine :param databaseRulesetId: Ruleset id to delete from Engine and list return None if OK Copy meta data from current RS to new Ruleset :param1 meta_id: Metadata id to copy :param2 newruleset_id: new RS to copy meta to return None if OK
1.835967
2
tests/unit/resources/test_factory.py
nglange/ibm-cos-sdk-python
33
6630546
<reponame>nglange/ibm-cos-sdk-python # Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' file accompanying this file. This file is # distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from ibm_botocore.model import DenormalizedStructureBuilder, ServiceModel from tests import BaseTestCase, mock from ibm_boto3.exceptions import ResourceLoadException from ibm_boto3.utils import ServiceContext from ibm_boto3.resources.base import ServiceResource from ibm_boto3.resources.collection import CollectionManager from ibm_boto3.resources.factory import ResourceFactory from ibm_boto3.resources.action import WaiterAction class BaseTestResourceFactory(BaseTestCase): def setUp(self): super(BaseTestResourceFactory, self).setUp() self.emitter = mock.Mock() self.factory = ResourceFactory(self.emitter) def load(self, resource_name, resource_json_definition=None, resource_json_definitions=None, service_model=None): if resource_json_definition is None: resource_json_definition = {} if resource_json_definitions is None: resource_json_definitions = {} service_context=ServiceContext( service_name='test', resource_json_definitions=resource_json_definitions, service_model=service_model, service_waiter_model=None ) return self.factory.load_from_definition( resource_name=resource_name, single_resource_json_definition=resource_json_definition, service_context=service_context ) class TestResourceFactory(BaseTestResourceFactory): def test_get_service_returns_resource_class(self): TestResource = self.load('test') self.assertIn(ServiceResource, TestResource.__bases__, 'Did not return a ServiceResource subclass for service') def test_get_resource_returns_resource_class(self): QueueResource = self.load('Queue') self.assertIn(ServiceResource, QueueResource.__bases__, 'Did not return a ServiceResource subclass for resource') def test_factory_sets_service_name(self): QueueResource = self.load('Queue') self.assertEqual(QueueResource.meta.service_name, 'test', 'Service name not set') def test_factory_sets_identifiers(self): model = { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'}, ], } MessageResource = self.load('Message', model) self.assertIn('queue_url', MessageResource.meta.identifiers, 'Missing queue_url identifier from model') self.assertIn('receipt_handle', MessageResource.meta.identifiers, 'Missing receipt_handle identifier from model') def test_identifiers_in_repr(self): model = { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'}, ], } defs = { 'Message': model } resource = self.load('Message', model, defs)('url', 'handle') # Class name self.assertIn('test.Message', repr(resource)) # Identifier names and values self.assertIn('queue_url', repr(resource)) self.assertIn("'url'", repr(resource)) self.assertIn('receipt_handle', repr(resource)) self.assertIn("'handle'", repr(resource)) def test_factory_creates_dangling_resources(self): model = { 'has': { 'Queue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } }, 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'input'}, {'target': 'Handle', 'source': 'input'} ] } } } } defs = { 'Queue': {}, 'Message': {} } TestResource = self.load('test', model, defs) self.assertTrue(hasattr(TestResource, 'Queue'), 'Missing Queue class from model') self.assertTrue(hasattr(TestResource, 'Message'), 'Missing Message class from model') def test_factory_creates_properties(self): model = { 'shape': 'TestShape', 'load': { 'request': { 'operation': 'DescribeTest', } } } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', }, 'LastModified': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape TestResource = self.load('test', model, service_model=service_model) self.assertTrue(hasattr(TestResource, 'e_tag'), 'ETag shape member not available on resource') self.assertTrue(hasattr(TestResource, 'last_modified'), 'LastModified shape member not available on resource') def test_factory_renames_on_clobber_identifier(self): model = { 'identifiers': [ {'name': 'Meta'} ] } # Each resource has a ``meta`` defined, so this identifier # must be renamed. cls = self.load('test', model) self.assertTrue(hasattr(cls, 'meta_identifier')) def test_factory_fails_on_clobber_action(self): model = { 'identifiers': [ {'name': 'Test'}, {'name': 'TestAction'} ], 'actions': { 'Test': { 'request': { 'operation': 'GetTest' } } } } # This fails because the resource has an identifier # that would be clobbered by the action name. with self.assertRaises(ValueError) as cm: self.load('test', model) self.assertIn('test', str(cm.exception)) self.assertIn('action', str(cm.exception)) def test_can_instantiate_service_resource(self): TestResource = self.load('test') resource = TestResource() self.assertIsInstance(resource, ServiceResource, 'Object is not an instance of ServiceResource') def test_non_service_resource_missing_defs(self): # Only services should get dangling defs defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } model = defs['Queue'] queue = self.load('Queue', model, defs)('url') self.assertTrue(not hasattr(queue, 'Queue')) self.assertTrue(not hasattr(queue, 'Message')) def test_subresource_requires_only_identifier(self): defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ], 'has': { 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'identifier', 'name': 'Url'}, {'target': 'ReceiptHandle', 'source': 'input'} ] } } } }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } model = defs['Queue'] queue = self.load('Queue', model, defs)('url') # Let's create a message and only give it a receipt handle # The required queue_url identifier should be set from the # queue itself. message = queue.Message('receipt') self.assertEqual(message.queue_url, 'url', 'Wrong queue URL set on the message resource instance') self.assertEqual(message.receipt_handle, 'receipt', 'Wrong receipt handle set on the message resource instance') def test_resource_meta_unique(self): queue_cls = self.load('Queue') queue1 = queue_cls() queue2 = queue_cls() self.assertEqual(queue1.meta, queue2.meta, 'Queue meta copies not equal after creation') queue1.meta.data = {'id': 'foo'} queue2.meta.data = {'id': 'bar'} self.assertNotEqual(queue_cls.meta, queue1.meta, 'Modified queue instance data should not modify the class data') self.assertNotEqual(queue1.meta, queue2.meta, 'Queue data should be unique to queue instance') self.assertNotEqual(queue1.meta, 'bad-value') def test_resource_meta_repr(self): queue_cls = self.load('Queue') queue = queue_cls() self.assertEqual(repr(queue.meta), 'ResourceMeta(\'test\', identifiers=[])') @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_calls_action(self, action_cls): model = { 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } action = action_cls.return_value queue = self.load('Queue', model)() queue.get_message_status('arg1', arg2=2) action.assert_called_with(queue, 'arg1', arg2=2) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_action_clears_data(self, action_cls): model = { 'load': { 'request': { 'operation': 'DescribeQueue' } }, 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } queue = self.load('Queue', model)() # Simulate loaded data queue.meta.data = {'some': 'data'} # Perform a call queue.get_message_status() # Cached data should be cleared self.assertIsNone(queue.meta.data) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_action_leaves_data(self, action_cls): # This model has NO load method. Cached data should # never be cleared since it cannot be reloaded! model = { 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } queue = self.load('Queue', model)() # Simulate loaded data queue.meta.data = {'some': 'data'} # Perform a call queue.get_message_status() # Cached data should not be cleared self.assertEqual(queue.meta.data, {'some': 'data'}) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_lazy_loads_properties(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'Url'} ], 'load': { 'request': { 'operation': 'DescribeTest', } } } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', 'shape_name': 'ETag' }, 'LastModified': { 'type': 'string', 'shape_name': 'LastModified' }, 'Url': { 'type': 'string', 'shape_name': 'Url' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape action = action_cls.return_value action.return_value = {'ETag': 'tag', 'LastModified': 'never'} resource = self.load( 'test', model, service_model=service_model)('url') # Accessing an identifier should not call load, even if it's in # the shape members. resource.url action.assert_not_called() # Accessing a property should call load self.assertEqual(resource.e_tag, 'tag', 'ETag property returned wrong value') self.assertEqual(action.call_count, 1) # Both params should have been loaded into the data bag self.assertIn('ETag', resource.meta.data) self.assertIn('LastModified', resource.meta.data) # Accessing another property should use cached value # instead of making a second call. self.assertEqual(resource.last_modified, 'never', 'LastModified property returned wrong value') self.assertEqual(action.call_count, 1) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_lazy_properties_missing_load(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'Url'} ] # Note the lack of a `load` method. These resources # are usually loaded via a call on a parent resource. } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', }, 'LastModified': { 'type': 'string' }, 'Url': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape action = action_cls.return_value action.return_value = {'ETag': 'tag', 'LastModified': 'never'} resource = self.load( 'test', model, service_model=service_model)('url') with self.assertRaises(ResourceLoadException): resource.last_modified @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_aliases_identifiers(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'id', 'memberName': 'foo_id'} ] } shape = DenormalizedStructureBuilder().with_members({ 'foo_id': { 'type': 'string', }, 'bar': { 'type': 'string' }, }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape shape_id = 'baz' resource = self.load( 'test', model, service_model=service_model)(shape_id) try: self.assertEqual(resource.id, shape_id) self.assertEqual(resource.foo_id, shape_id) except ResourceLoadException: self.fail("Load attempted on identifier alias.") def test_resource_loads_references(self): model = { 'shape': 'InstanceShape', 'identifiers': [{'name': 'GroupId'}], 'has': { 'Subnet': { 'resource': { 'type': 'Subnet', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'SubnetId'} ] } }, 'Vpcs': { 'resource': { 'type': 'Vpc', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'Vpcs[].Id'} ] } } } } defs = { 'Subnet': { 'identifiers': [{'name': 'Id'}] }, 'Vpc': { 'identifiers': [{'name': 'Id'}] } } service_model = ServiceModel({ 'shapes': { 'InstanceShape': { 'type': 'structure', 'members': { 'SubnetId': { 'shape': 'String' } } }, 'String': { 'type': 'string' } } }) resource = self.load('Instance', model, defs, service_model)('group-id') # Load the resource with no data resource.meta.data = {} self.assertTrue( hasattr(resource, 'subnet'), 'Resource should have a subnet reference') self.assertIsNone( resource.subnet, 'Missing identifier, should return None') self.assertIsNone(resource.vpcs) # Load the resource with data to instantiate a reference resource.meta.data = { 'SubnetId': 'abc123', 'Vpcs': [ {'Id': 'vpc1'}, {'Id': 'vpc2'} ] } self.assertIsInstance(resource.subnet, ServiceResource) self.assertEqual(resource.subnet.id, 'abc123') vpcs = resource.vpcs self.assertIsInstance(vpcs, list) self.assertEqual(len(vpcs), 2) self.assertEqual(vpcs[0].id, 'vpc1') self.assertEqual(vpcs[1].id, 'vpc2') @mock.patch('ibm_boto3.resources.model.Collection') def test_resource_loads_collections(self, mock_model): model = { 'hasMany': { u'Queues': { 'request': { 'operation': 'ListQueues' }, 'resource': { 'type': 'Queue' } } } } defs = { 'Queue': {} } service_model = ServiceModel({}) mock_model.return_value.name = 'queues' resource = self.load('test', model, defs, service_model)() self.assertTrue(hasattr(resource, 'queues'), 'Resource should expose queues collection') self.assertIsInstance(resource.queues, CollectionManager, 'Queues collection should be a collection manager') def test_resource_loads_waiters(self): model = { "waiters": { "Exists": { "waiterName": "BucketExists", "params": [ {"target": "Bucket", "source": "identifier", "name": "Name"}] } } } defs = { 'Bucket': {} } service_model = ServiceModel({}) resource = self.load('test', model, defs, service_model)() self.assertTrue(hasattr(resource, 'wait_until_exists'), 'Resource should expose resource waiter: wait_until_exists') @mock.patch('ibm_boto3.resources.factory.WaiterAction') def test_resource_waiter_calls_waiter_method(self, waiter_action_cls): model = { "waiters": { "Exists": { "waiterName": "BucketExists", "params": [ {"target": "Bucket", "source": "identifier", "name": "Name"}] } } } defs = { 'Bucket': {} } service_model = ServiceModel({}) waiter_action = waiter_action_cls.return_value resource = self.load('test', model, defs, service_model)() resource.wait_until_exists('arg1', arg2=2) waiter_action.assert_called_with(resource, 'arg1', arg2=2) class TestResourceFactoryDanglingResource(BaseTestResourceFactory): def setUp(self): super(TestResourceFactoryDanglingResource, self).setUp() self.model = { 'has': { 'Queue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } } } } self.defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] } } def test_dangling_resources_create_resource_instance(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue('test') self.assertIsInstance(q, ServiceResource, 'Dangling resource instance not a ServiceResource') def test_hash_resource_equal(self): resource = self.load('test', self.model, self.defs)() p = resource.Queue('test') q = resource.Queue('test') self.assertEqual(p, q, "Should be equal resource") self.assertEqual(hash(p), hash(q), "Hash values should be equal") def test_hash_resource_not_equal(self): resource = self.load('test', self.model, self.defs)() p = resource.Queue('test1') q = resource.Queue('test2') self.assertNotEquals(p, q, "Should not be equal resource") self.assertNotEquals(hash(p), hash(q), "Hash values should be different") def test_dangling_resource_create_with_kwarg(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue(url='test') self.assertIsInstance(q, ServiceResource, 'Dangling resource created with kwargs is not a ServiceResource') def test_dangling_resource_shares_client(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue('test') self.assertEqual(resource.meta.client, q.meta.client, 'Client was not shared to dangling resource instance') def test_dangling_resource_requires_identifier(self): resource = self.load('test', self.model, self.defs)() with self.assertRaises(ValueError): resource.Queue() def test_dangling_resource_raises_for_unknown_arg(self): resource = self.load('test', self.model, self.defs)() with self.assertRaises(ValueError): resource.Queue(url='foo', bar='baz') def test_dangling_resource_identifier_is_immutable(self): resource = self.load('test', self.model, self.defs)() queue = resource.Queue('url') # We should not be able to change the identifier's value with self.assertRaises(AttributeError): queue.url = 'foo' def test_dangling_resource_equality(self): resource = self.load('test', self.model, self.defs)() q1 = resource.Queue('url') q2 = resource.Queue('url') self.assertEqual(q1, q2) def test_dangling_resource_inequality(self): self.defs = { 'Queue': { 'identifiers': [{'name': 'Url'}], 'has': { 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'identifier', 'name': 'Url'}, {'target': 'Handle', 'source': 'input'} ] } } } }, 'Message': { 'identifiers': [{'name': 'QueueUrl'}, {'name': 'Handle'}] } } resource = self.load('test', self.model, self.defs)() q1 = resource.Queue('url') q2 = resource.Queue('different') m = q1.Message('handle') self.assertNotEqual(q1, q2) self.assertNotEqual(q1, m) def test_dangling_resource_loads_data(self): # Given a loadable resource instance that contains a reference # to another resource which has a resource data path, the # referenced resource should be loaded with all of the data # contained at that path. This allows loading references # which would otherwise not be loadable (missing load method) # and prevents extra load calls for others when we already # have the data available. self.defs = { 'Instance': { 'identifiers': [{'name': 'Id'}], 'has': { 'NetworkInterface': { 'resource': { 'type': 'NetworkInterface', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'NetworkInterface.Id'} ], 'path': 'NetworkInterface' } } } }, 'NetworkInterface': { 'identifiers': [{'name': 'Id'}], 'shape': 'NetworkInterfaceShape' } } self.model = self.defs['Instance'] shape = DenormalizedStructureBuilder().with_members({ 'Id': { 'type': 'string', }, 'PublicIp': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape cls = self.load('Instance', self.model, self.defs, service_model) instance = cls('instance-id') # Set some data as if we had completed a load action. def set_meta_data(): instance.meta.data = { 'NetworkInterface': { 'Id': 'network-interface-id', 'PublicIp': '127.0.0.1' } } instance.load = mock.Mock(side_effect=set_meta_data) # Now, get the reference and make sure it has its data # set as expected. interface = instance.network_interface self.assertIsNotNone(interface.meta.data) self.assertEqual(interface.public_ip, '127.0.0.1') class TestServiceResourceSubresources(BaseTestResourceFactory): def setUp(self): super(TestServiceResourceSubresources, self).setUp() self.model = { 'has': { 'QueueObject': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } }, 'PriorityQueue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } } } } self.defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } def test_subresource_custom_name(self): resource = self.load('test', self.model, self.defs)() self.assertTrue(hasattr(resource, 'QueueObject')) def test_contains_all_subresources(self): resource = self.load('test', self.model, self.defs)() self.assertIn('QueueObject', dir(resource)) self.assertIn('PriorityQueue', dir(resource)) self.assertIn('Message', dir(resource)) def test_get_available_subresources(self): resource = self.load('test', self.model, self.defs)() self.assertTrue(hasattr(resource, 'get_available_subresources')) subresources = sorted(resource.get_available_subresources()) expected = sorted(['PriorityQueue', 'Message', 'QueueObject']) self.assertEqual(subresources, expected) def test_subresource_missing_all_subresources(self): resource = self.load('test', self.model, self.defs)() message = resource.Message('url', 'handle') self.assertNotIn('QueueObject', dir(message)) self.assertNotIn('PriorityQueue', dir(message)) self.assertNotIn('Queue', dir(message)) self.assertNotIn('Message', dir(message)) def test_event_emitted_when_class_created(self): self.load('test', self.model, self.defs) self.assertTrue(self.emitter.emit.called) call_args = self.emitter.emit.call_args # Verify the correct event name emitted. self.assertEqual(call_args[0][0], 'creating-resource-class.test.ServiceResource') # Verify we send out the class attributes dict. actual_class_attrs = sorted(call_args[1]['class_attributes']) self.assertEqual(actual_class_attrs, [ 'Message', 'PriorityQueue', 'QueueObject', 'get_available_subresources', 'meta']) base_classes = sorted(call_args[1]['base_classes']) self.assertEqual(base_classes, [ServiceResource])
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' file accompanying this file. This file is # distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from ibm_botocore.model import DenormalizedStructureBuilder, ServiceModel from tests import BaseTestCase, mock from ibm_boto3.exceptions import ResourceLoadException from ibm_boto3.utils import ServiceContext from ibm_boto3.resources.base import ServiceResource from ibm_boto3.resources.collection import CollectionManager from ibm_boto3.resources.factory import ResourceFactory from ibm_boto3.resources.action import WaiterAction class BaseTestResourceFactory(BaseTestCase): def setUp(self): super(BaseTestResourceFactory, self).setUp() self.emitter = mock.Mock() self.factory = ResourceFactory(self.emitter) def load(self, resource_name, resource_json_definition=None, resource_json_definitions=None, service_model=None): if resource_json_definition is None: resource_json_definition = {} if resource_json_definitions is None: resource_json_definitions = {} service_context=ServiceContext( service_name='test', resource_json_definitions=resource_json_definitions, service_model=service_model, service_waiter_model=None ) return self.factory.load_from_definition( resource_name=resource_name, single_resource_json_definition=resource_json_definition, service_context=service_context ) class TestResourceFactory(BaseTestResourceFactory): def test_get_service_returns_resource_class(self): TestResource = self.load('test') self.assertIn(ServiceResource, TestResource.__bases__, 'Did not return a ServiceResource subclass for service') def test_get_resource_returns_resource_class(self): QueueResource = self.load('Queue') self.assertIn(ServiceResource, QueueResource.__bases__, 'Did not return a ServiceResource subclass for resource') def test_factory_sets_service_name(self): QueueResource = self.load('Queue') self.assertEqual(QueueResource.meta.service_name, 'test', 'Service name not set') def test_factory_sets_identifiers(self): model = { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'}, ], } MessageResource = self.load('Message', model) self.assertIn('queue_url', MessageResource.meta.identifiers, 'Missing queue_url identifier from model') self.assertIn('receipt_handle', MessageResource.meta.identifiers, 'Missing receipt_handle identifier from model') def test_identifiers_in_repr(self): model = { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'}, ], } defs = { 'Message': model } resource = self.load('Message', model, defs)('url', 'handle') # Class name self.assertIn('test.Message', repr(resource)) # Identifier names and values self.assertIn('queue_url', repr(resource)) self.assertIn("'url'", repr(resource)) self.assertIn('receipt_handle', repr(resource)) self.assertIn("'handle'", repr(resource)) def test_factory_creates_dangling_resources(self): model = { 'has': { 'Queue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } }, 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'input'}, {'target': 'Handle', 'source': 'input'} ] } } } } defs = { 'Queue': {}, 'Message': {} } TestResource = self.load('test', model, defs) self.assertTrue(hasattr(TestResource, 'Queue'), 'Missing Queue class from model') self.assertTrue(hasattr(TestResource, 'Message'), 'Missing Message class from model') def test_factory_creates_properties(self): model = { 'shape': 'TestShape', 'load': { 'request': { 'operation': 'DescribeTest', } } } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', }, 'LastModified': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape TestResource = self.load('test', model, service_model=service_model) self.assertTrue(hasattr(TestResource, 'e_tag'), 'ETag shape member not available on resource') self.assertTrue(hasattr(TestResource, 'last_modified'), 'LastModified shape member not available on resource') def test_factory_renames_on_clobber_identifier(self): model = { 'identifiers': [ {'name': 'Meta'} ] } # Each resource has a ``meta`` defined, so this identifier # must be renamed. cls = self.load('test', model) self.assertTrue(hasattr(cls, 'meta_identifier')) def test_factory_fails_on_clobber_action(self): model = { 'identifiers': [ {'name': 'Test'}, {'name': 'TestAction'} ], 'actions': { 'Test': { 'request': { 'operation': 'GetTest' } } } } # This fails because the resource has an identifier # that would be clobbered by the action name. with self.assertRaises(ValueError) as cm: self.load('test', model) self.assertIn('test', str(cm.exception)) self.assertIn('action', str(cm.exception)) def test_can_instantiate_service_resource(self): TestResource = self.load('test') resource = TestResource() self.assertIsInstance(resource, ServiceResource, 'Object is not an instance of ServiceResource') def test_non_service_resource_missing_defs(self): # Only services should get dangling defs defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } model = defs['Queue'] queue = self.load('Queue', model, defs)('url') self.assertTrue(not hasattr(queue, 'Queue')) self.assertTrue(not hasattr(queue, 'Message')) def test_subresource_requires_only_identifier(self): defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ], 'has': { 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'identifier', 'name': 'Url'}, {'target': 'ReceiptHandle', 'source': 'input'} ] } } } }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } model = defs['Queue'] queue = self.load('Queue', model, defs)('url') # Let's create a message and only give it a receipt handle # The required queue_url identifier should be set from the # queue itself. message = queue.Message('receipt') self.assertEqual(message.queue_url, 'url', 'Wrong queue URL set on the message resource instance') self.assertEqual(message.receipt_handle, 'receipt', 'Wrong receipt handle set on the message resource instance') def test_resource_meta_unique(self): queue_cls = self.load('Queue') queue1 = queue_cls() queue2 = queue_cls() self.assertEqual(queue1.meta, queue2.meta, 'Queue meta copies not equal after creation') queue1.meta.data = {'id': 'foo'} queue2.meta.data = {'id': 'bar'} self.assertNotEqual(queue_cls.meta, queue1.meta, 'Modified queue instance data should not modify the class data') self.assertNotEqual(queue1.meta, queue2.meta, 'Queue data should be unique to queue instance') self.assertNotEqual(queue1.meta, 'bad-value') def test_resource_meta_repr(self): queue_cls = self.load('Queue') queue = queue_cls() self.assertEqual(repr(queue.meta), 'ResourceMeta(\'test\', identifiers=[])') @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_calls_action(self, action_cls): model = { 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } action = action_cls.return_value queue = self.load('Queue', model)() queue.get_message_status('arg1', arg2=2) action.assert_called_with(queue, 'arg1', arg2=2) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_action_clears_data(self, action_cls): model = { 'load': { 'request': { 'operation': 'DescribeQueue' } }, 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } queue = self.load('Queue', model)() # Simulate loaded data queue.meta.data = {'some': 'data'} # Perform a call queue.get_message_status() # Cached data should be cleared self.assertIsNone(queue.meta.data) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_action_leaves_data(self, action_cls): # This model has NO load method. Cached data should # never be cleared since it cannot be reloaded! model = { 'actions': { 'GetMessageStatus': { 'request': { 'operation': 'DescribeMessageStatus' } } } } queue = self.load('Queue', model)() # Simulate loaded data queue.meta.data = {'some': 'data'} # Perform a call queue.get_message_status() # Cached data should not be cleared self.assertEqual(queue.meta.data, {'some': 'data'}) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_lazy_loads_properties(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'Url'} ], 'load': { 'request': { 'operation': 'DescribeTest', } } } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', 'shape_name': 'ETag' }, 'LastModified': { 'type': 'string', 'shape_name': 'LastModified' }, 'Url': { 'type': 'string', 'shape_name': 'Url' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape action = action_cls.return_value action.return_value = {'ETag': 'tag', 'LastModified': 'never'} resource = self.load( 'test', model, service_model=service_model)('url') # Accessing an identifier should not call load, even if it's in # the shape members. resource.url action.assert_not_called() # Accessing a property should call load self.assertEqual(resource.e_tag, 'tag', 'ETag property returned wrong value') self.assertEqual(action.call_count, 1) # Both params should have been loaded into the data bag self.assertIn('ETag', resource.meta.data) self.assertIn('LastModified', resource.meta.data) # Accessing another property should use cached value # instead of making a second call. self.assertEqual(resource.last_modified, 'never', 'LastModified property returned wrong value') self.assertEqual(action.call_count, 1) @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_lazy_properties_missing_load(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'Url'} ] # Note the lack of a `load` method. These resources # are usually loaded via a call on a parent resource. } shape = DenormalizedStructureBuilder().with_members({ 'ETag': { 'type': 'string', }, 'LastModified': { 'type': 'string' }, 'Url': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape action = action_cls.return_value action.return_value = {'ETag': 'tag', 'LastModified': 'never'} resource = self.load( 'test', model, service_model=service_model)('url') with self.assertRaises(ResourceLoadException): resource.last_modified @mock.patch('ibm_boto3.resources.factory.ServiceAction') def test_resource_aliases_identifiers(self, action_cls): model = { 'shape': 'TestShape', 'identifiers': [ {'name': 'id', 'memberName': 'foo_id'} ] } shape = DenormalizedStructureBuilder().with_members({ 'foo_id': { 'type': 'string', }, 'bar': { 'type': 'string' }, }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape shape_id = 'baz' resource = self.load( 'test', model, service_model=service_model)(shape_id) try: self.assertEqual(resource.id, shape_id) self.assertEqual(resource.foo_id, shape_id) except ResourceLoadException: self.fail("Load attempted on identifier alias.") def test_resource_loads_references(self): model = { 'shape': 'InstanceShape', 'identifiers': [{'name': 'GroupId'}], 'has': { 'Subnet': { 'resource': { 'type': 'Subnet', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'SubnetId'} ] } }, 'Vpcs': { 'resource': { 'type': 'Vpc', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'Vpcs[].Id'} ] } } } } defs = { 'Subnet': { 'identifiers': [{'name': 'Id'}] }, 'Vpc': { 'identifiers': [{'name': 'Id'}] } } service_model = ServiceModel({ 'shapes': { 'InstanceShape': { 'type': 'structure', 'members': { 'SubnetId': { 'shape': 'String' } } }, 'String': { 'type': 'string' } } }) resource = self.load('Instance', model, defs, service_model)('group-id') # Load the resource with no data resource.meta.data = {} self.assertTrue( hasattr(resource, 'subnet'), 'Resource should have a subnet reference') self.assertIsNone( resource.subnet, 'Missing identifier, should return None') self.assertIsNone(resource.vpcs) # Load the resource with data to instantiate a reference resource.meta.data = { 'SubnetId': 'abc123', 'Vpcs': [ {'Id': 'vpc1'}, {'Id': 'vpc2'} ] } self.assertIsInstance(resource.subnet, ServiceResource) self.assertEqual(resource.subnet.id, 'abc123') vpcs = resource.vpcs self.assertIsInstance(vpcs, list) self.assertEqual(len(vpcs), 2) self.assertEqual(vpcs[0].id, 'vpc1') self.assertEqual(vpcs[1].id, 'vpc2') @mock.patch('ibm_boto3.resources.model.Collection') def test_resource_loads_collections(self, mock_model): model = { 'hasMany': { u'Queues': { 'request': { 'operation': 'ListQueues' }, 'resource': { 'type': 'Queue' } } } } defs = { 'Queue': {} } service_model = ServiceModel({}) mock_model.return_value.name = 'queues' resource = self.load('test', model, defs, service_model)() self.assertTrue(hasattr(resource, 'queues'), 'Resource should expose queues collection') self.assertIsInstance(resource.queues, CollectionManager, 'Queues collection should be a collection manager') def test_resource_loads_waiters(self): model = { "waiters": { "Exists": { "waiterName": "BucketExists", "params": [ {"target": "Bucket", "source": "identifier", "name": "Name"}] } } } defs = { 'Bucket': {} } service_model = ServiceModel({}) resource = self.load('test', model, defs, service_model)() self.assertTrue(hasattr(resource, 'wait_until_exists'), 'Resource should expose resource waiter: wait_until_exists') @mock.patch('ibm_boto3.resources.factory.WaiterAction') def test_resource_waiter_calls_waiter_method(self, waiter_action_cls): model = { "waiters": { "Exists": { "waiterName": "BucketExists", "params": [ {"target": "Bucket", "source": "identifier", "name": "Name"}] } } } defs = { 'Bucket': {} } service_model = ServiceModel({}) waiter_action = waiter_action_cls.return_value resource = self.load('test', model, defs, service_model)() resource.wait_until_exists('arg1', arg2=2) waiter_action.assert_called_with(resource, 'arg1', arg2=2) class TestResourceFactoryDanglingResource(BaseTestResourceFactory): def setUp(self): super(TestResourceFactoryDanglingResource, self).setUp() self.model = { 'has': { 'Queue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } } } } self.defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] } } def test_dangling_resources_create_resource_instance(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue('test') self.assertIsInstance(q, ServiceResource, 'Dangling resource instance not a ServiceResource') def test_hash_resource_equal(self): resource = self.load('test', self.model, self.defs)() p = resource.Queue('test') q = resource.Queue('test') self.assertEqual(p, q, "Should be equal resource") self.assertEqual(hash(p), hash(q), "Hash values should be equal") def test_hash_resource_not_equal(self): resource = self.load('test', self.model, self.defs)() p = resource.Queue('test1') q = resource.Queue('test2') self.assertNotEquals(p, q, "Should not be equal resource") self.assertNotEquals(hash(p), hash(q), "Hash values should be different") def test_dangling_resource_create_with_kwarg(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue(url='test') self.assertIsInstance(q, ServiceResource, 'Dangling resource created with kwargs is not a ServiceResource') def test_dangling_resource_shares_client(self): resource = self.load('test', self.model, self.defs)() q = resource.Queue('test') self.assertEqual(resource.meta.client, q.meta.client, 'Client was not shared to dangling resource instance') def test_dangling_resource_requires_identifier(self): resource = self.load('test', self.model, self.defs)() with self.assertRaises(ValueError): resource.Queue() def test_dangling_resource_raises_for_unknown_arg(self): resource = self.load('test', self.model, self.defs)() with self.assertRaises(ValueError): resource.Queue(url='foo', bar='baz') def test_dangling_resource_identifier_is_immutable(self): resource = self.load('test', self.model, self.defs)() queue = resource.Queue('url') # We should not be able to change the identifier's value with self.assertRaises(AttributeError): queue.url = 'foo' def test_dangling_resource_equality(self): resource = self.load('test', self.model, self.defs)() q1 = resource.Queue('url') q2 = resource.Queue('url') self.assertEqual(q1, q2) def test_dangling_resource_inequality(self): self.defs = { 'Queue': { 'identifiers': [{'name': 'Url'}], 'has': { 'Message': { 'resource': { 'type': 'Message', 'identifiers': [ {'target': 'QueueUrl', 'source': 'identifier', 'name': 'Url'}, {'target': 'Handle', 'source': 'input'} ] } } } }, 'Message': { 'identifiers': [{'name': 'QueueUrl'}, {'name': 'Handle'}] } } resource = self.load('test', self.model, self.defs)() q1 = resource.Queue('url') q2 = resource.Queue('different') m = q1.Message('handle') self.assertNotEqual(q1, q2) self.assertNotEqual(q1, m) def test_dangling_resource_loads_data(self): # Given a loadable resource instance that contains a reference # to another resource which has a resource data path, the # referenced resource should be loaded with all of the data # contained at that path. This allows loading references # which would otherwise not be loadable (missing load method) # and prevents extra load calls for others when we already # have the data available. self.defs = { 'Instance': { 'identifiers': [{'name': 'Id'}], 'has': { 'NetworkInterface': { 'resource': { 'type': 'NetworkInterface', 'identifiers': [ {'target': 'Id', 'source': 'data', 'path': 'NetworkInterface.Id'} ], 'path': 'NetworkInterface' } } } }, 'NetworkInterface': { 'identifiers': [{'name': 'Id'}], 'shape': 'NetworkInterfaceShape' } } self.model = self.defs['Instance'] shape = DenormalizedStructureBuilder().with_members({ 'Id': { 'type': 'string', }, 'PublicIp': { 'type': 'string' } }).build_model() service_model = mock.Mock() service_model.shape_for.return_value = shape cls = self.load('Instance', self.model, self.defs, service_model) instance = cls('instance-id') # Set some data as if we had completed a load action. def set_meta_data(): instance.meta.data = { 'NetworkInterface': { 'Id': 'network-interface-id', 'PublicIp': '127.0.0.1' } } instance.load = mock.Mock(side_effect=set_meta_data) # Now, get the reference and make sure it has its data # set as expected. interface = instance.network_interface self.assertIsNotNone(interface.meta.data) self.assertEqual(interface.public_ip, '127.0.0.1') class TestServiceResourceSubresources(BaseTestResourceFactory): def setUp(self): super(TestServiceResourceSubresources, self).setUp() self.model = { 'has': { 'QueueObject': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } }, 'PriorityQueue': { 'resource': { 'type': 'Queue', 'identifiers': [ {'target': 'Url', 'source': 'input'} ] } } } } self.defs = { 'Queue': { 'identifiers': [ {'name': 'Url'} ] }, 'Message': { 'identifiers': [ {'name': 'QueueUrl'}, {'name': 'ReceiptHandle'} ] } } def test_subresource_custom_name(self): resource = self.load('test', self.model, self.defs)() self.assertTrue(hasattr(resource, 'QueueObject')) def test_contains_all_subresources(self): resource = self.load('test', self.model, self.defs)() self.assertIn('QueueObject', dir(resource)) self.assertIn('PriorityQueue', dir(resource)) self.assertIn('Message', dir(resource)) def test_get_available_subresources(self): resource = self.load('test', self.model, self.defs)() self.assertTrue(hasattr(resource, 'get_available_subresources')) subresources = sorted(resource.get_available_subresources()) expected = sorted(['PriorityQueue', 'Message', 'QueueObject']) self.assertEqual(subresources, expected) def test_subresource_missing_all_subresources(self): resource = self.load('test', self.model, self.defs)() message = resource.Message('url', 'handle') self.assertNotIn('QueueObject', dir(message)) self.assertNotIn('PriorityQueue', dir(message)) self.assertNotIn('Queue', dir(message)) self.assertNotIn('Message', dir(message)) def test_event_emitted_when_class_created(self): self.load('test', self.model, self.defs) self.assertTrue(self.emitter.emit.called) call_args = self.emitter.emit.call_args # Verify the correct event name emitted. self.assertEqual(call_args[0][0], 'creating-resource-class.test.ServiceResource') # Verify we send out the class attributes dict. actual_class_attrs = sorted(call_args[1]['class_attributes']) self.assertEqual(actual_class_attrs, [ 'Message', 'PriorityQueue', 'QueueObject', 'get_available_subresources', 'meta']) base_classes = sorted(call_args[1]['base_classes']) self.assertEqual(base_classes, [ServiceResource])
en
0.896204
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' file accompanying this file. This file is # distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. # Class name # Identifier names and values # Each resource has a ``meta`` defined, so this identifier # must be renamed. # This fails because the resource has an identifier # that would be clobbered by the action name. # Only services should get dangling defs # Let's create a message and only give it a receipt handle # The required queue_url identifier should be set from the # queue itself. # Simulate loaded data # Perform a call # Cached data should be cleared # This model has NO load method. Cached data should # never be cleared since it cannot be reloaded! # Simulate loaded data # Perform a call # Cached data should not be cleared # Accessing an identifier should not call load, even if it's in # the shape members. # Accessing a property should call load # Both params should have been loaded into the data bag # Accessing another property should use cached value # instead of making a second call. # Note the lack of a `load` method. These resources # are usually loaded via a call on a parent resource. # Load the resource with no data # Load the resource with data to instantiate a reference # We should not be able to change the identifier's value # Given a loadable resource instance that contains a reference # to another resource which has a resource data path, the # referenced resource should be loaded with all of the data # contained at that path. This allows loading references # which would otherwise not be loadable (missing load method) # and prevents extra load calls for others when we already # have the data available. # Set some data as if we had completed a load action. # Now, get the reference and make sure it has its data # set as expected. # Verify the correct event name emitted. # Verify we send out the class attributes dict.
1.822501
2
utils/Geometry.py
albertdow/zinv-analysis
0
6630547
import numpy as np import numba as nb @nb.vectorize def BoundPhi(phi): if phi >= np.pi: phi -= 2*np.pi elif phi < -np.pi: phi += 2*np.pi return phi @nb.njit def DeltaR2(deta, dphi): return deta**2 + BoundPhi(dphi)**2 @nb.njit def RadToCart2D(r, phi): return r*np.cos(phi), r*np.sin(phi) @nb.njit def CartToRad2D(x, y): return np.sqrt(x**2+y**2), BoundPhi(np.arctan2(y, x)) @nb.njit def PartCoorToCart3D(pt, eta, phi): x, y = RadToCart2D(pt, phi) z = pt*np.sinh(eta) return x, y, z @nb.njit def CartToPartCoor3D(x, y, z): pt, phi = CartToRad2D(x, y) eta = np.arctanh(z/np.sqrt(z**2+pt**2)) return pt, eta, phi @nb.njit def LorTHPMToXYZE(t, h, p, m): x = t*np.cos(p) y = t*np.sin(p) z = t*np.sinh(h) e = np.sqrt(m**2 + t**2 + z**2) return x, y, z, e @nb.njit def LorXYZEToTHPM(x, y, z, e): t = np.sqrt(x**2+y**2) h = np.arctanh(z/np.sqrt(t**2+z**2)) if z!=0. else 0. p = BoundPhi(np.arctan2(y, x)) m2 = e**2 - t**2 - z**2 m = np.sign(m2) * np.sqrt(abs(m2)) return t, h, p, m
import numpy as np import numba as nb @nb.vectorize def BoundPhi(phi): if phi >= np.pi: phi -= 2*np.pi elif phi < -np.pi: phi += 2*np.pi return phi @nb.njit def DeltaR2(deta, dphi): return deta**2 + BoundPhi(dphi)**2 @nb.njit def RadToCart2D(r, phi): return r*np.cos(phi), r*np.sin(phi) @nb.njit def CartToRad2D(x, y): return np.sqrt(x**2+y**2), BoundPhi(np.arctan2(y, x)) @nb.njit def PartCoorToCart3D(pt, eta, phi): x, y = RadToCart2D(pt, phi) z = pt*np.sinh(eta) return x, y, z @nb.njit def CartToPartCoor3D(x, y, z): pt, phi = CartToRad2D(x, y) eta = np.arctanh(z/np.sqrt(z**2+pt**2)) return pt, eta, phi @nb.njit def LorTHPMToXYZE(t, h, p, m): x = t*np.cos(p) y = t*np.sin(p) z = t*np.sinh(h) e = np.sqrt(m**2 + t**2 + z**2) return x, y, z, e @nb.njit def LorXYZEToTHPM(x, y, z, e): t = np.sqrt(x**2+y**2) h = np.arctanh(z/np.sqrt(t**2+z**2)) if z!=0. else 0. p = BoundPhi(np.arctan2(y, x)) m2 = e**2 - t**2 - z**2 m = np.sign(m2) * np.sqrt(abs(m2)) return t, h, p, m
none
1
2.477593
2
Data Preparation Layer/Data Enchichment_ML prep_Outlier Detection module/modelling_main.py
marcroiglama/GIVO
1
6630548
from __future__ import division, print_function import numpy as np import pandas as pd from sklearn.externals import joblib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import modelling_functions as mf def mainEvaluateInterpolation(): # 1.Get spark data and transform to pandas df df = mf.readCSV('curated_sensors.csv') print(df.columns) variable = raw_input("\nCHOOSE A VARIABLE: ") methods = ['time', 'polynomial1','polynomial2','polynomial3', 'polynomial5','polynomial7','polynomial9'] # 2. Create a validation set with some extra NaNs df_target = df[[variable]].copy() df_validation = mf.createValidationSet(df_target.dropna().copy()) cond = df_validation['value set to NaN'].index print('\nEvaluation of filled NaNs with the mean\n') df_mean = df_validation.fillna(df_validation[variable].mean()) mf.error(df_target.loc[cond], df_mean.loc[cond,variable]) for method in methods: # 3. Interpolate to fill blanks if method[0:4] == 'poly': d = method[10] df_ip_validation = mf.interpolate(df_validation[variable].copy(), method, 4, int(d)) print('\nEvaluation of polynomial with degree ' + d + '\n') else: df_ip_validation = mf.interpolate(df_validation[variable].copy(), method, 4, None) print('\nEvaluation of ' + method +' interpolation method\n') # 4. Compare results of the df_ip_validate and original df mf.error(df_target.loc[cond],df_ip_validation.loc[cond,method]) del [df_ip_validation] def mainApplyInterpolation(): df = mf.readCSV('curated_sensors.csv') print(df.columns) variable = raw_input("\nCHOOSE A VARIABLE: ") # 5. Select to best method to apply to the data and keep these values print('\nlist of methods: mean, time, polynomial1, polynomial2,\ polynomial3, polynomial5, polynomial7, polynomial9\n') method = raw_input("CHOOSE THE BEST METHOD: ") df_target = df[[variable]].copy() if method == 'mean': df_ip = df_target.fillna(df_target.mean()) elif method[0:4] == 'poly': df_ip = mf.interpolate(df_target.copy(), method, 4, method[10]) else: df_ip = mf.interpolate(df_target.copy(), method, 4, None) blancs = df_target[variable].isnull() df_target.loc[blancs] = df_ip.loc[blancs] #6. Show results mf.interplots(df[variable].copy(),df_target.copy(),method) print('\n number of blancs on the original data:\n', df[variable].isnull().sum()) print('\n number of blancs after interpolation:\n', df_ip.isnull().sum()) print('\n if any blanc persist means that its sorrounded \ by more than other 3 blancs, they will be deleted \n') # 7. Save modified data (UNCOMMENT!) ''' df_full = mf.readCSV('interpolated_sensors.csv') df_full[variable] = df_target df_full.to_csv('interpolated_sensors.csv') ''' #firts time that the script runs: #df_target.to_csv('interpolated_sensors.csv') print("interpolation done!") def mainPreModel(): df_ip = mf.readCSV('interpolated_sensors.csv') # df_ip = mf.dropNotInterpolatedBlancs(df_ip) df_ip.to_csv('interpolated_sensors.csv') df_train, df_test = mf.splitData(df_ip, 0.3) mf.fitStandardScaler(df_train) df_train = mf.standarizing(df_train) df_test = mf.standarizing(df_test) df_train.to_csv('train_test_sets/train_set.csv') df_test.to_csv('train_test_sets/test_set.csv') print('\nfind train and test sets as csv files\n') def mainOutlierDetection(folder, model_file, train_pred_file, test_pred_file, c): # 1.Load train and test sets df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') print(len(df_train)) # 2.Create sklearn model and save it clf = mf.instanceModel(df_train, folder, model_file, c) # 3.Load sklearn model clf = joblib.load(folder + '/' + model_file) # 4.Predict and save predictions mf.predict(df_train, folder, train_pred_file, clf) mf.predict(df_test, folder, test_pred_file, clf) def mainOutlierMetrics(folder, train_pred_file, test_pred_file,): # Load predictions train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) # Calcule outlier ratios ratios = [mf.outlier_metrics(train_predicted, train_pred_file), mf.outlier_metrics(test_predicted, test_pred_file)] return ratios def mainPlotOutliers(folder, model_file, train_pred_file, test_pred_file, v1, v2, v3, ratios): # Load predictions df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') df_train = mf.inverseStandarizing(df_train) df_test = mf.inverseStandarizing(df_test) train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) df_train['outliers'] = train_predicted['outliers'] df_test['outliers'] = test_predicted['outliers'] # Plot variables if v3 != None: mf.outlier_plot3D(df_train, df_test, v1, v2, v3, model_file, ratios) else: mf.outlier_plot2D(df_train, df_test, v1, v2, model_file, ratios) def mainDimensionReduction(folder, model, train_pred_file, test_pred_file): # Read predictions df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) # Plot PCA f, (ax1,ax2) = plt.subplots(1,2) df_pca_train, df_pca_test = mf.pca(df_train.copy(), df_test.copy()) df_pca_train['outliers'] = train_predicted['outliers'] columns_except_outliers = test_predicted.columns != 'outliers' df_pca_test['outliers'] = test_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_pca_train, 'PCA', ax1) mf.plotDimensionReductionOutliers2D(df_pca_test, 'PCA',ax2) title1 = ('Train set | ' + model + ' | PCA') ax1.set_title(title1, fontsize = 9) ax1.set_xlim(-7,7) ax1.set_ylim(-10,10) title2 = ('Test set | ' + model + ' | PCA') ax2.set_title(title2, fontsize = 9) ax2.set_xlim(-7,7) ax2.set_ylim(-10,10) plt.show() # Plot T-SNE f, (ax1,ax2) = plt.subplots(1,2) df_tsne_train, df_tsne_test = mf.tsne(df_train.copy(), df_test.copy()) df_tsne_train['outliers'] = train_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_tsne_train, 't-SNE', ax1) df_tsne_test['outliers'] = test_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_tsne_test, 't-SNE', ax2) title1 = ('Train set | ' + model + ' | T-SNE') title2 = ('Test set | ' + model + ' | T-SNE') ax1.set_title(title1, fontsize = 9) ax2.set_title(title2, fontsize = 9) plt.show() if __name__ == '__main__': ''' # mainEvaluateInterpolation() # mainApplyInterpolation() # mainPreModel() ''' # inizialize algorithm = 'EllipticEnvelope' # algorithm = 'IsolationForest' # algorithm = 'LocalOutlierFactor' # algorithm = 'OneClassSVM' # algorithm = 'ensemble' c = 0.04 folder = algorithm model = folder + '_' + str(c) model_file = model + '.sav' train_pred_file = 'train_' + model + '.csv' test_pred_file = 'test_' + model + '.csv' # fit and predict #mainOutlierDetection(folder, model_file, train_pred_file, test_pred_file, c) # evaluation plt.rcParams["figure.figsize"] = [8,4] ratios = mainOutlierMetrics(folder, train_pred_file, test_pred_file,) mainPlotOutliers(folder, model_file, train_pred_file, test_pred_file, 'co', 'humidity', None, ratios) mainDimensionReduction(folder, model, train_pred_file, test_pred_file) ''' algorithms = ['EllipticEnvelope', 'IsolationForest', 'LocalOutlierFactor'] mf.ensemble(algorithms, c,'train') #mf.ensemble(algorithms, c,'test') ''' print('\n############## WORKS FINE ##################')
from __future__ import division, print_function import numpy as np import pandas as pd from sklearn.externals import joblib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import modelling_functions as mf def mainEvaluateInterpolation(): # 1.Get spark data and transform to pandas df df = mf.readCSV('curated_sensors.csv') print(df.columns) variable = raw_input("\nCHOOSE A VARIABLE: ") methods = ['time', 'polynomial1','polynomial2','polynomial3', 'polynomial5','polynomial7','polynomial9'] # 2. Create a validation set with some extra NaNs df_target = df[[variable]].copy() df_validation = mf.createValidationSet(df_target.dropna().copy()) cond = df_validation['value set to NaN'].index print('\nEvaluation of filled NaNs with the mean\n') df_mean = df_validation.fillna(df_validation[variable].mean()) mf.error(df_target.loc[cond], df_mean.loc[cond,variable]) for method in methods: # 3. Interpolate to fill blanks if method[0:4] == 'poly': d = method[10] df_ip_validation = mf.interpolate(df_validation[variable].copy(), method, 4, int(d)) print('\nEvaluation of polynomial with degree ' + d + '\n') else: df_ip_validation = mf.interpolate(df_validation[variable].copy(), method, 4, None) print('\nEvaluation of ' + method +' interpolation method\n') # 4. Compare results of the df_ip_validate and original df mf.error(df_target.loc[cond],df_ip_validation.loc[cond,method]) del [df_ip_validation] def mainApplyInterpolation(): df = mf.readCSV('curated_sensors.csv') print(df.columns) variable = raw_input("\nCHOOSE A VARIABLE: ") # 5. Select to best method to apply to the data and keep these values print('\nlist of methods: mean, time, polynomial1, polynomial2,\ polynomial3, polynomial5, polynomial7, polynomial9\n') method = raw_input("CHOOSE THE BEST METHOD: ") df_target = df[[variable]].copy() if method == 'mean': df_ip = df_target.fillna(df_target.mean()) elif method[0:4] == 'poly': df_ip = mf.interpolate(df_target.copy(), method, 4, method[10]) else: df_ip = mf.interpolate(df_target.copy(), method, 4, None) blancs = df_target[variable].isnull() df_target.loc[blancs] = df_ip.loc[blancs] #6. Show results mf.interplots(df[variable].copy(),df_target.copy(),method) print('\n number of blancs on the original data:\n', df[variable].isnull().sum()) print('\n number of blancs after interpolation:\n', df_ip.isnull().sum()) print('\n if any blanc persist means that its sorrounded \ by more than other 3 blancs, they will be deleted \n') # 7. Save modified data (UNCOMMENT!) ''' df_full = mf.readCSV('interpolated_sensors.csv') df_full[variable] = df_target df_full.to_csv('interpolated_sensors.csv') ''' #firts time that the script runs: #df_target.to_csv('interpolated_sensors.csv') print("interpolation done!") def mainPreModel(): df_ip = mf.readCSV('interpolated_sensors.csv') # df_ip = mf.dropNotInterpolatedBlancs(df_ip) df_ip.to_csv('interpolated_sensors.csv') df_train, df_test = mf.splitData(df_ip, 0.3) mf.fitStandardScaler(df_train) df_train = mf.standarizing(df_train) df_test = mf.standarizing(df_test) df_train.to_csv('train_test_sets/train_set.csv') df_test.to_csv('train_test_sets/test_set.csv') print('\nfind train and test sets as csv files\n') def mainOutlierDetection(folder, model_file, train_pred_file, test_pred_file, c): # 1.Load train and test sets df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') print(len(df_train)) # 2.Create sklearn model and save it clf = mf.instanceModel(df_train, folder, model_file, c) # 3.Load sklearn model clf = joblib.load(folder + '/' + model_file) # 4.Predict and save predictions mf.predict(df_train, folder, train_pred_file, clf) mf.predict(df_test, folder, test_pred_file, clf) def mainOutlierMetrics(folder, train_pred_file, test_pred_file,): # Load predictions train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) # Calcule outlier ratios ratios = [mf.outlier_metrics(train_predicted, train_pred_file), mf.outlier_metrics(test_predicted, test_pred_file)] return ratios def mainPlotOutliers(folder, model_file, train_pred_file, test_pred_file, v1, v2, v3, ratios): # Load predictions df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') df_train = mf.inverseStandarizing(df_train) df_test = mf.inverseStandarizing(df_test) train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) df_train['outliers'] = train_predicted['outliers'] df_test['outliers'] = test_predicted['outliers'] # Plot variables if v3 != None: mf.outlier_plot3D(df_train, df_test, v1, v2, v3, model_file, ratios) else: mf.outlier_plot2D(df_train, df_test, v1, v2, model_file, ratios) def mainDimensionReduction(folder, model, train_pred_file, test_pred_file): # Read predictions df_train = mf.readCSV('train_test_sets/train_set.csv') df_test = mf.readCSV('train_test_sets/test_set.csv') train_predicted = mf.readCSV(folder + '/' + train_pred_file) test_predicted = mf.readCSV(folder + '/' + test_pred_file) # Plot PCA f, (ax1,ax2) = plt.subplots(1,2) df_pca_train, df_pca_test = mf.pca(df_train.copy(), df_test.copy()) df_pca_train['outliers'] = train_predicted['outliers'] columns_except_outliers = test_predicted.columns != 'outliers' df_pca_test['outliers'] = test_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_pca_train, 'PCA', ax1) mf.plotDimensionReductionOutliers2D(df_pca_test, 'PCA',ax2) title1 = ('Train set | ' + model + ' | PCA') ax1.set_title(title1, fontsize = 9) ax1.set_xlim(-7,7) ax1.set_ylim(-10,10) title2 = ('Test set | ' + model + ' | PCA') ax2.set_title(title2, fontsize = 9) ax2.set_xlim(-7,7) ax2.set_ylim(-10,10) plt.show() # Plot T-SNE f, (ax1,ax2) = plt.subplots(1,2) df_tsne_train, df_tsne_test = mf.tsne(df_train.copy(), df_test.copy()) df_tsne_train['outliers'] = train_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_tsne_train, 't-SNE', ax1) df_tsne_test['outliers'] = test_predicted['outliers'] mf.plotDimensionReductionOutliers2D(df_tsne_test, 't-SNE', ax2) title1 = ('Train set | ' + model + ' | T-SNE') title2 = ('Test set | ' + model + ' | T-SNE') ax1.set_title(title1, fontsize = 9) ax2.set_title(title2, fontsize = 9) plt.show() if __name__ == '__main__': ''' # mainEvaluateInterpolation() # mainApplyInterpolation() # mainPreModel() ''' # inizialize algorithm = 'EllipticEnvelope' # algorithm = 'IsolationForest' # algorithm = 'LocalOutlierFactor' # algorithm = 'OneClassSVM' # algorithm = 'ensemble' c = 0.04 folder = algorithm model = folder + '_' + str(c) model_file = model + '.sav' train_pred_file = 'train_' + model + '.csv' test_pred_file = 'test_' + model + '.csv' # fit and predict #mainOutlierDetection(folder, model_file, train_pred_file, test_pred_file, c) # evaluation plt.rcParams["figure.figsize"] = [8,4] ratios = mainOutlierMetrics(folder, train_pred_file, test_pred_file,) mainPlotOutliers(folder, model_file, train_pred_file, test_pred_file, 'co', 'humidity', None, ratios) mainDimensionReduction(folder, model, train_pred_file, test_pred_file) ''' algorithms = ['EllipticEnvelope', 'IsolationForest', 'LocalOutlierFactor'] mf.ensemble(algorithms, c,'train') #mf.ensemble(algorithms, c,'test') ''' print('\n############## WORKS FINE ##################')
en
0.561146
# 1.Get spark data and transform to pandas df # 2. Create a validation set with some extra NaNs # 3. Interpolate to fill blanks # 4. Compare results of the df_ip_validate and original df # 5. Select to best method to apply to the data and keep these values #6. Show results # 7. Save modified data (UNCOMMENT!) df_full = mf.readCSV('interpolated_sensors.csv') df_full[variable] = df_target df_full.to_csv('interpolated_sensors.csv') #firts time that the script runs: #df_target.to_csv('interpolated_sensors.csv') # df_ip = mf.dropNotInterpolatedBlancs(df_ip) # 1.Load train and test sets # 2.Create sklearn model and save it # 3.Load sklearn model # 4.Predict and save predictions # Load predictions # Calcule outlier ratios # Load predictions # Plot variables # Read predictions # Plot PCA # Plot T-SNE # mainEvaluateInterpolation() # mainApplyInterpolation() # mainPreModel() # inizialize # algorithm = 'IsolationForest' # algorithm = 'LocalOutlierFactor' # algorithm = 'OneClassSVM' # algorithm = 'ensemble' # fit and predict #mainOutlierDetection(folder, model_file, train_pred_file, test_pred_file, c) # evaluation algorithms = ['EllipticEnvelope', 'IsolationForest', 'LocalOutlierFactor'] mf.ensemble(algorithms, c,'train') #mf.ensemble(algorithms, c,'test') ############## WORKS FINE ##################')
3.051198
3
redpanda/examples/python/kafka-produce.py
lbooker42/deephaven-core
0
6630549
<reponame>lbooker42/deephaven-core # # Test driver to produce kafka messages using single type serializers for key and value. # # To run this script, you need confluent-kafka libraries installed. # To create a dedicated venv for it, you can do: # # $ mkdir confluent-kafka; cd confluent-kafka # $ python3 -m venv confluent-kafka # $ cd confluent-kafka # $ source bin/activate # $ pip3 install confluent-kafka # $ pip3 install avro # # Note: On a Mac you may need to install the librdkafka package. # You can use "brew install librdkafka" if the pip3 command fails # with an error like "librdkafka/rdkafka.h' file not found" # as found at confluentinc/confluent-kafka-python#166. # You may also need the following (be sure to substitute the right version of librdkafka): # export C_INCLUDE_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/include # export LIBRARY_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/lib # # Examples of use for DH testing together with web UI. # # == Common to all: # # * Start the redpanda compose: (cd redpanda && docker-compose up --build) # * From web UI do: # # > from deephaven import kafka_consumer as kc # > from deephaven.stream.kafka.consumer import TableType # # == Example (1) Simple String Key and simple double Value # # From web UI do: # # > t = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Symbol', 'deephaven.value.column.name':'Price', 'deephaven.value.column.type':'double'}, 'quotes', table_type=TableType.append()) # # You should see a table show up with columns [ KafkaPartition, KafkaOffset, KafkaTimestamp, symbol, price ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py quotes 0 MSFT double:274.82 # # You should see one row show up on the web UI table, data matching above. # # == Example (2) Simple String Key and simple long Value # # From web UI do: # > t2 = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Metric', 'deephaven.value.column.name':'Value', 'deephaven.value.column.type':'long', 'deephaven.offset.column.name':'', 'deephaven.partition.column.name':''}, 'metrics', table_type=TableType.append()) # # You should see a table show up with columns: [ KafkaTimestamp, Metric, Value ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py metrics 0 us_west.latency.millis long:29 # # == Example (3) JSON. # # From web UI do: # # > from deephaven import dtypes as dh # > t3 = kc.consume({'bootstrap.servers' : 'redpanda:29092'}, 'orders', value_spec=kc.json_spec([ ('Symbol', dh.string), ('Side', dh.string), ('Price', dh.double), ('Qty', dh.int_), ('UserName', dh.string), ('UserId', dh.int_) ], mapping = { '/User/Name' : 'UserName', '/User/Id' : 'UserId'}), table_type=TableType.append()) # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 kafka-produce.py orders 0 '' 'str:{ "Symbol" : "MSFT", "Side" : "BUY", "Price" : "278.85", "Qty" : "200", "User" : { "Name" : "Pepo", "Id" : 1234 } }' # # You should see one row of data as per above showing up in the UI. # # from confluent_kafka import Producer import sys import struct data_arg_form = "type:value" def usage(): print("Usage: " + sys.argv[0] + " topic-name partition " + data_arg_form + " [" + data_arg_form + "]", file=sys.stderr) sys.exit(1) if len(sys.argv) < 4 or len(sys.argv) > 5 or (len(sys.argv) == 2 and sys.argv[1] == '-h'): usage() c = 1 topic_name = sys.argv[c] c += 1 try: partition = int(sys.argv[c]) except ValueError as err: print('Failed to parse "' + sys.argv[c] + '" as a partition number: ' + str(err), file=sys.stderr) usage() if partition < 0: print('Partition argument should be a non-negative integer, instead got: ' + str(partition), file=sys.stderr) usage() c += 1 def delivery_report(err, msg): """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """ if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message key=|{}|, value=|{}| delivered to topic {} partition {}' .format(msg.key(), msg.value(), msg.topic(), msg.partition())) # producer = Producer({ 'bootstrap.servers': 'localhost:9092', 'on_delivery': delivery_report, }) def wrong_form(data_arg): print(sys.argv[0] + ": Error, argument " + data_arg + " is not of the form " + data_arg_form + ".", file=sys.stderr) sys.exit(1) def data_arg_to_data(data_arg): s = data_arg.split(':', 1) if len(s) != 2: if len(s) == 1: # Assume string. return s[0] else: wrong_form(data_arg) if (s[0] == "str"): return s[1] if s[0] == "float": return struct.pack('>f', float(s[1])) if s[0] == "double": return struct.pack('>d', float(s[1])) if s[0] == "int": return int(s[1]).to_bytes(4, "big") if s[0] == "long": return int(s[1]).to_bytes(8, "big") print(sys.argv[0] + ": Error, type " + s[0] + " not supported.", file=sys.stderr) sys.exit(1) if len(sys.argv) == 3: key = None value = data_arg_to_data(sys.argv[c]) c += 1 else: key = data_arg_to_data(sys.argv[c]) c += 1 value = data_arg_to_data(sys.argv[c]) c += 1 producer.produce(topic=topic_name, partition=partition, key=key, value=value) producer.flush()
# # Test driver to produce kafka messages using single type serializers for key and value. # # To run this script, you need confluent-kafka libraries installed. # To create a dedicated venv for it, you can do: # # $ mkdir confluent-kafka; cd confluent-kafka # $ python3 -m venv confluent-kafka # $ cd confluent-kafka # $ source bin/activate # $ pip3 install confluent-kafka # $ pip3 install avro # # Note: On a Mac you may need to install the librdkafka package. # You can use "brew install librdkafka" if the pip3 command fails # with an error like "librdkafka/rdkafka.h' file not found" # as found at confluentinc/confluent-kafka-python#166. # You may also need the following (be sure to substitute the right version of librdkafka): # export C_INCLUDE_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/include # export LIBRARY_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/lib # # Examples of use for DH testing together with web UI. # # == Common to all: # # * Start the redpanda compose: (cd redpanda && docker-compose up --build) # * From web UI do: # # > from deephaven import kafka_consumer as kc # > from deephaven.stream.kafka.consumer import TableType # # == Example (1) Simple String Key and simple double Value # # From web UI do: # # > t = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Symbol', 'deephaven.value.column.name':'Price', 'deephaven.value.column.type':'double'}, 'quotes', table_type=TableType.append()) # # You should see a table show up with columns [ KafkaPartition, KafkaOffset, KafkaTimestamp, symbol, price ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py quotes 0 MSFT double:274.82 # # You should see one row show up on the web UI table, data matching above. # # == Example (2) Simple String Key and simple long Value # # From web UI do: # > t2 = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Metric', 'deephaven.value.column.name':'Value', 'deephaven.value.column.type':'long', 'deephaven.offset.column.name':'', 'deephaven.partition.column.name':''}, 'metrics', table_type=TableType.append()) # # You should see a table show up with columns: [ KafkaTimestamp, Metric, Value ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py metrics 0 us_west.latency.millis long:29 # # == Example (3) JSON. # # From web UI do: # # > from deephaven import dtypes as dh # > t3 = kc.consume({'bootstrap.servers' : 'redpanda:29092'}, 'orders', value_spec=kc.json_spec([ ('Symbol', dh.string), ('Side', dh.string), ('Price', dh.double), ('Qty', dh.int_), ('UserName', dh.string), ('UserId', dh.int_) ], mapping = { '/User/Name' : 'UserName', '/User/Id' : 'UserId'}), table_type=TableType.append()) # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 kafka-produce.py orders 0 '' 'str:{ "Symbol" : "MSFT", "Side" : "BUY", "Price" : "278.85", "Qty" : "200", "User" : { "Name" : "Pepo", "Id" : 1234 } }' # # You should see one row of data as per above showing up in the UI. # # from confluent_kafka import Producer import sys import struct data_arg_form = "type:value" def usage(): print("Usage: " + sys.argv[0] + " topic-name partition " + data_arg_form + " [" + data_arg_form + "]", file=sys.stderr) sys.exit(1) if len(sys.argv) < 4 or len(sys.argv) > 5 or (len(sys.argv) == 2 and sys.argv[1] == '-h'): usage() c = 1 topic_name = sys.argv[c] c += 1 try: partition = int(sys.argv[c]) except ValueError as err: print('Failed to parse "' + sys.argv[c] + '" as a partition number: ' + str(err), file=sys.stderr) usage() if partition < 0: print('Partition argument should be a non-negative integer, instead got: ' + str(partition), file=sys.stderr) usage() c += 1 def delivery_report(err, msg): """ Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). """ if err is not None: print('Message delivery failed: {}'.format(err)) else: print('Message key=|{}|, value=|{}| delivered to topic {} partition {}' .format(msg.key(), msg.value(), msg.topic(), msg.partition())) # producer = Producer({ 'bootstrap.servers': 'localhost:9092', 'on_delivery': delivery_report, }) def wrong_form(data_arg): print(sys.argv[0] + ": Error, argument " + data_arg + " is not of the form " + data_arg_form + ".", file=sys.stderr) sys.exit(1) def data_arg_to_data(data_arg): s = data_arg.split(':', 1) if len(s) != 2: if len(s) == 1: # Assume string. return s[0] else: wrong_form(data_arg) if (s[0] == "str"): return s[1] if s[0] == "float": return struct.pack('>f', float(s[1])) if s[0] == "double": return struct.pack('>d', float(s[1])) if s[0] == "int": return int(s[1]).to_bytes(4, "big") if s[0] == "long": return int(s[1]).to_bytes(8, "big") print(sys.argv[0] + ": Error, type " + s[0] + " not supported.", file=sys.stderr) sys.exit(1) if len(sys.argv) == 3: key = None value = data_arg_to_data(sys.argv[c]) c += 1 else: key = data_arg_to_data(sys.argv[c]) c += 1 value = data_arg_to_data(sys.argv[c]) c += 1 producer.produce(topic=topic_name, partition=partition, key=key, value=value) producer.flush()
en
0.440194
# # Test driver to produce kafka messages using single type serializers for key and value. # # To run this script, you need confluent-kafka libraries installed. # To create a dedicated venv for it, you can do: # # $ mkdir confluent-kafka; cd confluent-kafka # $ python3 -m venv confluent-kafka # $ cd confluent-kafka # $ source bin/activate # $ pip3 install confluent-kafka # $ pip3 install avro # # Note: On a Mac you may need to install the librdkafka package. # You can use "brew install librdkafka" if the pip3 command fails # with an error like "librdkafka/rdkafka.h' file not found" # as found at confluentinc/confluent-kafka-python#166. # You may also need the following (be sure to substitute the right version of librdkafka): # export C_INCLUDE_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/include # export LIBRARY_PATH=/opt/homebrew/Cellar/librdkafka/1.9.0/lib # # Examples of use for DH testing together with web UI. # # == Common to all: # # * Start the redpanda compose: (cd redpanda && docker-compose up --build) # * From web UI do: # # > from deephaven import kafka_consumer as kc # > from deephaven.stream.kafka.consumer import TableType # # == Example (1) Simple String Key and simple double Value # # From web UI do: # # > t = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Symbol', 'deephaven.value.column.name':'Price', 'deephaven.value.column.type':'double'}, 'quotes', table_type=TableType.append()) # # You should see a table show up with columns [ KafkaPartition, KafkaOffset, KafkaTimestamp, symbol, price ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py quotes 0 MSFT double:274.82 # # You should see one row show up on the web UI table, data matching above. # # == Example (2) Simple String Key and simple long Value # # From web UI do: # > t2 = kc.consume({'bootstrap.servers':'redpanda:29092', 'deephaven.key.column.name':'Metric', 'deephaven.value.column.name':'Value', 'deephaven.value.column.type':'long', 'deephaven.offset.column.name':'', 'deephaven.partition.column.name':''}, 'metrics', table_type=TableType.append()) # # You should see a table show up with columns: [ KafkaTimestamp, Metric, Value ] # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 ./kafka-produce.py metrics 0 us_west.latency.millis long:29 # # == Example (3) JSON. # # From web UI do: # # > from deephaven import dtypes as dh # > t3 = kc.consume({'bootstrap.servers' : 'redpanda:29092'}, 'orders', value_spec=kc.json_spec([ ('Symbol', dh.string), ('Side', dh.string), ('Price', dh.double), ('Qty', dh.int_), ('UserName', dh.string), ('UserId', dh.int_) ], mapping = { '/User/Name' : 'UserName', '/User/Id' : 'UserId'}), table_type=TableType.append()) # # Run this script on the host (not on a docker image) to produce one row: # # $ python3 kafka-produce.py orders 0 '' 'str:{ "Symbol" : "MSFT", "Side" : "BUY", "Price" : "278.85", "Qty" : "200", "User" : { "Name" : "Pepo", "Id" : 1234 } }' # # You should see one row of data as per above showing up in the UI. # # Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). # # Assume string.
2.360703
2
utils/__init__.py
thearyadev/Python-Console-Logging
0
6630550
from .console import Console
from .console import Console
none
1
1.054096
1