content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
#!/usr/bin/env python
import sys
import time
from ansible.module_utils.forward import *
try:
from fwd_api import fwd
except:
print('Error importing fwd from fwd_api. Check that you ran ' +
'setup (see README).')
sys.exit(-1)
# Module documentation for ansible-doc.
DOCUMENTATION = '''
---
module: forward_snapshot
short_description: Collects new snapshot for a given network
description:
- Collects new snapshot for a given network.
options:
properties_file_path:
description:
- Local properties file name.
url:
description:
- URL of Forward server.
required: true
username:
description:
- Username to login to Forward server.
required: true
password:
description:
- Password to login to Forward server.
required: true
network_name:
description:
- Name of the network for which collection will be performed.
required: true
freshness:
description:
- Freshness duration of the latest snapshot. If latest was not collected with in the duration provided, this
module perform new collection.
Freshness duration is in the form of Minutes, Hours and Days (examples 20m, 2h, 1h10m or 1d1h30m).
type:
description:
- Type could be either 'collect' or 'mock'.
With a collection, the Forward Collector collects configuration and state from every device in the Device page.
If 'devices' param is present to the module, only those user-specified devices are collected.
mock_snapshot:
description:
- Details of the snapshot to upload. Instead of collecting new snapshot, we will upload the snapshot provided with
this option.
'''
# Example usage for ansible-doc.
EXAMPLES = '''
---
- name: Ensure up-to-date network collection
forward_snapshot:
url: https://localhost:8443
username: admin
password: password
network_name: test-network
freshness: 10m
type: mock
mock_snapshot:
name: snapshot_1
path: /snapshots/1.zip
- name: Take a new partial collection
forward_snapshot:
url: https://localhost:8443
username: admin
password: password
network_name: test-network
type: collect
devices:
- sjc-te-fw01
- atl-edge-fw01
'''
def parse_freshness(module, freshness):
seconds = 0
current_val = 0
for c in freshness:
if c.isdigit():
current_val = current_val * 10 + int(c)
elif c in ['s', 'S']:
seconds += current_val
elif c in ['m', 'M']:
seconds += (current_val * 60)
elif c in ['h', 'H']:
seconds += (current_val * 60 * 60)
elif c in ['d', 'D']:
seconds += (current_val * 60 * 60 * 24)
else:
module.fail_json(rc=256, msg="Freshness string is invalid.")
return seconds
def get_snapshots(fwd_client_instance, network_id):
r = fwd_client_instance.get_snapshots_info(network_id, verbose=False)
return r.get_snapshots()
def is_latest_snapshot_non_fresh(snapshots, freshness_duration):
if len(snapshots) == 0:
return True
snapshot_create_time = snapshots[0].get_creation_time() / 1000
elapsed_time = time.time() - snapshot_create_time
if freshness_duration < elapsed_time:
return True
else:
return False
def upload_snapshot(fwd_client_instance, network_id, mock_snapshot):
return fwd_client_instance.upload_snapshot(network_id, mock_snapshot['path'], mock_snapshot['name'])
def take_snapshot(fwd_client_instance, network_id, snapshots, devices, wait_time):
latest_snapshot = snapshots[0] if len(snapshots) != 0 else None
if not fwd_client_instance.take_snapshot(network_id, devices):
return None
while fwd_client_instance.is_collection_inprogress(network_id) and (wait_time is None or wait_time > 0):
time.sleep(10)
if wait_time is not None:
wait_time -= 10
snapshots = get_snapshots(fwd_client_instance, network_id)
if len(snapshots) < 1:
return None
if snapshots[0].get_id() == latest_snapshot.get_id():
return None
return snapshots[0]
def main():
'''The entrypoint for this module.
Prints ansible facts in JSON format on STDOUT and exits.
'''
module = AnsibleModule(
argument_spec=dict(
properties_file_path=dict(type='str', required=False),
url=dict(type='str', required=False),
username=dict(type='str', required=False),
password=dict(type='str', required=False, no_log=True),
network_name=dict(type='str', required=False),
freshness=dict(type='str', required=False),
type=dict(type='str', required=False, default='collect', choices=['collect', 'mock']),
devices=dict(type='list', required=False),
mock_snapshot=dict(type='dict', required=False),
wait_time=dict(type='int', required=False),
)
)
properties_file_path = module.params['properties_file_path']
properties = Properties(module, properties_file_path)
url = properties.get_url()
if url is None:
module.fail_json(rc=256, msg="Forward server URL is not provided.")
username = properties.get_username()
if username is None:
module.fail_json(rc=256, msg="Username to login to Forward server is not provided.")
password = properties.get_password()
if password is None:
module.fail_json(rc=256, msg="Password to login to Forward server is not provided.")
network_name = properties.get_network_name()
if network_name is None:
module.fail_json(rc=256, msg="Network for which collection need to be performed is not provided.")
fwd_client_instance = fwd.Fwd(url, username, password, verbose=False, verify_ssl_cert=False)
freshness_duration = 0
freshness = module.params['freshness']
if freshness is not None:
freshness_duration = parse_freshness(module, freshness)
network_id = Utils.get_network_id(fwd_client_instance, network_name)
if network_id < 0:
module.fail_json(rc=256, msg="No network present with given name '%s'." % network_name)
wait_time = module.params['wait_time']
devices = module.params['devices']
snapshots = get_snapshots(fwd_client_instance, network_id)
if is_latest_snapshot_non_fresh(snapshots, freshness_duration):
new_snapshot = None
snapshot_type = module.params['type']
if snapshot_type == 'collect':
new_snapshot = take_snapshot(fwd_client_instance, network_id, snapshots, devices, wait_time)
elif snapshot_type == 'mock':
mock_snapshot = module.params['mock_snapshot']
if mock_snapshot is None:
module.fail_json(rc=256, msg="Mock snapshot details not provided.")
if 'name' not in mock_snapshot:
module.fail_json(rc=256, msg="Mock snapshot name not provided.")
if 'path' not in mock_snapshot:
module.fail_json(rc=256, msg="Mock snapshot file path not provided.")
new_snapshot = upload_snapshot(fwd_client_instance, network_id, mock_snapshot)
else:
module.fail_json(rc=256, msg="Type '%s' is not supported." % snapshot_type)
if new_snapshot is None:
module.exit_json(changed=False, failed=True)
snapshot_link = "%s/?/search?networkId=%d&snapshotId=%d" % (url, network_id, new_snapshot.get_id())
module.exit_json(changed=True, snapshot_id=new_snapshot.get_id(), snapshot_link=snapshot_link)
snapshot_link = "%s/?/search?networkId=%d&snapshotId=%d" % (url, network_id, snapshots[0].get_id())
module.exit_json(changed=False, snapshot_id=snapshots[0].get_id(), snapshot_link=snapshot_link)
# Although PEP-8 prohibits wildcard imports, ansible modules _must_ use them:
# https://github.com/ansible/ansible/blob/devel/lib/ansible/module_common.py#L116
from ansible.module_utils.basic import * # noqa
main()
|
python
|
from django.db.models import ForeignKey
from graphene.utils.str_converters import to_camel_case
# https://github.com/graphql-python/graphene/issues/348#issuecomment-267717809
def get_selected_names(info):
"""
Parses a query info into a list of composite field names.
For example the following query:
{
carts {
id
name
...cartInfo
}
}
fragment cartInfo on CartType { whatever }
Will result in an array:
[
'carts',
'carts.id',
'carts.name',
'carts.whatever'
]
"""
from graphql.language.ast import FragmentSpread
fragments = info.fragments
def iterate_field_names(prefix, field):
name = field.name.value
if isinstance(field, FragmentSpread):
results = []
new_prefix = prefix
sub_selection = fragments[field.name.value].selection_set.selections
else:
results = [prefix + name]
new_prefix = prefix + name + "."
sub_selection = (
field.selection_set.selections if field.selection_set else []
)
for sub_field in sub_selection:
results += iterate_field_names(new_prefix, sub_field)
return results
results = iterate_field_names("", info.field_asts[0])
return results
def optimize_queryset(qs, info, root):
"""
Pulls in available database relations to avoid N+1 queries.
For example the following query:
{
carts {
id
name
...cartInfo
}
}
fragment cartInfo on CartType {
store {
id
name
}
}
It will automatically pull in the 'store' relation (assuming its a ForeignKey
or ManyToMany) using the ORM.
>>> qs = Cart.objects.all()
>>> optimize_queryset(qs, info, 'carts')
"""
# right now we're only handling one level deep
root_len = len(to_camel_case(root)) + 1
selected_fields = set(
[x[root_len:] if x.startswith(root) else x for x in get_selected_names(info)]
)
select = []
for field in qs.model._meta.fields:
field_name = to_camel_case(field.name)
if field_name in selected_fields:
if isinstance(field, ForeignKey):
select.append(field.name)
if select:
qs = qs.select_related(*select)
prefetch = []
for field in qs.model._meta.many_to_many:
field_name = to_camel_case(field.name)
if field_name in selected_fields:
prefetch.append(field.name)
if prefetch:
qs = qs.prefetch_related(*prefetch)
return qs
|
python
|
"""Constants for integration_blueprint tests."""
from custom_components.arpansa_uv.const import CONF_NAME, CONF_LOCATIONS, CONF_POLL_INTERVAL
# Mock config data to be used across multiple tests
MOCK_CONFIG = {CONF_NAME: "test_arpansa", CONF_LOCATIONS: ['Brisbane','Sydney','Melbourne','Canberra'], CONF_POLL_INTERVAL: 1}
|
python
|
import json
from datetime import datetime, timedelta
from email import utils as email_utils
import pytest
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from app.models.exceptions import NotFound
from app.models.products import Brand, Category, Product, FEATURED_THRESHOLD
def create_basic_db_brand() -> Category:
return Brand(name="test", country_code="RU")
def create_basic_db_category() -> Category:
return Category(name="test")
def create_basic_db_product() -> Product:
# create product
brand = create_basic_db_brand()
category = create_basic_db_category()
product = Product(name="test", rating=5, brand=brand, categories=[category], items_in_stock=1)
return product
def test_get_all_products(client: FlaskClient, session: Session):
# Test without any db records
response = client.get('/products')
json_response = json.loads(response.data)
assert response.status_code == 200
assert not json_response.get('results')
# Populate and test with db records
for i in range(10):
product = create_basic_db_product()
session.add(product)
session.commit()
response = client.get('/products')
json_response = json.loads(response.data)
assert response.status_code == 200
assert len(json_response.get('results')) == 10
def test_read_product(client: FlaskClient, session: Session):
# create product that we should read
product = create_basic_db_product()
session.add(product)
session.commit()
# request product by id
response = client.get(f"/products/{product.id}")
json_response = json.loads(response.data)
# Check status
assert response.status_code == 200
# Check if returned object is similar
assert json_response["id"] == product.id
assert json_response["name"] == product.name
assert json_response["rating"] == product.rating
assert json_response["brand"]["id"] == product.brand_id
assert json_response["items_in_stock"] == product.items_in_stock
def test_create_product(client: FlaskClient, session: Session):
# create brand and category to add to new product
brand = create_basic_db_brand()
category = create_basic_db_category()
session.add(brand)
session.add(category)
session.commit()
now = datetime.utcnow()
# request creation of product
product_create_request = {
"name": "test",
"rating": 5,
"brand": brand.id,
"categories": [category.id],
"receipt_date": email_utils.format_datetime(now),
"expiration_date": email_utils.format_datetime(now + timedelta(days=30)),
"items_in_stock": 10
}
response = client.post('/products', data=json.dumps(product_create_request), content_type='application/json')
json_response = json.loads(response.data)
# check status
assert response.status_code == 201
# check if data is the same
product = Product.get(json_response["id"])
assert product.name == product_create_request["name"]
assert product.rating == product_create_request["rating"]
assert product.brand_id == brand.id
assert product.categories == [category]
assert product.items_in_stock == product_create_request["items_in_stock"]
def test_update_product(client: FlaskClient, session: Session):
# create product
product = create_basic_db_product()
session.add(product)
session.commit()
# check before change
product_pre_update = product.serialized
# request update
response = client.patch(
f"/products/{product.id}",
data=json.dumps({"name": "test2"}),
content_type='application/json'
)
# check status
assert response.status_code == 200
# check if product changed in database
session.refresh(product)
assert product.name == "test2"
# make sure everything else is NOT changed
product_post_update = product.serialized
assert product_post_update["id"] == product_pre_update["id"]
assert product_post_update["featured"] == product_pre_update["featured"]
assert product_post_update["brand"] == product_pre_update["brand"]
assert product_post_update["categories"] == product_pre_update["categories"]
assert product_post_update["items_in_stock"] == product_pre_update["items_in_stock"]
assert product_post_update["receipt_date"] == product_pre_update["receipt_date"]
assert product_post_update["expiration_date"] == product_pre_update["expiration_date"]
assert product_post_update["created_at"] == product_pre_update["created_at"]
def test_delete_product(client: FlaskClient, session: Session):
# create product
product = create_basic_db_product()
session.add(product)
session.commit()
# request delete
product_id = product.id
response = client.delete(f"/products/{product_id}")
# check if successful
assert response.status_code == 200
# check if product deleted
with pytest.raises(NotFound):
Product.get(product_id)
def test_acceptance_criteria_1(client: FlaskClient):
# Try to break all validation rules (excluding ones from other criteria)
response = client.post('/products', data=json.dumps({
"name": "s" * 51,
"rating": 11,
"items_in_stock": -1
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 400
assert json_response["errors"]
assert len(json_response["errors"]) == 5
def test_acceptance_criteria_2(client: FlaskClient, session: Session):
# Create brands and categories to test with
brand = create_basic_db_brand()
categories = [
create_basic_db_category() for i in range(6)
]
session.add(brand)
session.add_all(categories)
session.commit()
# Try to pass more categories than is allowed
response = client.post('/products', data=json.dumps({
"name": "test",
"rating": 5,
"brand": brand.id,
"categories": [c.id for c in categories],
"items_in_stock": 1
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 400
assert json_response["errors"]
assert len(json_response["errors"]) == 1
# Try to pass less categories than is allowed
response = client.post('/products', data=json.dumps({
"name": "test",
"rating": 5,
"brand": brand.id,
"categories": [],
"items_in_stock": 1
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 400
assert json_response["errors"]
assert len(json_response["errors"]) == 1
def test_acceptance_criteria_3(client: FlaskClient, session: Session):
# create brand and category to add to new product
brand = create_basic_db_brand()
category = create_basic_db_category()
session.add(brand)
session.add(category)
session.commit()
now = datetime.utcnow()
# Try to pass expiration date that is too early (creation)
response = client.post('/products', data=json.dumps({
"name": "test",
"rating": 5,
"brand": brand.id,
"categories": [category.id],
"expiration_date": email_utils.format_datetime(now),
"items_in_stock": 1
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 400
assert len(json_response["errors"]) == 1
assert json_response["errors"][0]["loc"][0] == 'expiration_date'
# Try to pass expiration date that is too early (update)
product = create_basic_db_product()
session.add(product)
session.commit()
response = client.patch(f"/products/{product.id}", data=json.dumps({
"expiration_date": email_utils.format_datetime(now),
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 400
assert len(json_response["errors"]) == 1
assert json_response["errors"][0]["loc"][0] == 'expiration_date'
def test_acceptance_criteria_4(client: FlaskClient, session: Session):
# create product
product = create_basic_db_product()
session.add(product)
session.commit()
assert product.featured is False
# Make sure product doesn't become featured when rating is less then threshold
response = client.patch(f'/products/{product.id}', data=json.dumps({
"rating": FEATURED_THRESHOLD - 1,
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 200
assert json_response["featured"] is False
# Check if featured is updated when rating is more then threshold
response = client.patch(f'/products/{product.id}', data=json.dumps({
"rating": FEATURED_THRESHOLD + 1,
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 200
assert json_response["featured"] is True
# Make sure product do not stop being featured if rating becomes less then threshold
response = client.patch(f'/products/{product.id}', data=json.dumps({
"rating": FEATURED_THRESHOLD - 1,
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 200
assert json_response["featured"] is True
def test_not_found(client: FlaskClient, session: Session):
response = client.get(f"/products/0")
json_response = json.loads(response.data)
assert response.status_code == 404
assert json_response["errors"]
response = client.post('/products', data=json.dumps({
"name": "test",
"rating": 5,
"brand": 0,
"categories": [0],
"items_in_stock": 10
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 404
assert json_response["errors"]
brand = create_basic_db_brand()
session.add(brand)
session.commit()
response = client.post('/products', data=json.dumps({
"name": "test",
"rating": 5,
"brand": brand.id,
"categories": [0],
"items_in_stock": 10
}), content_type='application/json')
json_response = json.loads(response.data)
assert response.status_code == 404
assert json_response["errors"]
|
python
|
print('domain.com'.endswith('com'))
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Batch-create ownCloud users
"""
__author__ = "Constantin Kraft <[email protected]>"
import sys
import argparse
import owncloud
from owncloud.owncloud import HTTPResponseError
import csv
API_URL = ''
# User needs Admin permissions
OC_USER = ''
OC_PASS = ''
oc = owncloud.Client(API_URL)
# authenticate with ownCloud
def authenticate():
try:
oc.login(OC_USER, OC_PASS)
print("Authentifizierung erfolgreich")
except Exception as e:
print("Authetifizierung fehlgeschlagen: ")
print(e)
# create user
def create_user(username, password):
try:
return oc.create_user(username, password)
except Exception as e:
print("Anlegen des Users {} mit Passwort {} fehlgeschlagen".format(username, password))
print(e)
# add user to existing group
def add_user_to_group(username, group):
try:
return oc.add_user_to_group(username, group)
except Exception as e:
print("Hinzufügen des Users {} zur Gruppe {} fehlgeschlagen".format(username, group))
print(e)
# create users
def create_users_from_file(file):
try:
with open(file, newline='') as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
if create_user(row['Name'], row['Passwort']):
print("User {} erfolgreich angelegt!".format(row['Name']))
if add_user_to_group(row['Name'], row['Alias']):
print("User {} erfolgreich zu Gruppe {} hinzugefügt!".format(row['Name'], row['Alias']))
except Exception as e:
print(e)
def main():
authenticate()
create_users_from_file(args.file)
if __name__ == "__main__":
try:
assert(API_URL != "")
assert(OC_USER != "")
assert(OC_PASS != "")
except AssertionError:
print("API-URL, Benutzername und Passwort müssen gesetzt sein!")
sys.exit(1)
parser = argparse.ArgumentParser(description="Mit diesem Skript lassen sich OwnCloud-User aus einer CSV-Datei einlesen"
" und anlegen")
parser.add_argument('-f', '--file', help='Die CSV-Datei, aus der Username, Passwort und Gruppe gelesen werden sollen',
required=True)
args = parser.parse_args()
main()
|
python
|
from chipclock.display import ModeDisplay
from chipclock.modes.clock import ClockMode
from chipclock.renderers.time import render_ascii, render_chip
from chipclock.renderers.segment import setup_pins, render_segment
seconds_pins = [
['LCD-D5', 'LCD-D11'],
['LCD-D4', 'LCD-D10'],
['LCD-D3', 'LCD-D7'],
['LCD-D20', 'LCD-D6'],
]
setup_pins(seconds_pins)
renderfunc = render_segment(seconds_pins)
disp = ModeDisplay()
clockmode = ClockMode(disp)
disp.register_mode('clock', clockmode, [render_ascii, render_chip(renderfunc)])
clockmode.run()
|
python
|
from typing import NoReturn, TypeVar, Type
import six
from .avrojson import AvroJsonConverter
TC = TypeVar('TC', bound='DictWrapper')
class DictWrapper(dict):
__slots__ = ['_inner_dict']
def __init__(self, inner_dict=None):
super(DictWrapper, self).__init__()
self._inner_dict = {} if inner_dict is None else inner_dict # type: dict
@classmethod
def _get_json_converter(cls) -> AvroJsonConverter:
# This attribute will be set by the AvroJsonConverter's init method.
return cls._json_converter
@classmethod
def from_obj(cls: Type[TC], obj, tuples=False) -> TC:
conv = cls._get_json_converter().with_tuple_union(tuples)
return conv.from_json_object(obj, cls.RECORD_SCHEMA)
def to_obj(self, tuples=False) -> dict:
conv = self._get_json_converter().with_tuple_union(tuples)
return conv.to_json_object(self, self.RECORD_SCHEMA)
def __getitem__(self, item):
return self._inner_dict.__getitem__(item)
def __iter__(self):
return self._inner_dict.__iter__()
def __len__(self):
return self._inner_dict.__len__()
def __setitem__(self, key, value) -> NoReturn:
raise NotImplementedError()
def items(self):
return self._inner_dict.items()
def keys(self):
return self._inner_dict.keys()
def values(self):
return self._inner_dict.values()
def fromkeys(self, v=None) -> NoReturn:
raise NotImplementedError
def clear(self) -> NoReturn:
raise NotImplementedError
def copy(self):
return DictWrapper(self._inner_dict.copy())
def get(self, k, d=None):
return self._inner_dict.get(k, d)
def __contains__(self, item):
return self._inner_dict.__contains__(item)
def __str__(self):
return self._inner_dict.__str__()
def __repr__(self):
return self._inner_dict.__repr__()
def __sizeof__(self):
return self._inner_dict.__sizeof__()
def pop(self, k, d=None) -> NoReturn:
raise NotImplementedError()
def popitem(self) -> NoReturn:
raise NotImplementedError()
def update(self, E=None, **F) -> NoReturn:
raise NotImplementedError()
def setdefault(self, k, d=None) -> NoReturn:
raise NotImplementedError()
def __eq__(self, other):
return self._inner_dict.__eq__(other)
def __ne__(self, other):
return self._inner_dict.__ne__(other)
def __le__(self, other):
return self._inner_dict.__le__(other)
def __ge__(self, other):
return self._inner_dict.__ge__(other)
def __lt__(self, other):
return self._inner_dict.__lt__(other)
def __gt__(self, other):
return self._inner_dict.__gt__(other)
def __hash__(self):
return self._inner_dict.__hash__()
|
python
|
"""Functions to simplify interacting with database."""
import datetime as dt
from math import ceil
from bson.objectid import ObjectId
from bson import SON
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import WriteConcern, IndexModel, ASCENDING, ReturnDocument
def init_db(config, loop):
"""Initiate the database connection.
Parameters
----------
config : AttrDict
The app configuration
loop : asyncio.AbstractEventLoop
The event loop to use for database connection
Returns
-------
db : motor.motor_asyncio.AsyncIOMotorClient
The database connection object
"""
db = AsyncIOMotorClient(
f"mongodb://{config.get('mongo', {}).get('url', 'localhost:27017')}/{config.get('mongo', {}).get('name', 'cherrydoor')}",
username=config.get("mongo", {}).get("username", None),
password=config.get("mongo", {}).get("password", None),
io_loop=loop,
)[config.get("mongo", {}).get("name", "cherrydoor")]
return db
async def setup_db(app):
"""Set up database indexes and collections.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
"""
user_indexes = [
IndexModel([("username", ASCENDING)], name="username_index", unique=True),
IndexModel([("cards", ASCENDING)], name="cards_index", sparse=True),
IndexModel([("tokens.token", ASCENDING)], name="token_index", sparse=True),
]
command_log_options = await app["db"].terminal.options()
if (
"capped" not in command_log_options
or not command_log_options["capped"]
or "timeseries" not in command_log_options
or command_log_options["timeseries"]["timeField"] != "timestamp"
):
await app["db"].drop_collection("terminal")
await app["db"].create_collection(
"terminal",
size=app["config"].get("command_log_size", 100000000),
capped=True,
max=10000,
# timeseries={
# "timeField": "timestamp",
# "metaField": "command",
# "granularity": "seconds",
# },
# expireAfterSeconds=app["config"].get(
# "command_log_expire_after", 604800
# ),
)
await app["db"].users.create_indexes(user_indexes)
async def close_db(app):
"""Close the database connection.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
"""
app["db"].close()
async def list_permissions(app, username):
"""List the permissions for a user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username of the user
Returns
-------
permissions : list
The list of permissions user has
"""
user = await app["db"].users.find_one(
{"username": username}, {"permissions": 1, "_id": 0}
)
if user is not None:
return user.get("permissions", [])
return []
async def user_exists(app, username):
"""Check if a user exists by username.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username of the user
Returns
-------
exists : bool
True if the user exists, False otherwise
"""
count = app["db"].users.count_documents({"username": username})
return count > 0
async def create_user(
app, username, hashed_password=None, permissions=None, cards=None
):
"""Create a single new user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username for the new user
hashed_password : str
The argon2id hashed password for the new user
permissions : list
The list of permissions the new user will have
cards : list
The list of cards assigned to the new user
Returns
-------
uid : str
The uid of the new user
"""
permissions = permissions if permissions else []
cards = cards if cards else []
result = (
await app["db"]
.users.with_options(write_concern=WriteConcern(w="majority"))
.insert_one(
{
"username": username,
"password": hashed_password,
"permissions": permissions,
"cards": cards,
}
)
)
return str(result.inserted_id)
async def change_user_password(app, identity, new_password_hash):
"""Change user's password.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
identity : str
The uid of the user whose password is to be changed
new_password_hash : str
The new argon2id hashed password
"""
await app["db"].users.update_one(
{"_id": ObjectId(identity)}, {"$set": {"password": new_password_hash}}
)
async def add_token_to_user(app, identity, token_name, token):
"""Assign an API token to a user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
identity : str
The uid of the user to whom the token is to be assigned
token_name : str
The frontend name of the token to be assigned
token : str
The branca token to be assigned
"""
await app["db"].users.update_one(
{"_id": ObjectId(identity)},
{"$addToSet": {"tokens": {"name": token_name, "token": token}}},
)
async def find_user_by_uid(app, identity, fields=["username"]):
"""Find a user by their uid.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
identity : str
The uid to search for
fields : list, default=["username"]
The fields to be returned in the user document
Returns
-------
user : dict
The user document
"""
return await find_user_by(app, "_id", ObjectId(identity), fields)
async def find_user_by_username(app, username, fields=["_id"]):
"""Find a user by their username.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username to search for
fields : list, default=["_id"]
The fields to be returned in the user document
Returns
-------
user : dict
The user document
"""
return await find_user_by(app, "username", username, fields)
async def find_user_by_token(app, token, fields=["username"]):
"""Find a user by an API token assigned to them.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
token : str
The API token to search for
fields : list, default=["username"]
The fields to be returned in the user document
Returns
-------
user : dict
The user document
"""
return await find_user_by(app, "tokens.token", token, fields)
async def find_user_by_cards(app, cards, fields=["username"]):
"""Find a user by a list of cards assigned to them.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
cards : list
The list of cards to search for
fields : list, default=["username"]
The fields to be returned in the user document
Returns
-------
user : dict
The user document
"""
if not isinstance(cards, list):
cards = [cards]
projection = {}
for field in fields:
projection[field] = 1
if "_id" not in fields:
projection["_id"] = 0
return await app["db"].users.find_one({"cards": cards}, projection)
async def find_user_by(app, search_fields, values, return_fields):
"""Find a user by arbritary search fields.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
search_fields : list
The fields to search for
values : list
The values to search for
return_fields : list
The fields to return in the user document
Returns
-------
user : dict
The user document
"""
if not isinstance(search_fields, list):
search_fields = [search_fields]
if not isinstance(values, list):
values = [values]
if "api_key" in search_fields:
search_fields[search_fields.index("api_key")] = "tokens.token"
projection = {}
for field in return_fields:
projection[field] = 1
if "_id" not in return_fields:
projection["_id"] = 0
user = await app["db"].users.find_one(
SON(dict(zip(search_fields, values))), projection=projection
)
return user
#
async def get_grouped_logs(app, datetime_from, datetime_to, granularity):
"""Get logs between two datetimes.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
datetime_from : datetime.datetime
The start datetime
datetime_to : datetime.datetime
The end datetime
granularity : str
The granularity of the logs to be returned
Returns
-------
logs : list
The list of logs between the two datetimes with a given granularity
"""
if not isinstance(granularity, dt.timedelta):
granularity = dt.timedelta(seconds=granularity)
boundries = [
datetime_from + granularity * i
for i in range(ceil((datetime_to - datetime_from) / granularity))
]
boundries[-1] = datetime_to + dt.timedelta(seconds=1)
pipeline = [
{"$match": {"timestamp": {"$gte": datetime_from, "$lte": datetime_to}}},
{
"$project": {
"timestamp": 1,
"successful": {"$toInt": "$success"},
"during_break": {
"$toInt": {"$eq": ["$auth_mode", "Manufacturer code"]}
},
}
},
{
"$bucket": {
"groupBy": "$timestamp",
"boundaries": boundries,
"default": "no_match",
"output": {
"count": {"$sum": 1},
"successful": {"$sum": "$successful"},
"during_break": {"$sum": "$during_break"},
},
}
},
]
logs = []
async for doc in app["db"].logs.aggregate(pipeline):
logs.append(
{
"date_from": doc["_id"].isoformat(),
"date_to": (doc["_id"] + granularity).isoformat(),
"count": doc["count"],
"successful": doc["successful"],
"during_break": doc["during_break"],
}
)
return logs
async def modify_user(app, uid=None, current_username=None, **kwargs):
"""Change user's properties.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
uid : str, default=None
The uid of the user to be modified
current_username : str, default=None
The current username of the user
**kwargs : dict
The properties to be changed.
username will override the current username
cards will override the current card list
permissions will override the current permissions
card will add a card to the user's card list
permission will add a permission to the user's permissions
Returns
-------
user : dict
The user document
"""
overwrite_keys = ["username", "cards", "permissions"]
append_keys = ["card", "permission"]
pipeline = []
if bool(set(overwrite_keys) & set(kwargs.keys())):
pipeline.append(
{
"$set": {
key: value
for key, value in kwargs.items()
if key in overwrite_keys and len(value) > 0
}
}
)
if bool(set(append_keys) & set(kwargs.keys())):
pipeline.append(
{
"$set": {
key: {"$concatArrays": [f"${key}", [value]]}
for key, value in kwargs.items()
if key in append_keys and len(value) > 0
}
}
)
if len(pipeline) <= 0:
return None
user = await app["db"].users.find_one_and_update(
{
"_id"
if uid is not None
else "username": uid
if uid is not None
else current_username
},
pipeline,
projection={"_id": 0, "username": 1, "permissions": 1, "cards": 1},
return_document=ReturnDocument.AFTER,
)
return user
# async def add_api_open_to_logs(app, )
async def user_exists(app, **kwargs):
"""Check if a user exists by arbitrary keys.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
**kwargs : dict
The properties and values to be seached for
Returns
-------
exists : bool
True if the user exists, False otherwise
"""
return app["db"].users.count_documents(kwargs) > 0
async def delete_user(app, uid=None, username=None):
"""Delete a specified user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
uid : str, default=None
The uid of the user to be deleted. If None will use username
username : str, default=None
The username of the user to be deleted if no uid is specified.
If also None won't delete anything.
Returns
-------
deleted : bool
True if the user was deleted, False otherwise
"""
if uid:
return await app["db"].users.delete_one({"_id": uid})
if username:
return await app["db"].users.delete_one({"username": username})
return False
async def add_cards_to_user(app, uid, cards):
"""Add cards to a user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
uid : str
The uid of the user to add cards to
cards : list
The cards to be added to the user
Returns
-------
user : dict
The modified user document
"""
user = await app["db"].find_one_and_update(
{"_id": uid},
{"$addToSet": {"cards": {"$each": cards}}},
projection={"_id": 0, "username": 1, "permissions": 1, "cards": 1},
return_document=ReturnDocument.AFTER,
)
return user
async def delete_cards_from_user(app, uid, cards):
"""Delete specified cards from a user.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
uid : str
The uid of the user to delete cards from
cards : list
The cards to be deleted from the user
Returns
-------
user : dict
The modified user document
"""
if not isinstance(cards, list):
cards = [cards]
user = await app["db"].users.find_one_and_update(
{"_id": uid},
{"$pullAll": {"cards": cards}},
projection={"_id": 0, "username": 1, "permissions": 1, "cards": 1},
return_document=ReturnDocument.AFTER,
)
return user
async def create_users(app, users):
"""Create multiple users.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
users : list
A list of dictionaries with user data to be created
"""
return (
await app["db"]
.users.with_options(write_concern=WriteConcern(w="majority"))
.insert_many(
[
{
"username": user.get("username"),
"password": user.get("password", None),
"permissions": user.get("permissions", []),
"cards": user.get("cards", []),
}
for user in users
]
)
)
async def get_users(app, return_fields=["username", "permissions", "cards"]):
"""Retrieve all users from the database.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
return_fields : list, default=["username", "permissions", "cards"]
The fields to be returned for each user.
Returns
-------
users : list
A list of user documents
"""
projection = {}
for field in return_fields:
projection[field] = 1
if "_id" not in return_fields:
projection["_id"] = 0
return app["db"].users.find({}, projection=projection)
async def set_default_permissions(app, username):
"""Set user permissions to the default ("enter").
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username of the user to be modified
Returns
-------
user : dict
The modified user document with usernae, permissions and cards fields
"""
user = await app["db"].users.find_one_and_update(
{"username": username},
{"$set": {"permissions": ["enter"]}},
projection={"_id": 0, "username": 1, "permissions": 1, "cards": 1},
return_document=ReturnDocument.AFTER,
)
return user
async def get_settings(app):
"""Retrieve breaks settings from the database.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
Returns
-------
breaks : dict
A dictionary with the breaks settings
"""
breaks = (await app["db"].settings.find_one({"setting": "break_times"})).get(
"value", []
)
return {"breaks": breaks}
async def save_settings(app, settings):
"""Save settings to the database.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
settings : dict
A dictionary with all settings to set
"""
# TODO optimize into a single query
for setting, value in settings.items():
await app["db"].settings.find_one_and_update(
{"setting": setting}, {"$set": {"value": value}}
)
|
python
|
#! /usr/bin/env python
#
def timestamp ( ):
#*****************************************************************************80
#
## TIMESTAMP prints the date as a timestamp.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 06 April 2013
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# None
#
import time
t = time.time ( )
print ( time.ctime ( t ) )
return None
def timestamp_test ( ):
#*****************************************************************************80
#
## TIMESTAMP_TEST tests TIMESTAMP.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 December 2014
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# None
#
import platform
print ( '' )
print ( 'TIMESTAMP_TEST:' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' TIMESTAMP prints a timestamp of the current date and time.' )
print ( '' )
timestamp ( )
#
# Terminate.
#
print ( '' )
print ( 'TIMESTAMP_TEST:' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
timestamp_test ( )
|
python
|
"""
Tests for the :module`regression_tests.parsers.c_parser.module` module.
"""
import io
import re
import sys
from textwrap import dedent
from unittest import mock
from regression_tests.utils.list import NamedObjectList
from tests.parsers.c_parser import WithModuleTests
class ModuleTests(WithModuleTests):
"""Tests for `Module`."""
def test_code_returns_original_source_code(self):
CODE = 'int main() {}'
module = self.parse(CODE)
self.assertEqual(module.code, CODE)
def test_file_name_returns_original_file_name(self):
FILE_NAME = 'test.c'
module = self.parse('int main() {}', FILE_NAME)
self.assertEqual(module.file_name, FILE_NAME)
def test_has_parse_errors_returns_false_when_no_errors(self):
module = self.parse('int main() { return 0; }')
self.assertFalse(module.has_parse_errors())
def test_has_parse_errors_returns_true_when_some_error(self):
module = self.parse('int main() { abcd }')
self.assertTrue(module.has_parse_errors())
def test_global_vars_returns_empty_list_when_no_global_vars(self):
module = self.parse('')
self.assertEqual(len(module.global_vars), 0)
def test_global_vars_returns_list_with_two_items_when_two_global_vars(self):
module = self.parse("""
int a;
int b;
""")
self.assertEqual(len(module.global_vars), 2)
def test_global_vars_returns_correct_variable_when_one_variable_with_initializer(self):
module = self.parse("""
int a = 1;
""")
var = module.global_vars[0]
self.assertEqual(var.name, 'a')
self.assertTrue(var.type.is_int())
self.assertEqual(var.initializer.value, 1)
def test_global_vars_returns_correct_var_when_var_is_array_with_initializer(self):
module = self.parse("""
char *p[] = {
"aaaa",
"bbbb"
};
""")
var = module.global_vars[0]
self.assertEqual(var.name, 'p')
self.assertTrue(var.type.is_array())
self.assertTrue(var.type.element_type.is_pointer())
self.assertTrue(var.type.element_type.pointed_type.is_char())
self.assertEqual(len(var.initializer), 2)
self.assertEqual(var.initializer[0], "aaaa")
self.assertEqual(var.initializer[1], 'bbbb')
def test_global_vars_returns_correct_var_when_var_is_struct_with_initializer(self):
module = self.parse("""
struct S {
int a;
double d;
};
struct S s1 = {2, 5.7};
""")
var = module.global_vars[0]
self.assertEqual(var.name, 's1')
self.assertTrue(var.type.is_struct())
self.assertEqual(len(var.initializer), 2)
self.assertEqual(var.initializer[0], 2)
self.assertEqual(var.initializer[1], 5.7)
def test_global_vars_returns_named_object_list(self):
module = self.parse("""
int a;
int b;
""")
self.assertIsInstance(module.global_vars, NamedObjectList)
def test_global_var_names_returns_global_var_names(self):
module = self.parse("""
int a;
int b;
int c;
""")
self.assertEqual(module.global_var_names, ['a', 'b', 'c'])
def test_global_var_count_returns_zero_when_no_global_vars(self):
module = self.parse('')
self.assertEqual(module.global_var_count, 0)
def test_global_var_count_returns_two_when_two_global_vars(self):
module = self.parse("""
int a;
int b;
""")
self.assertEqual(module.global_var_count, 2)
def test_has_global_vars_without_names_returns_false_when_no_global_vars(self):
module = self.parse('')
self.assertFalse(module.has_global_vars())
def test_has_global_vars_without_names_returns_true_when_there_are_global_vars(self):
module = self.parse('int g;')
self.assertTrue(module.has_global_vars())
def test_has_global_vars_with_single_empty_list_checks_presence_of_at_least_one_global_var(self):
module = self.parse('int g;')
self.assertTrue(module.has_global_vars([]))
def test_has_global_vars_returns_true_when_all_given_global_vars_are_present(self):
module = self.parse("""
int g1;
int g2;
int g3;
""")
self.assertTrue(module.has_global_vars('g1', 'g2'))
def test_has_global_vars_returns_true_when_all_given_global_vars_passed_as_list_are_present(self):
module = self.parse("""
int g1;
int g2;
int g3;
""")
self.assertTrue(module.has_global_vars(['g1', 'g2']))
def test_has_global_vars_disregards_order(self):
module = self.parse("""
int g1;
int g2;
int g3;
""")
self.assertTrue(module.has_global_vars('g2', 'g1'))
def test_has_global_vars_returns_false_when_not_all_given_global_vars_are_present(self):
module = self.parse("""
int g1;
int g3;
""")
self.assertFalse(module.has_global_vars('g1', 'g2'))
def test_has_global_vars_can_be_called_with_variable_object_as_argument(self):
module = self.parse("""
int g1;
int g2;
""")
var1 = self.get_var('int', 'g1')
self.assertTrue(module.has_global_vars(var1, 'g2'))
def test_has_no_global_vars_returns_true_when_no_global_vars(self):
module = self.parse('')
self.assertTrue(module.has_no_global_vars())
def test_has_no_global_vars_returns_false_when_there_are_global_vars(self):
module = self.parse('int a;')
self.assertFalse(module.has_no_global_vars())
def test_has_just_global_vars_returns_true_when_no_global_vars_and_no_global_vars_given(self):
module = self.parse('')
self.assertTrue(module.has_just_global_vars())
def test_has_just_global_vars_returns_false_when_no_global_vars_and_global_var_given(self):
module = self.parse('')
self.assertFalse(module.has_just_global_vars('g1'))
def test_has_just_global_vars_returns_false_when_more_global_vars_are_present(self):
module = self.parse("""
int g1;
int g2;
""")
self.assertFalse(module.has_just_global_vars('g1'))
def test_has_just_global_vars_returns_true_when_just_given_global_vars_are_present(self):
module = self.parse("""
int g1;
int g2;
""")
self.assertTrue(module.has_just_global_vars('g1', 'g2'))
def test_has_just_global_vars_disregards_order(self):
module = self.parse("""
int g1;
int g2;
""")
self.assertTrue(module.has_just_global_vars('g2', 'g1'))
def test_has_just_global_vars_global_var_can_be_passed_in_list(self):
module = self.parse("""
int g1;
int g2;
""")
self.assertTrue(module.has_just_global_vars(['g2', 'g1']))
def test_has_just_global_vars_global_var_can_be_passed_in_set(self):
module = self.parse("""
int g1;
int g2;
""")
self.assertTrue(module.has_just_global_vars({'g2', 'g1'}))
def test_has_just_global_vars_can_be_called_with_variable_object_as_argument(self):
module = self.parse("""
int g1;
int g2;
""")
var1 = self.get_var('int', 'g1')
self.assertTrue(module.has_just_global_vars(var1, 'g2'))
def test_has_global_var_returns_true_when_global_var_exists(self):
module = self.parse('int a;')
self.assertTrue(module.has_global_var('a'))
def test_has_global_var_can_be_called_with_variable_object_as_argument(self):
module = self.parse('int a;')
var = self.get_var('int', 'a')
self.assertTrue(module.has_global_var(var))
def test_global_vars_with_initializers_are_not_recognized_as_funcs(self):
module = self.parse("""
int a = 1;
""")
self.assertEqual(module.global_var_count, 1)
self.assertEqual(module.func_count, 0)
def test_global_var_array_initializer_compared_to_list(self):
module = self.parse("""
int array[3] = {1, 2, 3};
""")
self.assertEqual(module.global_vars[0].initializer, [1, 2, 3])
def test_global_var_array_initializer_float_is_not_equal_to_int(self):
module = self.parse("""
float array[3] = {1, 2.0, 3};
""")
self.assertNotEqual(module.global_vars[0].initializer, '[1, 2, 3]')
def test_funcs_returns_empty_list_when_no_funcs(self):
module = self.parse('')
self.assertEqual(len(module.funcs), 0)
def test_funcs_returns_two_funcs_when_two_funcs(self):
module = self.parse("""
void func1() {}
void func2() {}
""")
self.assertEqual(len(module.funcs), 2)
def test_funcs_ignores_declarations(self):
module = self.parse('int func();')
self.assertEqual(len(module.funcs), 0)
def test_funcs_ignores_structures(self):
module = self.parse('struct X { int a; };')
self.assertEqual(len(module.funcs), 0)
def test_funcs_ignores_external_funcs_from_headers(self):
module = self.parse('#include <stdio.h>')
self.assertEqual(len(module.funcs), 0)
def test_funcs_returns_named_object_list(self):
module = self.parse("""
void func1() {}
void func2() {}
""")
self.assertIsInstance(module.funcs, NamedObjectList)
def test_funcs_returns_list_with_correct_type_of_parameter_which_is_struct(self):
module = self.parse("""
struct X { int a; };
void func(struct X x) {}
""")
param_type = module.funcs[0].params[0].type
self.assertTrue(param_type.is_struct())
self.assertEqual(param_type.name, 'X')
def test_func_raises_exception_when_no_such_function_is_found(self):
module = self.parse("""
void func() {}
""")
with self.assertRaises(AssertionError):
module.func('a', 'b')
def test_func_returns_first_func_when_both_of_them_exist(self):
module = self.parse("""
void func() {}
void _func() {}
""")
self.assertEqual(module.func('func', '_func').name, 'func')
def test_func_returns_second_func_when_first_does_not_exist(self):
module = self.parse("""
void _func() {}
""")
self.assertEqual(module.func('func', '_func').name, '_func')
def test_func_can_be_called_with_function_object_as_argument(self):
code = """
void _func() {}
"""
module = self.parse(code)
fn = self.get_func(code, '_func')
self.assertEqual(module.func(fn).name, '_func')
def test_func_raises_exception_when_no_function_name_is_given(self):
module = self.parse("""
void func() {}
""")
with self.assertRaises(AssertionError):
module.func()
def test_has_funcs_without_names_returns_false_when_no_funcs(self):
module = self.parse('')
self.assertFalse(module.has_funcs())
def test_has_funcs_without_names_returns_true_when_there_are_funcs(self):
module = self.parse('void func() {}')
self.assertTrue(module.has_funcs())
def test_has_funcs_with_single_empty_list_checks_presence_of_at_least_one_func(self):
module = self.parse('void func() {}')
self.assertTrue(module.has_funcs([]))
def test_has_funcs_returns_true_when_all_given_funcs_are_present(self):
module = self.parse("""
void func1() {}
void func2() {}
void func3() {}
""")
self.assertTrue(module.has_funcs('func1', 'func2'))
def test_has_funcs_returns_true_when_all_given_funcs_passed_as_list_are_present(self):
module = self.parse("""
void func1() {}
void func2() {}
void func3() {}
""")
self.assertTrue(module.has_funcs(['func1', 'func2']))
def test_has_funcs_disrgards_order(self):
module = self.parse("""
void func1() {}
void func2() {}
void func3() {}
""")
self.assertTrue(module.has_funcs('func2', 'func1'))
def test_has_funcs_returns_false_when_not_all_given_funcs_are_present(self):
module = self.parse("""
void func1() {}
void func3() {}
""")
self.assertFalse(module.has_funcs('func1', 'func2'))
def test_has_funcs_can_be_called_with_function_object_as_argument(self):
code = """
void func1() {}
void func2() {}
"""
module = self.parse(code)
fn = self.get_func(code, 'func2')
self.assertTrue(module.has_funcs('func1', fn))
def test_has_no_funcs_returns_true_when_no_funcs(self):
module = self.parse('')
self.assertTrue(module.has_no_funcs())
def test_has_no_funcs_returns_false_when_there_are_funcs(self):
module = self.parse('void func() {}')
self.assertFalse(module.has_no_funcs())
def test_has_just_funcs_returns_true_when_no_funcs_and_no_funcs_given(self):
module = self.parse('')
self.assertTrue(module.has_just_funcs())
def test_has_just_funcs_returns_false_when_no_funcs_and_func_given(self):
module = self.parse('')
self.assertFalse(module.has_just_funcs('func'))
def test_has_just_funcs_returns_false_when_more_funcs_are_present(self):
module = self.parse("""
int func1() {}
int func2() {}
""")
self.assertFalse(module.has_just_funcs('func1'))
def test_has_just_funcs_returns_true_when_just_given_funcs_are_present(self):
module = self.parse("""
int func1() {}
int func2() {}
""")
self.assertTrue(module.has_just_funcs('func1', 'func2'))
def test_has_just_funcs_disregards_order(self):
module = self.parse("""
int func1() {}
int func2() {}
""")
self.assertTrue(module.has_just_funcs('func2', 'func1'))
def test_has_just_funcs_func_can_be_passed_in_list(self):
module = self.parse("""
int func1() {}
int func2() {}
""")
self.assertTrue(module.has_just_funcs(['func2', 'func1']))
def test_has_just_funcs_func_can_be_passed_in_set(self):
module = self.parse("""
int func1() {}
int func2() {}
""")
self.assertTrue(module.has_just_funcs({'func2', 'func1'}))
def test_has_just_funcs_can_be_called_with_function_object_as_argument(self):
code = """
void func1() {}
void func2() {}
"""
module = self.parse(code)
fn = self.get_func(code, 'func2')
self.assertTrue(module.has_just_funcs('func1', fn))
def test_has_func_returns_true_when_func_exists(self):
module = self.parse('void func() {}')
self.assertTrue(module.has_func('func'))
def test_has_func_returns_false_when_no_such_func(self):
module = self.parse('')
self.assertFalse(module.has_func('func'))
def test_has_func_matching_returns_true_when_func_matches(self):
module = self.parse('''
void func1() {}
void _func2() {}
''')
self.assertTrue(module.has_func_matching(r'_?func1'))
self.assertTrue(module.has_func_matching(r'_?func2'))
def test_has_func_matching_returns_false_when_func_does_not_match(self):
module = self.parse('void func() {}')
self.assertFalse(module.has_func_matching(r'foo'))
def test_has_func_matching_checks_whole_name(self):
module = self.parse('void func() {}')
self.assertFalse(module.has_func_matching(r''))
self.assertFalse(module.has_func_matching(r'f'))
self.assertFalse(module.has_func_matching(r'fu'))
self.assertFalse(module.has_func_matching(r'fun'))
self.assertTrue(module.has_func_matching(r'func'))
def test_func_names_returns_func_names(self):
module = self.parse("""
void func1() {}
void func2() {}
void func3() {}
""")
self.assertEqual(module.func_names, ['func1', 'func2', 'func3'])
def test_func_count_returns_zero_when_no_funcs(self):
module = self.parse('')
self.assertEqual(module.func_count, 0)
def test_func_count_returns_two_when_two_funcs(self):
module = self.parse("""
void func1() {}
void func2() {}
""")
self.assertEqual(module.func_count, 2)
def test_funcs_are_not_recognized_as_global_vars(self):
module = self.parse("""
int func() {}
""")
self.assertEqual(module.func_count, 1)
self.assertEqual(module.global_var_count, 0)
def test_comments_returns_empty_list_when_no_comments(self):
module = self.parse('int main() {}')
self.assertEqual(len(module.comments), 0)
def test_comments_returns_two_comments_when_two_comments(self):
module = self.parse("""
// before
int main() {
// inside
}
""")
self.assertEqual(module.comments, ['// before', '// inside'])
def test_hash_comment_matching_returns_true_when_comment_matches(self):
module = self.parse("""
// test
""")
self.assertTrue(module.has_comment_matching(r'// test'))
def test_hash_comment_matching_returns_false_when_comment_does_not_match(self):
module = self.parse("""
// test
""")
self.assertFalse(module.has_comment_matching(r'test'))
def test_hash_comment_matching_checks_whole_comment(self):
module = self.parse("""
// test
""")
self.assertFalse(module.has_comment_matching(r''))
self.assertFalse(module.has_comment_matching(r'/'))
self.assertFalse(module.has_comment_matching(r'// tes'))
self.assertTrue(module.has_comment_matching(r'// test'))
def test_includes_returns_empty_list_when_no_includes(self):
module = self.parse('int i;')
self.assertEqual(len(module.includes), 0)
def test_includes_returns_correct_result_when_one_include_with_angle_brackets(self):
module = self.parse("""
#include <stdio.h>
""")
self.assertEqual(len(module.includes), 1)
self.assertEqual(module.includes[0], '#include <stdio.h>')
def test_includes_returns_correct_result_when_one_include_with_quotes(self):
module = self.parse("""
#include "stdio.h"
""")
self.assertEqual(len(module.includes), 1)
self.assertEqual(module.includes[0], '#include "stdio.h"')
def test_includes_returns_list_with_two_includes_when_two_includes(self):
module = self.parse("""
#include <stdio.h>
#include <stdlib.h>
""")
self.assertEqual(len(module.includes), 2)
def test_has_include_of_file_returns_true_when_include_exists(self):
module = self.parse("""
#include <stdio.h>
""")
self.assertTrue(module.has_include_of_file('stdio.h'))
def test_has_include_of_file_returns_false_when_include_does_not_exist(self):
module = self.parse('')
self.assertFalse(module.has_include_of_file('stdio.h'))
def test_string_literal_values_returns_empty_set_if_no_literals(self):
module = self.parse('')
self.assertEqual(module.string_literal_values, set())
def test_string_literal_values_returns_correct_set_when_two_string_literals(self):
module = self.parse("""
#include <stdio.h>
void func() {
printf("str1");
printf("str2");
}
""")
self.assertEqual(module.string_literal_values, {'str1', 'str2'})
def test_string_literal_values_include_wide_string_literals(self):
module = self.parse("""
#include <stdio.h>
#include <wchar.h>
void func() {
wprintf(L"wide string");
}
""")
self.assertEqual(module.string_literal_values, {'wide string'})
def test_string_literal_values_does_not_consider_nan_as_string(self):
# There seems to be a bug in clang (cindex) that causes NAN, which
# expands to __builtin_nanf, to be considered a string literal. This
# test checks that we correctly detect and handle such situations.
module = self.parse("""
#include <math.h>
float my_nan = NAN;
""")
self.assertEqual(module.string_literal_values, set())
def test_has_string_literal_returns_false_when_no_such_literal(self):
module = self.parse('')
self.assertFalse(module.has_string_literal('contents'))
def test_has_string_literal_returns_true_when_literal_in_global_var_initializer(self):
module = self.parse("""
const char *msg = "test me";
""")
self.assertTrue(module.has_string_literal('test me'))
def test_has_string_literal_returns_true_when_literal_in_function_body(self):
module = self.parse("""
#include <stdio.h>
void func() {
if (1) {
printf("Answer is: %d", 42);
}
}
""")
self.assertTrue(module.has_string_literal('Answer is: %d'))
def test_has_string_literal_returns_true_even_when_error(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts("hello");
}
}
""")
self.assertTrue(module.has_string_literal('hello'))
def test_has_string_literal_returns_true_when_literal_in_comment(self):
# This is a side-effect of using contains() to check the presence of
# the literal.
module = self.parse("""
// "hello"
""")
self.assertTrue(module.has_string_literal('hello'))
def test_has_string_literal_returns_false_when_literal_without_quotes(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts(hello);
}
}
""")
self.assertFalse(module.has_string_literal('hello'))
def test_has_string_literal_escapes_passed_value_before_calling_contains(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts("$^()[]{}.*+?");
}
}
""")
self.assertTrue(module.has_string_literal('$^()[]{}.*+?'))
def test_has_string_literal_matching_returns_false_when_no_such_literal(self):
module = self.parse('')
self.assertFalse(module.has_string_literal_matching(r'.*'))
def test_has_string_literal_matching_returns_true_when_literal_in_global_var_initializer(self):
module = self.parse("""
const char *msg = "test me";
""")
self.assertTrue(module.has_string_literal_matching(r'te.. me'))
def test_has_string_literal_matching_returns_true_when_literal_in_function_body(self):
module = self.parse("""
#include <stdio.h>
void func() {
if (1) {
printf("Answer is: %d", 42);
}
}
""")
self.assertTrue(module.has_string_literal_matching('Answer is: .*'))
def test_has_string_literal_matching_returns_true_even_when_error(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts("hello");
}
}
""")
self.assertTrue(module.has_string_literal_matching(r'he[l]+o'))
def test_has_string_literal_matching_returns_true_when_literal_in_comment(self):
# This is a side-effect of using contains() to check the presence of
# the literal.
module = self.parse("""
// "hello"
""")
self.assertTrue(module.has_string_literal_matching(r'he[l]+o'))
def test_has_string_literal_matching_returns_false_when_literal_without_quotes(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts(hello);
}
}
""")
self.assertFalse(module.has_string_literal_matching(r'he[l]+o'))
def test_has_string_literal_matching_properly_handles_caret_and_dollar_in_regexp(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts("hello");
}
}
""")
# A caret ('^') marks the beginning of the string and a dollar ('$')
# marks the end.
self.assertTrue(module.has_string_literal_matching(r'^hello$'))
def test_has_string_literal_matching_works_even_if_regexep_is_compiled(self):
module = self.parse("""
int main() {
if (undefined_variable) {
puts("hello");
}
}
""")
self.assertTrue(module.has_string_literal_matching(re.compile(r'^hello$')))
def test_has_any_global_vars_returns_false_when_no_code(self):
module = self.parse("")
self.assertFalse(module.has_any_global_vars())
def test_has_any_global_vars_returns_true_when_global_variable_present(self):
module = self.parse("""
int i;
""")
self.assertTrue(module.has_any_global_vars())
def test_structs_returns_empty_list_when_no_structs(self):
module = self.parse('')
self.assertEqual(len(module.structs), 0)
self.assertEqual(len(module.unnamed_structs), 0)
self.assertEqual(len(module.named_structs), 0)
def test_structs_returns_list_with_two_items_when_two_structs(self):
module = self.parse("""
struct {int a};
struct S {int b};
""")
self.assertEqual(len(module.structs), 2)
def test_unnamed_structs_returns_list_with_one_items_when_two_structs_and_only_one_unnamed(self):
module = self.parse("""
struct {int a};
struct S {int b};
""")
self.assertEqual(len(module.unnamed_structs), 1)
def test_named_structs_returns_list_with_one_items_when_two_structs_and_only_one_named(self):
module = self.parse("""
struct {int a};
struct S {int b};
""")
self.assertEqual(len(module.named_structs), 1)
def test_unnamed_structs_returns_correct_struct_when_one_unnamed_struct(self):
module = self.parse("""
struct {int a};
""")
struct = module.unnamed_structs[0]
self.assertIsNone(struct.name)
self.assertEqual(struct.member_count, 1)
self.assertEqual(struct.member_names[0], 'a')
def test_named_structs_returns_correct_struct_when_one_named_struct(self):
module = self.parse("""
struct S {int a};
""")
struct = module.named_structs[0]
self.assertEqual(struct.name, 'S')
self.assertEqual(struct.member_count, 1)
self.assertEqual(struct.member_names[0], 'a')
def test_named_structs_returns_named_object_list(self):
module = self.parse("""
struct S {int a};
""")
self.assertIsInstance(module.named_structs, NamedObjectList)
def test_named_structs_returns_named_structs_names(self):
module = self.parse("""
struct S1 {int a};
struct S2 {int a};
""")
self.assertEqual(module.struct_names, ['S1', 'S2'])
def test_struct_count_returns_zero_when_no_structs(self):
module = self.parse('')
self.assertEqual(module.struct_count, 0)
self.assertEqual(module.unnamed_struct_count, 0)
self.assertEqual(module.named_struct_count, 0)
def test_named_struct_count_returns_zero_when_no_named_structs(self):
module = self.parse("""
struct {int a};
""")
self.assertEqual(module.named_struct_count, 0)
def test_unnamed_struct_count_returns_zero_when_no_unnamed_structs(self):
module = self.parse("""
struct S {int a};
""")
self.assertEqual(module.unnamed_struct_count, 0)
def test_counters_return_correct_values_when_one_named_struct_and_two_unnamed_structs(self):
module = self.parse("""
struct {char c};
struct S {int a};
struct {double d};
""")
self.assertEqual(module.struct_count, 3)
self.assertEqual(module.unnamed_struct_count, 2)
self.assertEqual(module.named_struct_count, 1)
def test_has_structs_returns_false_when_no_structs(self):
module = self.parse('')
self.assertFalse(module.has_any_structs())
self.assertFalse(module.has_any_named_structs())
self.assertFalse(module.has_any_unnamed_structs())
def test_has_structs_returns_true_when_there_are_structs(self):
module = self.parse("""
struct {char c};
struct S {int a};
""")
self.assertTrue(module.has_any_structs())
self.assertTrue(module.has_any_unnamed_structs())
self.assertTrue(module.has_any_named_structs())
def test_has_named_structs_with_empty_list_checks_presence_of_at_least_one_named_struct(self):
module = self.parse("""
struct S {int a};
""")
self.assertTrue(module.has_named_structs([]))
def test_has_named_structs_returns_true_when_all_given_named_structs_are_present(self):
module = self.parse("""
struct S {int a};
struct SO {int a};
struct SOS {int a};
""")
self.assertTrue(module.has_named_structs('S', 'SOS'))
def test_has_named_structs_returns_true_when_all_given_named_structs_passed_as_list_are_present(self):
module = self.parse("""
struct S {int a};
struct SO {int a};
struct SOS {int a};
""")
self.assertTrue(module.has_named_structs(['S', 'SOS']))
def test_has_named_structs_disregards_order(self):
module = self.parse("""
struct S {int a};
struct SO {int a};
struct SOS {int a};
""")
self.assertTrue(module.has_named_structs('SOS', 'S'))
def test_has_named_structs_returns_false_when_not_all_given_named_structs_are_present(self):
module = self.parse("""
struct S {int a};
struct SO {int a};
""")
self.assertFalse(module.has_named_structs('SOS', 'S'))
def test_has_named_structs_can_be_called_with_struct_object_as_argument(self):
code = """
struct S {int a};
struct SO {int a};
"""
module = self.parse(code)
struct = self.get_named_struct(code, 'SO')
self.assertTrue(module.has_named_structs('S', struct))
def test_has_no_structs_returns_true_when_no_structs(self):
module = self.parse('')
self.assertTrue(module.has_no_structs())
self.assertTrue(module.has_no_unnamed_structs())
self.assertTrue(module.has_no_named_structs())
def test_has_no_structs_returns_false_when_there_are_structs(self):
module = self.parse("""
struct S {int a};
struct {int a};
""")
self.assertFalse(module.has_no_structs())
self.assertFalse(module.has_no_unnamed_structs())
self.assertFalse(module.has_no_named_structs())
def test_has_just_named_structs_returns_true_when_no_named_structs_and_no_named_structs_given(self):
module = self.parse('')
self.assertTrue(module.has_just_named_structs())
def test_has_just_named_structs_returns_false_when_no_named_structs_and_named_struct_given(self):
module = self.parse('')
self.assertFalse(module.has_just_named_structs('S'))
def test_has_just_named_structs_returns_false_when_more_named_structs_are_present(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertFalse(module.has_just_named_structs('S'))
def test_has_just_named_structs_returns_true_when_just_given_named_structs_are_present(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertTrue(module.has_just_named_structs('S', 'S2'))
def test_has_just_named_structs_disregards_order(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertTrue(module.has_just_named_structs('S2', 'S'))
def test_has_just_named_structs_can_be_passed_in_list(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertTrue(module.has_just_named_structs(['S2', 'S']))
def test_has_just_named_structs_can_be_passed_in_set(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertTrue(module.has_just_named_structs({'S2', 'S'}))
def test_has_just_named_structs_disregards_unnamed_structs(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
struct {double d};
""")
self.assertTrue(module.has_just_named_structs('S', 'S2'))
def test_has_just_named_structs_can_be_called_with_struct_object_as_argument(self):
code = """
struct S {int a};
struct SO {int a};
"""
module = self.parse(code)
struct = self.get_named_struct(code, 'SO')
self.assertTrue(module.has_just_named_structs('S', struct))
def test_has_named_struct_returns_true_when_named_struct_exists(self):
module = self.parse("""
struct S {int a};
struct S2 {int a};
""")
self.assertTrue(module.has_named_struct('S'))
def test_has_named_struct_returns_false_when_named_struct_does_not_exist(self):
module = self.parse('')
self.assertFalse(module.has_named_struct('S'))
def test_has_named_struct_can_be_called_with_struct_object_as_argument(self):
code = """
struct S {int a};
struct SO {int a};
"""
module = self.parse(code)
struct = self.get_named_struct(code, 'SO')
self.assertTrue(module.has_named_struct(struct))
def test_unions_returns_empty_list_when_no_unions(self):
module = self.parse('')
self.assertEqual(len(module.unions), 0)
self.assertEqual(len(module.unnamed_unions), 0)
self.assertEqual(len(module.named_unions), 0)
def test_unions_returns_list_with_two_items_when_two_unions(self):
module = self.parse("""
union {int a};
union U {int b};
""")
self.assertEqual(len(module.unions), 2)
def test_unnamed_unions_returns_list_with_one_items_when_two_unions_and_only_one_unnamed(self):
module = self.parse("""
union {int a};
union U {int b};
""")
self.assertEqual(len(module.unnamed_unions), 1)
def test_named_unions_returns_list_with_one_items_when_two_unions_and_only_one_named(self):
module = self.parse("""
union {int a};
union U {int b};
""")
self.assertEqual(len(module.named_unions), 1)
def test_unnamed_unions_returns_correct_union_when_one_unnamed_union(self):
module = self.parse("""
union {int a};
""")
union = module.unnamed_unions[0]
self.assertIsNone(union.name)
self.assertEqual(union.member_count, 1)
self.assertEqual(union.member_names[0], 'a')
def test_named_unions_returns_correct_union_when_one_named_union(self):
module = self.parse("""
union U {int a};
""")
union = module.named_unions[0]
self.assertEqual(union.name, 'U')
self.assertEqual(union.member_count, 1)
self.assertEqual(union.member_names[0], 'a')
def test_named_unions_returns_named_object_list(self):
module = self.parse("""
union U {int a};
""")
self.assertIsInstance(module.named_unions, NamedObjectList)
def test_named_unions_returns_named_unions_names(self):
module = self.parse("""
union U1 {int a};
union U2 {int a};
""")
self.assertEqual(module.union_names, ['U1', 'U2'])
def test_union_count_returns_zero_when_no_unions(self):
module = self.parse('')
self.assertEqual(module.union_count, 0)
self.assertEqual(module.unnamed_union_count, 0)
self.assertEqual(module.named_union_count, 0)
def test_named_union_count_returns_zero_when_no_named_unions(self):
module = self.parse("""
union {int a};
""")
self.assertEqual(module.named_union_count, 0)
def test_unnamed_union_count_returns_zero_when_no_unnamed_unions(self):
module = self.parse("""
union U {int a};
""")
self.assertEqual(module.unnamed_union_count, 0)
def test_counters_return_correct_values_when_one_named_union_and_two_unnamed_unions(self):
module = self.parse("""
union {char c};
union U {int a};
union {double d};
""")
self.assertEqual(module.union_count, 3)
self.assertEqual(module.unnamed_union_count, 2)
self.assertEqual(module.named_union_count, 1)
def test_has_unions_returns_false_when_no_unions(self):
module = self.parse('')
self.assertFalse(module.has_any_unions())
self.assertFalse(module.has_any_named_unions())
self.assertFalse(module.has_any_unnamed_unions())
def test_has_unions_returns_true_when_there_are_unions(self):
module = self.parse("""
union {char c};
union U {int a};
""")
self.assertTrue(module.has_any_unions())
self.assertTrue(module.has_any_named_unions())
self.assertTrue(module.has_any_unnamed_unions())
def test_has_named_unions_with_empty_list_checks_presence_of_at_least_one_named_union(self):
module = self.parse("""
union U {int a};
""")
self.assertTrue(module.has_named_unions([]))
def test_has_named_unions_returns_true_when_all_given_named_unions_are_present(self):
module = self.parse("""
union U {int a};
union UO {int a};
union UOO {int a};
""")
self.assertTrue(module.has_named_unions('U', 'UOO'))
def test_has_named_unions_returns_true_when_all_given_named_unions_passed_as_list_are_present(self):
module = self.parse("""
union U {int a};
union UO {int a};
union UOO {int a};
""")
self.assertTrue(module.has_named_unions(['U', 'UOO']))
def test_has_named_unions_disregards_order(self):
module = self.parse("""
union U {int a};
union UO {int a};
union UOO {int a};
""")
self.assertTrue(module.has_named_unions('UOO', 'U'))
def test_has_named_unions_returns_false_when_not_all_given_named_unions_are_present(self):
module = self.parse("""
union U {int a};
union UO {int a};
""")
self.assertFalse(module.has_named_unions('UOO', 'U'))
def test_has_named_unions_can_be_called_with_union_object_as_argument(self):
code = """
union U {int a};
union UO {int a};
"""
module = self.parse(code)
union = self.get_named_union(code, 'UO')
self.assertTrue(module.has_named_unions('U', union))
def test_has_no_unions_returns_true_when_no_unions(self):
module = self.parse('')
self.assertTrue(module.has_no_unions())
self.assertTrue(module.has_no_unnamed_unions())
self.assertTrue(module.has_no_named_unions())
def test_has_no_unions_returns_false_when_there_are_unions(self):
module = self.parse("""
union U {int a};
union {int a};
""")
self.assertFalse(module.has_no_unions())
self.assertFalse(module.has_no_unnamed_unions())
self.assertFalse(module.has_no_named_unions())
def test_has_just_named_unions_returns_true_when_no_named_unions_and_no_named_unions_given(self):
module = self.parse('')
self.assertTrue(module.has_just_named_unions())
def test_has_just_named_unions_returns_false_when_no_named_unions_and_named_union_given(self):
module = self.parse('')
self.assertFalse(module.has_just_named_unions('U'))
def test_has_just_named_unions_returns_false_when_more_named_unions_are_present(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertFalse(module.has_just_named_unions('U'))
def test_has_just_named_unions_returns_true_when_just_given_named_unions_are_present(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertTrue(module.has_just_named_unions('U', 'U2'))
def test_has_just_named_unions_disregards_order(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertTrue(module.has_just_named_unions('U2', 'U'))
def test_has_just_named_unions_can_be_passed_in_list(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertTrue(module.has_just_named_unions(['U2', 'U']))
def test_has_just_named_unions_can_be_passed_in_set(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertTrue(module.has_just_named_unions({'U2', 'U'}))
def test_has_just_named_unions_disregards_unnamed_unions(self):
module = self.parse("""
union U {int a};
union U2 {int a};
union {double d};
""")
self.assertTrue(module.has_just_named_unions('U', 'U2'))
def test_has_just_named_unions_can_be_called_with_union_object_as_argument(self):
code = """
union U {int a};
union UO {int a};
"""
module = self.parse(code)
union = self.get_named_union(code, 'UO')
self.assertTrue(module.has_just_named_unions('U', union))
def test_has_named_union_returns_true_when_named_union_exists(self):
module = self.parse("""
union U {int a};
union U2 {int a};
""")
self.assertTrue(module.has_named_union('U'))
def test_has_named_union_returns_false_when_named_union_does_not_exist(self):
module = self.parse('')
self.assertFalse(module.has_named_unions('U'))
def test_has_named_union_can_be_called_with_union_object_as_argument(self):
code = """
union U {int a};
union UO {int a};
"""
module = self.parse(code)
union = self.get_named_union(code, 'UO')
self.assertTrue(module.has_named_union(union))
def test_enums_returns_empty_list_when_no_enums(self):
module = self.parse('')
self.assertEqual(len(module.enums), 0)
self.assertEqual(len(module.unnamed_enums), 0)
self.assertEqual(len(module.named_enums), 0)
def test_enums_returns_list_with_two_items_when_two_enums(self):
module = self.parse("""
enum {a};
enum e {b};
""")
self.assertEqual(len(module.enums), 2)
def test_unnamed_enums_returns_list_with_one_items_when_two_enums_and_only_one_unnamed(self):
module = self.parse("""
enum {a};
enum e {b};
""")
self.assertEqual(len(module.unnamed_enums), 1)
def test_named_enums_returns_list_with_one_items_when_two_enums_and_only_one_named(self):
module = self.parse("""
enum {a};
enum e {b};
""")
self.assertEqual(len(module.named_enums), 1)
def test_unnamed_enums_returns_correct_enum_when_one_unnamed_enum(self):
module = self.parse("""
enum {a};
""")
enum = module.unnamed_enums[0]
self.assertIsNone(enum.name)
self.assertEqual(enum.item_count, 1)
self.assertEqual(enum.item_names[0], 'a')
def test_named_enums_returns_correct_enum_when_one_named_enum(self):
module = self.parse("""
enum e {a};
""")
enum = module.named_enums[0]
self.assertEqual(enum.name, 'e')
self.assertEqual(enum.item_count, 1)
self.assertEqual(enum.item_names[0], 'a')
def test_named_enums_returns_named_object_list(self):
module = self.parse("""
enum e {a};
""")
self.assertIsInstance(module.named_enums, NamedObjectList)
def test_named_enums_returns_named_enums_names(self):
module = self.parse("""
enum e1 {a};
enum e2 {a};
""")
self.assertEqual(module.enum_names, ['e1', 'e2'])
def test_enum_count_returns_zero_when_no_enums(self):
module = self.parse('')
self.assertEqual(module.enum_count, 0)
self.assertEqual(module.unnamed_enum_count, 0)
self.assertEqual(module.named_enum_count, 0)
def test_named_enum_count_returns_zero_when_no_named_enums(self):
module = self.parse("""
enum {a};
""")
self.assertEqual(module.named_enum_count, 0)
def test_unnamed_enum_count_returns_zero_when_no_unnamed_enums(self):
module = self.parse("""
enum e {a};
""")
self.assertEqual(module.unnamed_enum_count, 0)
def test_counters_return_correct_values_when_one_named_enum_and_two_unnamed_enums(self):
module = self.parse("""
enum {c};
enum e {a};
enum {d};
""")
self.assertEqual(module.enum_count, 3)
self.assertEqual(module.unnamed_enum_count, 2)
self.assertEqual(module.named_enum_count, 1)
def test_has_enums_returns_false_when_no_enums(self):
module = self.parse('')
self.assertFalse(module.has_any_enums())
self.assertFalse(module.has_any_named_enums())
self.assertFalse(module.has_any_unnamed_enums())
def test_has_enums_returns_true_when_there_are_enums(self):
module = self.parse("""
enum {c};
enum e {a};
""")
self.assertTrue(module.has_any_enums())
self.assertTrue(module.has_any_named_enums())
self.assertTrue(module.has_any_unnamed_enums())
def test_has_named_enums_with_empty_list_checks_presence_of_at_least_one_named_enum(self):
module = self.parse("""
enum e {a};
""")
self.assertTrue(module.has_named_enums([]))
def test_has_named_enums_returns_true_when_all_given_named_enums_are_present(self):
module = self.parse("""
enum e {a};
enum e1 {b};
enum e2 {c};
""")
self.assertTrue(module.has_named_enums('e', 'e2'))
def test_has_named_enums_returns_true_when_all_given_named_enums_passed_as_list_are_present(self):
module = self.parse("""
enum e {a};
enum e1 {b};
enum e2 {c};
""")
self.assertTrue(module.has_named_enums(['e', 'e2']))
def test_has_named_enums_disregards_order(self):
module = self.parse("""
enum e {a};
enum e1 {b};
enum e2 {c};
""")
self.assertTrue(module.has_named_enums('e', 'e2'))
def test_has_named_enums_returns_false_when_not_all_given_named_enums_are_present(self):
module = self.parse("""
enum e {a};
enum e1 {b};
""")
self.assertFalse(module.has_named_enums('e2', 'e'))
def test_has_named_enums_can_be_called_with_enum_object_as_argument(self):
code = """
enum e {a};
enum e1 {b};
"""
module = self.parse(code)
enum = self.get_named_enum(code, 'e1')
self.assertTrue(module.has_named_enums('e', enum))
def test_has_no_enums_returns_true_when_no_enums(self):
module = self.parse('')
self.assertTrue(module.has_no_enums())
self.assertTrue(module.has_no_unnamed_enums())
self.assertTrue(module.has_no_named_enums())
def test_has_no_enums_returns_false_when_there_are_enums(self):
module = self.parse("""
enum e {a};
enum {b};
""")
self.assertFalse(module.has_no_enums())
self.assertFalse(module.has_no_unnamed_enums())
self.assertFalse(module.has_no_named_enums())
def test_has_just_named_enums_returns_true_when_no_named_enums_and_no_named_enums_given(self):
module = self.parse('')
self.assertTrue(module.has_just_named_enums())
def test_has_just_named_enums_returns_false_when_no_named_enums_and_named_enum_given(self):
module = self.parse('')
self.assertFalse(module.has_just_named_enums('e'))
def test_has_just_named_enums_returns_false_when_more_named_enums_are_present(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertFalse(module.has_just_named_enums('e'))
def test_has_just_named_enums_returns_true_when_just_given_named_enums_are_present(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertTrue(module.has_just_named_enums('e', 'e2'))
def test_has_just_named_enums_disregards_order(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertTrue(module.has_just_named_enums('e2', 'e'))
def test_has_just_named_enums_can_be_passed_in_list(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertTrue(module.has_just_named_enums(['e2', 'e']))
def test_has_just_named_enums_can_be_passed_in_set(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertTrue(module.has_just_named_enums({'e2', 'e'}))
def test_has_just_named_enums_disregards_unnamed_enums(self):
module = self.parse("""
enum e {a};
enum e2 {b};
enum {c};
""")
self.assertTrue(module.has_just_named_enums('e', 'e2'))
def test_has_just_named_enums_can_be_called_with_enum_object_as_argument(self):
code = """
enum e {a};
enum e1 {b};
"""
module = self.parse(code)
enum = self.get_named_enum(code, 'e1')
self.assertTrue(module.has_just_named_enums('e', enum))
def test_has_named_enum_returns_true_when_named_enum_exists(self):
module = self.parse("""
enum e {a};
enum e2 {b};
""")
self.assertTrue(module.has_named_enum('e'))
def test_has_named_enum_returns_false_when_named_enum_does_not_exist(self):
module = self.parse('')
self.assertFalse(module.has_named_enums('e'))
def test_has_named_enum_can_be_called_with_enum_object_as_argument(self):
code = """
enum e {a};
enum e1 {b};
"""
module = self.parse(code)
enum = self.get_named_enum(code, 'e1')
self.assertTrue(module.has_named_enum(enum))
def test_enum_item_names_returns_names_of_all_items_in_all_enums_in_module(self):
module = self.parse("""
enum e {a};
enum e2 {b};
enum {c};
""")
self.assertEqual(module.enum_item_names, ['a', 'b', 'c'])
def test_enum_item_count_returns_correct_value(self):
module = self.parse("""
enum e {a};
enum e2 {b};
enum {c};
""")
self.assertEqual(module.enum_item_count, 3)
def test_empty_enums_returns_empty_enums(self):
module = self.parse("""
enum e {a};
enum e2 {};
enum e3 {c};
""")
self.assertEqual(len(module.empty_enums), 1)
self.assertEqual(module.empty_enums[0].name, 'e2')
def test_empty_enum_count_returns_correct_value(self):
module = self.parse("""
enum e {a};
enum e2 {};
enum e3 {c};
""")
self.assertEqual(module.empty_enum_count, 1)
def test_has_any_empty_enums_returns_true_when_empty_enums(self):
module = self.parse("""
enum {};
""")
self.assertTrue(module.has_any_empty_enums())
def test_has_any_empty_enums_returns_false_when_no_empty_enums(self):
module = self.parse("""
enum {a};
""")
self.assertFalse(module.has_any_empty_enums())
def test_has_no_empty_enums_returns_false_when_empty_enums(self):
module = self.parse("""
enum {};
""")
self.assertFalse(module.has_no_empty_enums())
def test_has_no_empty_enums_returns_true_when_no_empty_enums(self):
module = self.parse("""
enum {a};
""")
self.assertTrue(module.has_no_empty_enums())
def test_dump_calls_dump_to_with_stdout(self):
module = self.parse('')
module.dump_to = mock.Mock()
module.dump()
module.dump_to.assert_called_once_with(sys.stdout, False)
def test_dump_calls_dump_to_with_stdout_and_verbose(self):
module = self.parse('')
module.dump_to = mock.Mock()
module.dump(True)
module.dump_to.assert_called_once_with(sys.stdout, True)
def test_dump_to(self):
stream = io.StringIO()
module = self.parse("""
#include <stdio.h>
#include <stdlib.h>
int x = 25;
double d;
struct s {
int a;
char c;
} s1 = {14, 1};
union u {
float f;
double d;
} u1;
enum e {
LEFT,
RIGHT
};
float func(int a) {
return 42.0;
}
int main() {
printf("str1");
return 0;
}
""")
module.dump_to(stream)
self.assertEqual(
stream.getvalue(),
dedent("""\
dummy.c
Includes:
---------
#include <stdio.h>
#include <stdlib.h>
Global vars:
------------
int x = 25
double d
struct s s1 = {14, 1}
union u u1
Structs:
--------
struct s {
int a;
char c;
}
Unions:
-------
union u {
float f;
double d;
}
Enums:
------
enum e {
LEFT,
RIGHT
}
Functions:
----------
float func(int a)
int main()
String literals:
----------------
str1
""")
)
def test_dump_to_verbose(self):
stream = io.StringIO()
module = self.parse("""
#include <stdio.h>
struct s {
int a;
char c;
} s1 = {14, 1};
union u {
double d;
};
enum { LEFT, RIGHT };
int main() {
printf("str1");
int i;
i = 8;
double pi = 3.14;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
;
}
if(1) {
i = 5;
while(35) {
;
}
}
}
while(6) {
if(1 > 2) {
}
}
xyz: ;
ijk: ;
switch(i) {
case 25:
goto xyz;
break;
default:
goto ijk;
}
do {} while(7);
return 42;
}
""")
module.dump_to(stream, True)
self.assertEqual(
stream.getvalue(),
dedent("""\
dummy.c
Includes:
---------
#include <stdio.h>
Global vars:
------------
struct s s1 = {14, 1}
Structs:
--------
struct s {
int a;
char c;
}
Unions:
-------
union u {
double d;
}
Enums:
------
enum {
LEFT,
RIGHT
}
Functions:
----------
int main()
String literals:
----------------
str1
Dump of main:
=============
int main()
Called functions:
-----------------
printf
For loops:
----------
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
While loops:
------------
while (35)
while (6)
Do while loops:
---------------
do while (7)
Assignments:
------------
i = 8
double pi = 3.14
int i = 0
int j = 0
i = 5
Variable definitions:
---------------------
int i
double pi = 3.14
int i = 0
int j = 0
If statements:
--------------
if (1)
if (1 > 2)
Return statements:
------------------
return 42
Switch statements:
------------------
switch(i) {
case 25
default
}
Goto statements:
----------------
goto xyz
goto ijk
Labels:
-------
xyz:
ijk:
Empty statement count:
----------------------
4
""")
)
def test_repr_returns_correct_repr(self):
module = self.parse("""
enum {};
""")
self.assertEqual(repr(module), "<Module file_name='dummy.c'>")
|
python
|
import types
from operator import add
import sys
from common.functions import permutations, pick_from
COMMON_ENGLISH_WORDS = ['of', 'the', 'he', 'she', 'when', 'if', 'was']
ALPHABET = map(chr, range(ord('a'), ord('z') + 1) + range(ord('A'), ord('Z') + 1))
NUMBERS = set(map(str, range(0, 10)))
SPECIAL_CHARACTERS = {'.', ',', ':', ';', '&', '\n', ' ', '(', ')', '[', ']', '$', '!', '?', "'", '"', '-', '=', '%', '@'}
ACCEPTABLE_ENGLISH_CHARACTERS = set(ALPHABET) | SPECIAL_CHARACTERS | NUMBERS
def decrypt(encrypted, key_length):
if isinstance(encrypted, types.GeneratorType):
return decrypt(to_list(encrypted), key_length)
best_solution, best_rank = None, -sys.maxint
solutions = [_attempt_decrypt_with_key(encrypted, key) for key in generate_keys(key_length)]
for solution in solutions:
if rank_as_english(solution) > best_rank:
best_solution = solution
best_rank = rank_as_english(solution)
return best_solution
def to_list(gen):
return [t for t in gen]
def generate_keys(key_length):
res = []
for symbols in pick_from(ALPHABET, key_length):
res += map(lambda perm: reduce(add, perm), permutations(symbols))
return res
def _attempt_decrypt_with_key(encrypted, key):
message = ''
for i in xrange(len(encrypted)):
char = chr(encrypted[i] ^ ord(key[i % len(key)]))
if not char in ACCEPTABLE_ENGLISH_CHARACTERS:
return ""
message += char
return message
def rank_as_english(possibly_in_english):
lowered = possibly_in_english.lower()
word_count_found = sum(map(int, map(lambda w: w in lowered, COMMON_ENGLISH_WORDS)))
return word_count_found
|
python
|
# File name: SIM_SolarSys.py
# Author: Nawaf Abdullah
# Creation Date: 9/October/2018
# Description: numerical simulation of the n-body problem of a solar system
from classicalMech.planet import Planet
import matplotlib.pyplot as plt
# Constants
PI = 3.14159
class System:
def __init__(self, i_ms, i_planet=None):
"""
initialize system with a start and a planet
:param i_planet: planet object
:param i_ms: mass of the system's star
"""
self.ms = i_ms
if i_planet is not None:
self.planets = i_planet
else:
self.planets = list()
def add_planet(self, i_planet):
"""
adds a planet to the system
:param i_planet: planet object
"""
self.planets.append(i_planet)
def del_planet(self, key):
"""
deletes a planet from the system
:param key: used to specify the planet object to be deleted
"""
for i in range(len(self.planets)):
if self.planets[i].get_key() == key:
del self.planets[i]
elif self.planets[i].get_key() != key and i <= len(self.planets):
raise ValueError("Object not found, key may be incorrect")
else:
continue
def calc_system(self, n, dt):
"""
Calculates system orbits
:param n: number of time steps
:param dt: time step size
"""
for j in range(n):
for A in self.planets:
i = len(A.vx) - 1
sys_vx = A.vx[i] - (4 * PI * PI * A.dx[i] * dt) / (A.R_i(i) ** 3)
sys_vy = A.vy[i] - (4 * PI * PI * A.dy[i] * dt) / (A.R_i(i) ** 3)
for B in self.planets:
if A is B:
continue
else:
M = B.m / self.ms
dx = A.dx[i] - B.dx[i]
dy = A.dy[i] - B.dy[i]
sys_vx -= (4 * PI * PI * M * dx * dt) / (A.R_ab_i(i, B))
sys_vy -= (4 * PI * PI * M * dy * dt) / (A.R_ab_i(i, B))
A.vx.append(sys_vx)
A.vy.append(sys_vy)
A.dx.append(A.dx[i] + A.vx[i + 1] * dt)
A.dy.append(A.dy[i] + A.vy[i + 1] * dt)
def plot(self):
"""
Plot the trajectories of the planets in the solar system
"""
for i in range(len(self.planets)):
i_key = self.planets[i].get_key()
plt.plot(self.planets[i].dx, self.planets[i].dy, label=str(i_key))
plt.legend()
plt.show()
def output_txt(self):
"""
outputs data to a text file
:return: None
"""
data = open("solar_system.txt", "a")
for i in range(len(self.planets)):
i_data = "Planet [" + str(i) + "]"
for j in range(len(self.planets[i].dx)):
i_data = "[i=" + str(j)+"]"+"[x]: " + str(self.planets[i].dx[j]) + "[y]: " + str(self.planets[i].dy[j])
data.write(i_data)
"""
# test case
sys = System(500000)
pl1 = Planet(4, 1, -1, 0, 2)
sys.add_planet(pl1)
pl2 = Planet(2, -2, -2, -0.8, 0.2)
sys.add_planet(pl2)
pl3 = Planet(3, -1, -1, 2, 0)
sys.add_planet(pl3)
pl4 = Planet(10, 1.5, 1.5, 1.5, -0.5)
sys.add_planet(pl4)
sys.calc_system(10000, 0.001)
sys.plot()
"""
|
python
|
# -*- coding: utf-8 -*-
import json
from jinja2.ext import Extension
from jinja2 import nodes
from watson.assets.webpack import exceptions
from watson.common.decorators import cached_property
__all__ = ['webpack']
class WebpackExtension(Extension):
tags = set(['webpack'])
cached_stats = None
@cached_property
def config(self):
conf = self.environment.application.config
return conf.get('assets', {}).get('webpack', {})
def parse(self, parser):
stream = parser.stream
lineno = next(stream).lineno
bundle = nodes.Const('main')
type_ = nodes.Const(None)
first = True
kwargs = []
while stream.current.type != 'block_end':
if not first:
stream.expect('comma')
first = False
if stream.current.test('name') and stream.look().test('assign'):
name = next(stream).value
stream.skip()
value = parser.parse_expression()
if name == 'bundle':
bundle = value
elif name == 'type':
type_ = value
else:
kwargs.append(nodes.Keyword(name, value))
args = [bundle, type_]
call = self.call_method('render', args=args, kwargs=kwargs)
call_block = nodes.CallBlock(call, [], [], [])
call_block.set_lineno(lineno)
return call_block
def load_stats(self):
if self.config.get('use_cache', True) and self.cached_stats:
return
data = {
'chunks': {
'main': []
}
}
try:
with open(self.config.get('stats_file', 'webpack-stats.json')) as f:
data = json.load(f)
except Exception:
raise exceptions.NotReadyError('Stats file not found, run Webpack.')
self.cached_stats = data
def _render(self, asset, type_=None):
extension = asset.split('.')[-1]
if extension == type_ or not type_:
asset_path = '{}/{}'.format(
self.config.get('bundle_dir', ''), asset)
return self._render_tag(asset_path)
def _render_tag(self, asset):
if asset.endswith('.js'):
return '<script type="text/javascript" src="{}"></script>'.format(
asset)
elif asset.endswith('.css'):
return '<link type="text/css" href="{}" rel="stylesheet">'.format(
asset)
def render(self, bundle, type_, caller=None, **kwargs):
self.load_stats()
if self.cached_stats['status'] != 'done':
raise exceptions.NotReadyError(
'Invalid stats file, please run Webpack again.')
assets = []
for _bundle in self.cached_stats['chunks'].get(bundle, []):
asset = self._render(_bundle['name'], type_)
if asset:
assets.append(asset)
return '\n'.join(assets)
webpack = WebpackExtension
|
python
|
#:coding=utf8:
import logging
from django.test import TestCase as DjangoTestCase
from django.conf import settings
from jogging.models import Log, jogging_init
class DatabaseHandlerTestCase(DjangoTestCase):
def setUp(self):
from jogging.handlers import DatabaseHandler, MockHandler
import logging
self.JOGGING = getattr(settings, 'JOGGING', None)
settings.JOGGING = {
'database_test': {
'handler': DatabaseHandler(),
'level': logging.DEBUG,
},
'multi_test': {
'handlers': [
{ 'handler': DatabaseHandler(), 'level': logging.DEBUG },
{ 'handler': MockHandler(), 'level': logging.DEBUG },
],
},
}
jogging_init()
def tearDown(self):
import logging
# clear out all handlers on loggers
loggers = [logging.getLogger(""), logging.getLogger("database_test"), logging.getLogger("multi_test")]
for logger in loggers:
logger.handlers = []
# delete all log entries in the database
for l in Log.objects.all():
l.delete()
if self.JOGGING:
settings.JOGGING = self.JOGGING
jogging_init()
def test_basic(self):
logger = logging.getLogger("database_test")
logger.info("My Logging Test")
log_obj = Log.objects.latest()
self.assertEquals(log_obj.level, "INFO")
self.assertEquals(log_obj.source, "database_test")
self.assertEquals(log_obj.msg, "My Logging Test")
self.assertTrue(log_obj.host)
def test_multi(self):
logger = logging.getLogger("multi_test")
logger.info("My Logging Test")
log_obj = Log.objects.latest()
self.assertEquals(log_obj.level, "INFO")
self.assertEquals(log_obj.source, "multi_test")
self.assertEquals(log_obj.msg, "My Logging Test")
self.assertTrue(log_obj.host)
log_obj = settings.JOGGING["multi_test"]["handlers"][1]["handler"].msgs[0]
self.assertEquals(log_obj.levelname, "INFO")
self.assertEquals(log_obj.name, "multi_test")
self.assertEquals(log_obj.msg, "My Logging Test")
class DictHandlerTestCase(DjangoTestCase):
def setUp(self):
from jogging.handlers import MockHandler
import logging
self.JOGGING = getattr(settings, 'JOGGING', None)
settings.JOGGING = {
'dict_handler_test': {
'handlers': [
{ 'handler': MockHandler(), 'level': logging.ERROR },
{ 'handler': MockHandler(), 'level': logging.INFO },
],
},
}
jogging_init()
def tearDown(self):
import logging
# clear out all handlers on loggers
loggers = [logging.getLogger(""), logging.getLogger("database_test"), logging.getLogger("multi_test")]
for logger in loggers:
logger.handlers = []
# delete all log entries in the database
for l in Log.objects.all():
l.delete()
if self.JOGGING:
settings.JOGGING = self.JOGGING
jogging_init()
def test_basic(self):
logger = logging.getLogger("dict_handler_test")
error_handler = settings.JOGGING["dict_handler_test"]["handlers"][0]["handler"]
info_handler = settings.JOGGING["dict_handler_test"]["handlers"][1]["handler"]
logger.info("My Logging Test")
# Make sure we didn't log to the error handler
self.assertEquals(len(error_handler.msgs), 0)
log_obj = info_handler.msgs[0]
self.assertEquals(log_obj.levelname, "INFO")
self.assertEquals(log_obj.name, "dict_handler_test")
self.assertEquals(log_obj.msg, "My Logging Test")
class GlobalExceptionTestCase(DjangoTestCase):
urls = 'jogging.tests.urls'
def setUp(self):
from jogging.handlers import DatabaseHandler, MockHandler
import logging
self.JOGGING = getattr(settings, 'JOGGING', None)
self.GLOBAL_LOG_HANDLERS = getattr(settings, 'GLOBAL_LOG_HANDLERS', None)
self.GLOBAL_LOG_LEVEL = getattr(settings, 'GLOBAL_LOG_LEVEL', None)
loggers = [logging.getLogger("")]
for logger in loggers:
logger.handlers = []
settings.JOGGING = {}
settings.GLOBAL_LOG_HANDLERS = [MockHandler()]
settings.GLOBAL_LOG_LEVEL = logging.DEBUG
jogging_init()
def tearDown(self):
import logging
# clear out all handlers on loggers
loggers = [logging.getLogger("")]
for logger in loggers:
logger.handlers = []
# delete all log entries in the database
for l in Log.objects.all():
l.delete()
if self.JOGGING:
settings.JOGGING = self.JOGGING
if self.GLOBAL_LOG_HANDLERS:
settings.GLOBAL_LOG_HANDLERS = self.GLOBAL_LOG_HANDLERS
if self.GLOBAL_LOG_LEVEL:
settings.GLOBAL_LOG_LEVEL = self.GLOBAL_LOG_LEVEL
jogging_init()
def test_exception(self):
from views import TestException
try:
resp = self.client.get("/exception_view")
self.fail("Expected Exception")
except TestException:
pass
root_handler = logging.getLogger("").handlers[0]
log_obj = root_handler.msgs[0]
self.assertEquals(log_obj.levelname, "ERROR")
self.assertEquals(log_obj.name, "root")
self.assertTrue("Traceback" in log_obj.msg)
|
python
|
"""Defines preselections. Currently implements 'loose' and 'tight' strategies."""
from __future__ import annotations
__all__ = ["preselection_mask", "cut_vars"]
from functools import singledispatch
import awkward as ak
import numpy as np
from uproot.behaviors.TTree import TTree
def cut_vars(strength: str) -> list[str]:
"""Returns a list of relevant variables to cut on, depending on cut strength."""
loose = [
"HGamEventInfoAuxDyn.yybb_btag77_cutFlow",
"HGamEventInfoAuxDyn.isPassed",
"HGamAntiKt4PFlowCustomVtxHggJetsAuxDyn.DL1r_FixedCutBEff_85",
"HGamEventInfoAuxDyn.yybb_candidate_jet1_fix",
]
tight = [
"HGamEventInfoAuxDyn.yybb_btag77_cutFlow",
"HGamEventInfoAuxDyn.isPassed",
"HGamEventInfoAuxDyn.passCrackVetoCleaning",
"HGamAntiKt4PFlowCustomVtxHggJetsAuxDyn.DL1r_FixedCutBEff_77",
"HGamEventInfoAuxDyn.yybb_candidate_jet1_fix",
"HGamEventInfoAuxDyn.yybb_candidate_jet2_fix",
]
if strength == "loose":
return loose
elif strength == "tight":
return tight
elif strength == "all":
return list(set(loose + tight))
else:
raise NotImplementedError(f"no protocol for cut strength '{strength}'")
# "2bjets"
def _mask_tight(
arrs: ak.Array,
) -> np.ndarray:
# go from arr[a, b ,c ,...] to arr[[a], [b], [c], ...] (fancy jagged indexing)
jet1_ind = ak.from_regular(
arrs["bjet1_idx"][:, np.newaxis],
axis=1,
)
jet2_ind = ak.from_regular(
arrs["bjet2_idx"][:, np.newaxis],
axis=1,
)
bjet1_req = (
ak.flatten(
arrs["HGamAntiKt4PFlowCustomVtxHggJetsAuxDyn.DL1r_FixedCutBEff_77"][
jet1_ind
],
)
== 1
)
bjet2_req = (
ak.flatten(
arrs["HGamAntiKt4PFlowCustomVtxHggJetsAuxDyn.DL1r_FixedCutBEff_77"][
jet2_ind
],
)
== 1
)
mask = (
(arrs["HGamEventInfoAuxDyn.yybb_btag77_cutFlow"] == 6)
* (arrs["HGamEventInfoAuxDyn.isPassed"] == 1)
* (arrs["HGamEventInfoAuxDyn.passCrackVetoCleaning"] == 1)
* bjet1_req
* bjet2_req
)
return mask.to_numpy().astype("bool")
def _from_tree_tight(
tree: TTree,
) -> np.ndarray:
arrs = tree.arrays(cut_vars("tight"))
return _mask_tight(arrs)
# "1bjet_2jets"
def _mask_loose(
arrs: ak.Array,
) -> np.ndarray:
# go from arr[a, b ,c ,...] to arr[[a], [b], [c], ...] (fancy jagged indexing)
jet1_ind = ak.from_regular(
arrs["bjet1_idx"][:, np.newaxis],
axis=1,
)
bjet_req = (
ak.flatten(
arrs["HGamAntiKt4PFlowCustomVtxHggJetsAuxDyn.DL1r_FixedCutBEff_85"][
jet1_ind
],
)
== 1
)
mask = (
(arrs["HGamEventInfoAuxDyn.yybb_btag77_cutFlow"] > 3)
* (arrs["HGamEventInfoAuxDyn.isPassed"] == 1)
* bjet_req
)
return mask.to_numpy().astype("bool")
def _from_tree_loose(
tree: TTree,
) -> np.ndarray:
arrs = tree.arrays(cut_vars("loose"))
return _mask_loose(arrs)
@singledispatch
def preselection_mask(data, strength: str) -> np.ndarray: # type: ignore
"""Constructs the mask representing a specified preselection strength.
Usage:
```
# my_data can be an awkward/numpy array or an uproot TTree
mask = shml.preselection_mask(my_data, 'loose')
# if my_data is an array:
cut_data = my_data[mask]
# or an uproot TTree:
data = my_data.arrays(list_of_my_variables, my_aliases)
cut_data = data[mask]
```
"""
raise NotImplementedError(
f"{type(data)} is not a supported type; "
+ "please provide an uproot tree or awkward array",
)
@preselection_mask.register
def _from_array(
data: ak.Array,
strength: str,
) -> np.ndarray: # usage: array[preselection.array_mask(array)]
if strength == "loose":
return _mask_loose(data)
elif strength == "tight":
return _mask_tight(data)
else:
raise NotImplementedError(f"no protocol for cut strength '{strength}'")
@preselection_mask.register
def _from_tree(
data: TTree,
strength: str,
) -> np.ndarray: # usage: tree.arrays()[preselection.array_mask(tree)]
if strength == "loose":
return _from_tree_loose(data)
elif strength == "tight":
return _from_tree_tight(data)
else:
raise NotImplementedError(f"no protocol for cut strength '{strength}'")
|
python
|
from tutils import Any
from tutils import Callable
from tutils import List
from tutils import Tuple
from tutils import cast
from tutils import concat
from tutils import reduce
from tutils import lmap
from tutils import splitstriplines
from tutils import load_and_process_input
from tutils import run_tests
""" END HELPER FUNCTIONS """
Coords = Tuple[int, int]
CoordsPair = Tuple[Coords, Coords]
DAY = "06"
INPUT, TEST = f"input-{DAY}.txt", f"test-input-{DAY}.txt"
TA1 = None
TA2 = None
ANSWER1 = 400410
ANSWER2 = 15343601
def process_one(data: List[str]) -> int:
def reducer(grid: List, line: str) -> List:
coords, command = parse_command(line)
return change_area(alter, grid, coords, command)
lights = [[0] * 1000 for i in range(0, 1000)]
return sum(concat(reduce(reducer, data, lights)))
def parse_command(text: str) -> Tuple[CoordsPair, str]:
stripped = text.replace("turn ", "").strip()
command, area = stripped.split(" ", 1)
coords = get_coords(area)
return (coords, command)
def get_coords(text: str) -> CoordsPair:
start, end = text.split(" through ")
start_strings, end_strings = start.split(","), end.split(",")
start_coords = (int(start_strings[0]), int(start_strings[1]))
end_coords = (int(end_strings[0]), int(end_strings[1]))
return start_coords, end_coords
def change_area(
func: Callable, grid: List, coords: CoordsPair, command: str
) -> List:
start, end = coords
for j in range(start[1], end[1] + 1):
for i in range(start[0], end[0] + 1):
grid[j][i] = func(grid[j][i], command)
return grid
def alter(current_value: int, command: str) -> int:
new_values = {"on": 1, "off": 0, "toggle": int(not bool(current_value))}
return new_values[command]
def process_two(data: Any) -> Any:
def reducer(grid: List, command: str) -> List:
return change_area(alter2, grid, *parse_command(command))
lights = [[0] * 1000 for i in range(0, 1000)]
return sum(concat(reduce(reducer, data, lights)))
def alter2(current_value: int, command: str) -> int:
new_values = {
"on": current_value + 1,
"off": max([0, current_value - 1]),
"toggle": current_value + 2,
}
return new_values[command]
def cli_main() -> None:
input_funcs = [splitstriplines]
data = load_and_process_input(INPUT, input_funcs)
run_tests(TEST, TA1, TA2, ANSWER1, input_funcs, process_one, process_two)
answer_one = process_one(data)
assert answer_one == ANSWER1
print("Answer one:", answer_one)
answer_two = process_two(data)
assert answer_two == ANSWER2
print("Answer two:", answer_two)
if __name__ == "__main__":
cli_main()
"""
--- Day 6: Probably a Fire Hazard ---
Because your neighbors keep defeating you in the holiday house decorating
contest year after year, you've decided to deploy one million lights in a
1000x1000 grid.
Furthermore, because you've been especially nice this year, Santa has mailed
you instructions on how to display the ideal lighting configuration.
Lights in your grid are numbered from 0 to 999 in each direction; the lights at
each corner are at 0,0, 0,999, 999,999, and 999,0. The instructions include
whether to turn on, turn off, or toggle various inclusive ranges given as
coordinate pairs. Each coordinate pair represents opposite corners of a
rectangle, inclusive; a coordinate pair like 0,0 through 2,2 therefore refers
to 9 lights in a 3x3 square. The lights all start turned off.
To defeat your neighbors this year, all you have to do is set up your lights by
doing the instructions Santa sent you in order.
For example:
turn on 0,0 through 999,999 would turn on (or leave on) every light.
toggle 0,0 through 999,0 would toggle the first line of 1000 lights,
turning off the ones that were on, and turning on the ones that were off.
turn off 499,499 through 500,500 would turn off (or leave off) the middle
four lights.
After following the instructions, how many lights are lit?
Your puzzle answer was 400410.
--- Part Two ---
You just finish implementing your winning light pattern when you realize you
mistranslated Santa's message from Ancient Nordic Elvish.
The light grid you bought actually has individual brightness controls; each
light can have a brightness of zero or more. The lights all start at zero.
The phrase turn on actually means that you should increase the brightness of
those lights by 1.
The phrase turn off actually means that you should decrease the brightness of
those lights by 1, to a minimum of zero.
The phrase toggle actually means that you should increase the brightness of
those lights by 2.
What is the total brightness of all lights combined after following Santa's
instructions?
For example:
turn on 0,0 through 0,0 would increase the total brightness by 1.
toggle 0,0 through 999,999 would increase the total brightness by 2000000.
Your puzzle answer was 15343601.
"""
|
python
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import __future__
import sys
print("===" * 30)
print("SAMPLE INPUT:")
print("===" * 30)
print(open("./input14.txt", 'r').read())
sys.stdin = open("./input14.txt", 'r')
#print(open("./challenge_sample_input", 'r').read())
#sys.stdin = open("./challenge_sample_input", 'r')
print("===" * 30)
print("SAMPLE OUTPUT:")
print("===" * 30)
print(open("./output14.txt", 'r').read())
#print(open("./challenge_sample_output", 'r').read())
print("===" * 30)
print("START")
print("===" * 30)
import itertools
K,M = map(int,raw_input().split())
a = [i for i in [map(int,raw_input().split())[1:] for _ in range(K)]]
def T(a): return sum([i ** 2 for i in a]) % M
print(max([T(n) for n in itertools.product(*a)]))
|
python
|
# -*- coding: utf-8 -*-
import io
import time
import queue
import socket
import select
import functools
from quickgui.framework.quick_base import time_to_die
class DisconnectedException(Exception):
'''Socket was disconnected'''
pass
class QueueClient():
'''
TCP client for queue-based communication.
Runs an infinite loop where it will connect to the specified host
and port, send whatever data comes from qout to the socket, and puts
any incoming data from the socket into qin.
qin and qout are seen from the perspective of the client, so qin is data
going to the client, and qout is data going to the task.
If the server connection is lost, this client will automatically try
to reconnect in an infinite loop instead of shutting down.
'''
def __init__(self, host, port, qin, qout):
self.qin = qin
self.qout = qout
self.host = host
self.port = port
self.connected = False
def run(self):
'''
Main client loop
Loop forever trying to reconnect if the connection fails,
and keep the queues active in any case.
Unlike in socket_server, we don't use threads because we want
to handle reconnects transparently, and having asynchronous
read/write becomes too complicated when the underlying socket
changes without warning.
'''
while not time_to_die():
self.connect()
try:
r, _, _ = select.select([self.sock, self.qout], [], [])
if self.qout in r:
self.write()
if self.sock in r:
self.read()
except DisconnectedException:
self.disconnect()
def read(self):
msg = None
try:
msg = self.sockfile.readline()
if msg:
self.qin.put(msg, block=False)
else:
print('recv giving up')
raise DisconnectedException
except queue.Full:
return
except OSError as e:
print('Exception: ', e)
raise DisconnectedException
def write(self):
try:
msg = self.qout.get(block=False)
self.sockfile.write(msg + '\n')
self.sockfile.flush()
except queue.Empty:
return
except OSError as e:
print('Send failed', e)
raise DisconnectedException
def connect(self):
if not self.connected:
# Provide a fake sockfile for read/write in case we don't connect
self.sockfile = io.StringIO('')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print('connecting to ', self.host, self.port)
self.sock.connect((self.host, self.port))
self.sockfile = self.sock.makefile('rw')
self.connected = True
print('Connected!')
except Exception as e:
print(e)
time.sleep(1) # Slow down reconnect loop
def disconnect(self):
try:
self.connected = False
self.sock.close()
except Exception:
pass
def _start_client(host, port, qin, qout):
client = QueueClient(host, port, qin, qout)
client.run()
def get_client(host, port):
'''Get a TCP client adapter
Returns a callable that, when called, produces a TCP client that will
connect to `host`:`port`, and can be used to connect a GUI's or
another client's input/output queues to a TCP socket.
The callable will have two arguments: `qin` and `qout`, that must be
the same queues used in the GUI instantiation.
'''
return functools.partial(_start_client, host, port)
|
python
|
import xml4h
import os
import re
import spacy
#doc = xml4h.parse('tests/data/monty_python_films.xml')
#https://xml4h.readthedocs.io/en/latest/
class getData:
def __init__(self, name, path):
self.name = name
self.path = path
self.files = []
# test
self.testfile = None
self.text_questions_dict = {}
self.text_answers_dict = {}
def getXML(self):
for path, dirnames, filenames in os.walk(self.path):
# print('{} {} {}'.format(repr(path), repr(dirnames), repr(filenames)))
for file in filenames:
if os.path.splitext(file)[1] == '.xml':
file_path = path + "/" + file
self.files.append(file_path)
for file in self.files:
print(file)
def test(self):
# get data
doc = xml4h.parse('/Users/zhaohuilee/Desktop/RA/2020-fall/ASGA/data/semeval2013-Task7-2and3way/training/3way/beetle/FaultFinding-BULB_C_VOLTAGE_EXPLAIN_WHY1.xml')
q_id = print(doc.question["id"])
q_text = print(doc.question.questionText.text)
self.text_questions_dict[q_id] = q_text
for st_ans in doc.question.studentAnswers.studentAnswer[:3]:
print(st_ans.text)
def tokenize(text):
tok = spacy.load('en')
text = re.sub(r"[^\x00-\x7F]+", " ", text)
regex = re.compile('[' + re.escape(string.punctuation) + '0-9\\r\\t\\n]') # remove punctuation and numbers
nopunct = regex.sub(" ", text.lower())
return [token.text for token in tok.tokenizer(nopunct)]
def return3way(self):
print("Hello my name is " + self.name)
if __name__ == "__main__":
print("start ")
three_way = getData("3-way",
"/Users/zhaohuilee/Desktop/RA/2020-fall/ASGA/data/semeval2013-Task7-2and3way/training/3way/beetle")
## three_way.getXML()
three_way.test()
print("done")
|
python
|
import os
import logging
"""
Provide a common interface for all our components to do logging
"""
def basic_logging_conf():
"""Will set up a basic logging configuration using basicConfig()"""
return basic_logging_conf_with_level(
logging.DEBUG if "MDBRAIN_DEBUG" in os.environ else logging.INFO)
def basic_logging_conf_with_level(level):
logging.basicConfig(format='%(asctime)s %(levelname)s %(module)s:%(lineno)s '
'%(message)s', level=level)
def logger_for_transaction(name: str, t_id: int):
"""Provide a specific default_logger for a transaction. The provided transaction id
will always be logged with every message.
Parameters
----------
name: str
The default_logger ID
t_id: int
The transaction id
"""
logger = logging.getLogger(name + "_" + str(t_id))
class TransactionFilter(logging.Filter):
def filter(self, record):
record.transaction_id = t_id
return True
logger.addFilter(TransactionFilter())
logger.propagate = False
if len(logger.handlers) == 0:
logger.addHandler(logging.StreamHandler())
for handler in logger.handlers:
handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s transaction=%(transaction_id)s '
'%(module)s:%(lineno)s %(message)s'))
return logger
|
python
|
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Implement a linked list with insert, append, find, delete, length, and print methods.
#
# * [Constraints](#Constraints)
# * [Test Cases](#Test-Cases)
# * [Algorithm](#Algorithm)
# * [Code](#Code)
# * [Unit Test](#Unit-Test)
# ## Constraints
#
# * Can we assume this is a non-circular, singly linked list?
# * Yes
# * Do we keep track of the tail or just the head?
# * Just the head
# * Can we insert None values?
# * No
# ## Test Cases
#
# ### Insert to Front
#
# * Insert a None
# * Insert in an empty list
# * Insert in a list with one element or more elements
#
# ### Append
#
# * Append a None
# * Append in an empty list
# * Insert in a list with one element or more elements
#
# ### Find
#
# * Find a None
# * Find in an empty list
# * Find in a list with one element or more matching elements
# * Find in a list with no matches
#
# ### Delete
#
# * Delete a None
# * Delete in an empty list
# * Delete in a list with one element or more matching elements
# * Delete in a list with no matches
#
# ### Length
#
# * Length of zero or more elements
#
# ### Print
#
# * Print an empty list
# * Print a list with one or more elements
# ## Algorithm
#
# ### Insert to Front
#
# * If the data we are inserting is None, return
# * Create a node with the input data, set node.next to head
# * Assign the head to the node
#
# Complexity:
# * Time: O(1)
# * Space: O(1)
#
# ### Append
#
# * If the data we are inserting is None, return
# * Create a node with the input data
# * If this is an empty list
# * Assign the head to the node
# * Else
# * Iterate to the end of the list
# * Set the final node's next to the new node
#
# Complexity:
# * Time: O(n)
# * Space: O(1)
#
# ### Find
#
# * If data we are finding is None, return
# * If the list is empty, return
# * For each node
# * If the value is a match, return it
# * Else, move on to the next node
#
# Complexity:
# * Time: O(n)
# * Space: O(1)
#
# ### Delete
#
# * If data we are deleting is None, return
# * If the list is empty, return
# * For each node, keep track of previous and current node
# * If the value we are deleting is a match in the current node
# * Update previous node's next pointer to the current node's next pointer
# * We do not have have to explicitly delete in Python
# * Else, move on to the next node
# * As an alternative, we could avoid the use of two pointers by evaluating the current node's next value:
# * If the next value is a match, set the current node's next to next.next
# * Special care should be taken if deleting the head node
#
# Complexity:
# * Time: O(n)
# * Space: O(1)
#
# ### Length
#
# * For each node
# * Increase length counter
#
# Complexity:
# * Time: O(n)
# * Space: O(1)
#
# ### Print
#
# * For each node
# * Print the node's value
#
# Complexity:
# * Time: O(n)
# * Space: O(1)
# ## Code
# In[1]:
get_ipython().run_cell_magic('writefile', 'linked_list.py', 'class Node(object):\n\n def __init__(self, data, next=None):\n self.next = next\n self.data = data\n\n def __str__(self):\n return self.data\n\n\nclass LinkedList(object):\n\n def __init__(self, head=None):\n self.head = head\n\n def __len__(self):\n curr = self.head\n counter = 0\n while curr is not None:\n counter += 1\n curr = curr.next\n return counter\n\n def insert_to_front(self, data):\n if data is None:\n return None\n node = Node(data, self.head)\n self.head = node\n return node\n\n def append(self, data):\n if data is None:\n return None\n node = Node(data)\n if self.head is None:\n self.head = node\n return node\n curr_node = self.head\n while curr_node.next is not None:\n curr_node = curr_node.next\n curr_node.next = node\n return node\n\n def find(self, data):\n if data is None:\n return None\n curr_node = self.head\n while curr_node is not None:\n if curr_node.data == data:\n return curr_node\n curr_node = curr_node.next\n return None\n\n def delete(self, data):\n if data is None:\n return\n if self.head is None:\n return\n if self.head.data == data:\n self.head = self.head.next\n return\n prev_node = self.head\n curr_node = self.head.next\n while curr_node is not None:\n if curr_node.data == data:\n prev_node.next = curr_node.next\n return\n prev_node = curr_node\n curr_node = curr_node.next\n\n def delete_alt(self, data):\n if data is None:\n return\n if self.head is None:\n return\n curr_node = self.head\n if curr_node.data == data:\n curr_node = curr_node.next\n return\n while curr_node.next is not None:\n if curr_node.next.data == data:\n curr_node.next = curr_node.next.next\n return\n curr_node = curr_node.next\n\n def print_list(self):\n curr_node = self.head\n while curr_node is not None:\n print(curr_node.data)\n curr_node = curr_node.next\n\n def get_all_data(self):\n data = []\n curr_node = self.head\n while curr_node is not None:\n data.append(curr_node.data)\n curr_node = curr_node.next\n return data')
# In[2]:
get_ipython().run_line_magic('run', 'linked_list.py')
# ## Unit Test
# In[3]:
get_ipython().run_cell_magic('writefile', 'test_linked_list.py', "import unittest\n\n\nclass TestLinkedList(unittest.TestCase):\n\n def test_insert_to_front(self):\n print('Test: insert_to_front on an empty list')\n linked_list = LinkedList(None)\n linked_list.insert_to_front(10)\n self.assertEqual(linked_list.get_all_data(), [10])\n\n print('Test: insert_to_front on a None')\n linked_list.insert_to_front(None)\n self.assertEqual(linked_list.get_all_data(), [10])\n\n print('Test: insert_to_front general case')\n linked_list.insert_to_front('a')\n linked_list.insert_to_front('bc')\n self.assertEqual(linked_list.get_all_data(), ['bc', 'a', 10])\n\n print('Success: test_insert_to_front\\n')\n\n def test_append(self):\n print('Test: append on an empty list')\n linked_list = LinkedList(None)\n linked_list.append(10)\n self.assertEqual(linked_list.get_all_data(), [10])\n\n print('Test: append a None')\n linked_list.append(None)\n self.assertEqual(linked_list.get_all_data(), [10])\n\n print('Test: append general case')\n linked_list.append('a')\n linked_list.append('bc')\n self.assertEqual(linked_list.get_all_data(), [10, 'a', 'bc'])\n\n print('Success: test_append\\n')\n\n def test_find(self):\n print('Test: find on an empty list')\n linked_list = LinkedList(None)\n node = linked_list.find('a')\n self.assertEqual(node, None)\n\n print('Test: find a None')\n head = Node(10)\n linked_list = LinkedList(head)\n node = linked_list.find(None)\n self.assertEqual(node, None)\n\n print('Test: find general case with matches')\n head = Node(10)\n linked_list = LinkedList(head)\n linked_list.insert_to_front('a')\n linked_list.insert_to_front('bc')\n node = linked_list.find('a')\n self.assertEqual(str(node), 'a')\n\n print('Test: find general case with no matches')\n node = linked_list.find('aaa')\n self.assertEqual(node, None)\n\n print('Success: test_find\\n')\n\n def test_delete(self):\n print('Test: delete on an empty list')\n linked_list = LinkedList(None)\n linked_list.delete('a')\n self.assertEqual(linked_list.get_all_data(), [])\n\n print('Test: delete a None')\n head = Node(10)\n linked_list = LinkedList(head)\n linked_list.delete(None)\n self.assertEqual(linked_list.get_all_data(), [10])\n\n print('Test: delete general case with matches')\n head = Node(10)\n linked_list = LinkedList(head)\n linked_list.insert_to_front('a')\n linked_list.insert_to_front('bc')\n linked_list.delete('a')\n self.assertEqual(linked_list.get_all_data(), ['bc', 10])\n\n print('Test: delete general case with no matches')\n linked_list.delete('aa')\n self.assertEqual(linked_list.get_all_data(), ['bc', 10])\n\n print('Success: test_delete\\n')\n\n def test_len(self):\n print('Test: len on an empty list')\n linked_list = LinkedList(None)\n self.assertEqual(len(linked_list), 0)\n\n print('Test: len general case')\n head = Node(10)\n linked_list = LinkedList(head)\n linked_list.insert_to_front('a')\n linked_list.insert_to_front('bc')\n self.assertEqual(len(linked_list), 3)\n\n print('Success: test_len\\n')\n\n\ndef main():\n test = TestLinkedList()\n test.test_insert_to_front()\n test.test_append()\n test.test_find()\n test.test_delete()\n test.test_len()\n\n\nif __name__ == '__main__':\n main()")
# In[4]:
get_ipython().run_line_magic('run', '-i test_linked_list.py')
|
python
|
#!/usr/bin/env python3
import json
import os
import random
random.seed(27)
from datetime import datetime
import sqlalchemy.ext
import traceback
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
import connexion
import orm
db_session = None
MAX_RETRIES = 1
def get_historic_global_sentiments_inner(
from_ms_ago=86400000, from_created_epoch_ms=1532441907000,
limit=1000, downsample_freq=None, sample_rate=1.0, sentiment_type='all', retry_count=0
):
global db_session
final_dataset = []
delta_ts = datetime.utcnow() - datetime(1970, 1, 1)
utc_now = int((delta_ts.days * 24 * 60 * 60 + delta_ts.seconds) * 1000 + delta_ts.microseconds / 1000.0)
# We'll pick up the most recent starting point
starting_point = max(utc_now - from_ms_ago, from_created_epoch_ms)
if sentiment_type == 'all':
sentiment_types = [
'social_teslamonitor', 'social_external_ensemble',
'news_external_ensemble', 'global_external_ensemble'
]
elif sentiment_type == 'teslamonitor':
sentiment_types = [
'social_teslamonitor',
]
elif sentiment_type == 'external':
sentiment_types = [
'social_external_ensemble', 'news_external_ensemble', 'global_external_ensemble'
]
else:
sentiment_types = [sentiment_type]
sentiment_types_sql = "', '".join(sentiment_types)
try:
if downsample_freq:
sql_query = f"""
SELECT sentiment_type, sentiment_seconds_back,
ROUND(created_at_epoch_ms/(1000*{downsample_freq})) AS bin,
ROUND(AVG(created_at_epoch_ms)) AS created_at_epoch_ms,
AVG(sentiment_absolute) AS sentiment_absolute,
AVG(sentiment_normalized) AS sentiment_normalized,
MIN(created_at_epoch_ms) AS min_created_at_epoch_ms,
MAX(created_at_epoch_ms) AS max_created_at_epoch_ms
FROM analysis_global_sentiment
WHERE created_at_epoch_ms >= {starting_point}
AND sentiment_type IN ('{sentiment_types_sql}')
GROUP BY sentiment_type, sentiment_seconds_back, bin
ORDER BY created_at_epoch_ms DESC
LIMIT {limit}
"""
results = db_session.connection().execute(sql_query)
final_dataset = [
{
'sentiment_type': row[0],
'sentiment_seconds_back': row[1],
'created_at_epoch_ms': row[3],
'sentiment_absolute': float(row[4]) if row[4] is not None else 50.0,
'sentiment_normalized': row[5],
'min_created_at_epoch_ms': row[6],
'max_created_at_epoch_ms': row[7],
} for row in results
]
else:
sql_query = f"""
SELECT sentiment_type, sentiment_seconds_back,
created_at_epoch_ms,
sentiment_absolute,
sentiment_normalized,
created_at_epoch_ms AS min_created_at_epoch_ms,
created_at_epoch_ms AS max_created_at_epoch_ms
FROM analysis_global_sentiment
WHERE created_at_epoch_ms >= {starting_point}
AND sentiment_type IN ('{sentiment_types_sql}')
ORDER BY created_at_epoch_ms DESC
"""
# The sampling is not random, we try to make the sample points equidistant in terms of points in the between.
if sample_rate < 1:
initial_results = db_session.connection().execute(sql_query)
# pick_up_rate = (1/sample_rate).as_integer_ratio()
# skip_rate = int(sample_rate * 10000)
dataset = [(i, row) for i, row in enumerate(initial_results)]
pre_limit_dataset = random.sample(dataset, int(sample_rate*len(dataset)))
# pre_limit_dataset = [p for i, p in enumerate(dataset) if (i % 10000) < skip_rate]
results = [
row for _, row in sorted(pre_limit_dataset[:limit], key=lambda tup: tup[0])
]
else:
sql_query = f'''
{sql_query}
LIMIT {limit}
'''
results = db_session.connection().execute(sql_query)
final_dataset = [
{
'sentiment_type': row[0],
'sentiment_seconds_back': row[1],
'created_at_epoch_ms': row[2],
'sentiment_absolute': float(row[3]),
'sentiment_normalized': row[4],
'min_created_at_epoch_ms': row[5],
'max_created_at_epoch_ms': row[6],
} for row in results
]
db_session.commit()
except sqlalchemy.exc.OperationalError:
db_session.rollback()
db_session.remove()
logger.warning(f'Recreating session because of issue with previous session: {traceback.format_exc()}')
# Restore the session and retry.
session_reconnect()
if retry_count < MAX_RETRIES:
final_dataset = get_historic_global_sentiments_inner(
from_ms_ago, from_created_epoch_ms, limit, sample_rate, sentiment_type, retry_count+1
)
else:
raise
except:
db_session.rollback()
logger.error(f'An error occurred when managing the query for retrieving global sentiment: {traceback.format_exc()}')
raise
if len(final_dataset) > 0:
logger.info(f"Most recent max_created_at_epoch_ms: {final_dataset[0]['max_created_at_epoch_ms']}. sentiment_absolute: {final_dataset[0]['sentiment_absolute']}")
return final_dataset
def get_historic_global_sentiments(
from_ms_ago=86400000, from_created_epoch_ms=1532441907000,
limit=1000, downsample_freq=None, sample_rate=1.0, sentiment_type='all'
):
return get_historic_global_sentiments_inner(from_ms_ago, from_created_epoch_ms, limit, downsample_freq, sample_rate, sentiment_type)
def session_reconnect():
global db_session
db_session = orm.init_db(ssh, db_host, db_name, db_user, db_password, db_port, ssh_username, ssh_password, 'utf8mb4')
db_host = os.getenv('AUTOMLPREDICTOR_DB_SERVER_IP', '127.0.0.1')
db_user = os.getenv('AUTOMLPREDICTOR_DB_SQL_USER', 'root')
db_password = os.getenv('AUTOMLPREDICTOR_DB_SQL_PASSWORD')
db_name = os.getenv('AUTOMLPREDICTOR_DB_NAME', 'automlpredictor_db_dashboard')
db_port = os.getenv('AUTOMLPREDICTOR_DB_PORT', 3306)
ssh_username = os.getenv('AUTOMLPREDICTOR_DB_SSH_USER', None)
ssh_password = os.getenv('AUTOMLPREDICTOR_DB_SSH_PASSWORD')
ssh = ssh_username is not None
session_reconnect()
app = connexion.FlaskApp(__name__)
app.add_api('swagger.yaml')
application = app.app
@application.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == '__main__':
app.run(port=8080)
|
python
|
#!/usr/bin/env python2
"""Create GO-Dag plots."""
__copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import sys
sys.path.append("/dfs/scratch2/caruiz/code/goatools/")
from goatools.cli.gosubdag_plot import PlotCli
def run():
"""Create GO-Dag plots."""
PlotCli().cli()
if __name__ == '__main__':
run()
# Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved.
|
python
|
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='uwkm_streamfields',
packages=['uwkm_streamfields'],
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.4.0',
description='Wagtail Bootstrap Streamfields',
long_description=long_description,
# The project's main homepage.
url='https://github.com/UWKM/uwkm_streamfields/',
branch_url='https://github.com/UWKM/uwkm_streamfields/tree/master',
download_url='https://github.com/UWKM/uwkm_streamfields/archive/master.zip',
# Author details
author='UWKM',
author_email='[email protected]',
# Choose your license
license='MIT',
include_package_data=True,
zip_safe=False,
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[],
# What does your project relate to?
keywords='wagtail cms streamfields bootstrap uwkm',
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[
],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
extras_require={
'dev': [],
'test': [],
},
)
|
python
|
import pytest
from . import constants
from pybible import pybible_load
from pybible.classes.bible import Bible
from pybible.classes.bible_without_apocrypha import BibleWithoutApocrypha
from pybible.classes.book import Book
from pybible.classes.chapter import Chapter
from pybible.classes.verse import Verse
@pytest.fixture
def bible():
return pybible_load.load()
def test_init(bible):
assert isinstance(eval(repr(bible)), Bible)
def test_len(bible):
assert len(bible) == constants.BIBLE_SIZE_TEST
def test_str(bible):
assert str(bible) == constants.BIBLE_NAME_TEST
def test_index_book_by_position(bible):
book = bible[constants.POS_TEST]
assert isinstance(book, Book)
assert str(book) == constants.BOOK_NAME_TEST
def test_index_book_by_position_error(bible):
with pytest.raises(SystemExit):
return bible[constants.POS_TEST_ERROR]
def test_index_book_by_name(bible):
book = bible[constants.BOOK_KEY_TEST]
assert isinstance(book, Book)
assert str(book) == constants.BOOK_NAME_TEST
def test_index_book_by_name_error(bible):
with pytest.raises(SystemExit):
return bible[constants.BOOK_KEY_TEST_ERROR]
def test_ot(bible):
ot = bible.ot()
assert len(ot) == constants.OT_SIZE_TEST
assert ot[constants.FIRST_POSITION].title == constants.OT_FIRST_BOOK_TITLE_TEST
assert ot[constants.LAST_POSITION].title == constants.OT_LAST_BOOK_TITLE_TEST
def test_nt(bible):
nt = bible.nt()
assert len(nt) == constants.NT_SIZE_TEST
assert nt[constants.FIRST_POSITION].title == constants.NT_FIRST_BOOK_TITLE_TEST
assert nt[constants.LAST_POSITION].title == constants.NT_LAST_BOOK_TITLE_TEST
def test_books_names(bible):
assert len(bible.books_names) == constants.BIBLE_SIZE_TEST
|
python
|
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.http import JsonResponse, HttpResponse
from .models import User, Photo, Followers
from .forms import *
from django.contrib.auth import authenticate, login, logout as dlogout
import json
def ajaxsignup(request):
ajax = AjaxSignUp(request.POST)
context = {'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxsavephoto(request):
ajax = AjaxSavePhoto(request.POST, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxlikephoto(request):
ajax = AjaxLikePhoto(request.GET, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxtag(request):
ajax = AjaxTagPhoto(request.GET, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxfollow(request):
ajax = AjaxFollow(request.GET, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxsetprofilepic(request):
ajax = AjaxSetProfilePic(request.POST, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxphotofeed(request):
ajax = AjaxPhotoFeed(request.GET, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxprofilefeed(request):
ajax = AjaxProfileFeed(request.GET, request.user)
context = { 'ajax_output': ajax.output() }
return render(request, 'ajax.html', context)
def ajaxlogin(request):
ajax = AjaxLogin(request.POST)
logged_in_user, output = ajax.validate()
if logged_in_user != None:
login(request, logged_in_user)
context = {'ajax_output': output}
return render(request, 'ajax.html', context)
def signup(request):
context = {}
return render(request, 'sign-up.html', context)
def home(request):
context = {}
if request.user.is_authenticated:
u = User.objects.filter(username=request.user.username)[0]
if u.profilepic == "":
u.profilepic = "static/assets/img/default.png"
url_parameter = request.GET.get("q")
if url_parameter:
users = User.objects.filter(username__icontains=url_parameter)
else:
users = ''
context["users"] = users
if request.is_ajax():
html = render_to_string(
template_name="users-search-result.html", context={"users": users}
)
data_dict = {"html_from_view": html}
return JsonResponse(data=data_dict, safe=False)
context = { 'user': request.user, 'ProfilePic': u.profilepic}
return render(request, 'logged-in-index.html', context)
return render(request, 'index.html', context)
def profile(request, username):
if User.objects.filter(username=username).exists():
u = User.objects.filter(username=username)[0]
if not Followers.objects.filter(user=username, follower=request.user.username).exists():
following = "Follow"
else:
following = "Unfollow"
if u.profilepic == "":
u.profilepic = "static/assets/img/default.png"
context = { "ProfilePic": u.profilepic, "whosprofile": username, "logged_in_as": request.user.username, "following": following }
if request.user.is_authenticated:
return render(request, 'logged-in-profile.html', context)
return render(request, 'profile.html', context)
else:
return redirect(home)
def search(request):
if request.method == 'GET':
search = request.GET['search']
return redirect("/"+search)
# users = User.objects.all()
# return JsonResponse({'users':users})
def upload(request):
form = UploadForm()
print(form.media)
return render(request, 'upload.html', { 'form': form })
def logout(request):
context = {}
dlogout(request)
return redirect(home)
|
python
|
import numpy
from scipy.spatial import distance
import matplotlib.pyplot as plt
# wspolczynnik uczenia
eta = 0.1
# momentum
alfa = 0
class NeuralNetwork:
def __repr__(self):
return "Instance of NeuralNetwork"
def __str__(self):
# todo: zaktualizuj to_string()
if self.is_bias:
return "hidden_layer (wiersze - neurony) :\n" + str(
self.hidden_layer) + "\noutput_layer (wiersze - neurony) :\n" + str(
self.output_layer) + "\nbiashiddenlayer\n" + str(
self.bias_hidden_layer) + "\nbiasoutputlayer\n" + str(self.bias_output_layer)
return "hidden_layer (wiersze - neurony) :\n" + str(
self.hidden_layer) + "\noutput_layer (wiersze - neurony) :\n" + str(self.output_layer)
def __init__(self, number_of_neurons_hidden_layer, number_of_neurons_output, is_bias, input_data, expected_outputs):
# czy uruchomilismy bias, bias aktualnie nie jest zaimplementowany dla warstwy radialnej
self.is_bias = is_bias
# dane wejsciowe
self.input_data = input_data
self.expected_outputs = expected_outputs
# Pozycja centrów ma być losowana z wektórów wejściowych
# Laczymy dane wejsciowe i expected outputs żeby móc je razem przelosować i zachować łączność danych
input_data_random_order = numpy.vstack((self.input_data, self.expected_outputs)).T
numpy.random.shuffle(input_data_random_order)
# wtworzymy wagi dla warstwy wejsciowej, najpierw tworzymy macierz o jakim chcemy rozmiarze
self.hidden_layer = numpy.zeros((len(input_data_random_order[0, :-1]), number_of_neurons_hidden_layer)).T
# ustawiamy n neuronom ich centra jako n pierwszych danych wejściowych (po przelosowaniu danych wejsciowych)
for i in range(numpy.size(self.hidden_layer, 0)):
self.hidden_layer[i] = input_data_random_order[i, :-1]
# print(self.hidden_layer)
# Ustawiamy sigmy początkowo na 1
self.scale_coefficient = numpy.ones(numpy.size(self.hidden_layer, 0))
# Szukamy sigm ze wzoru
self.find_sigma()
# print(self.scale_coefficient)
# delty dla momentum, aktualnie nie uczymy wsteczną propagacją warstwy ukrytej więc nie używamy
self.delta_weights_hidden_layer = numpy.zeros((len(input_data_random_order[0]),
number_of_neurons_hidden_layer)).T
# tworzymy warstwę wyjściową z losowymi wagami od -1 do 1, jak w zad 1
self.output_layer = 2 * numpy.random.random((number_of_neurons_hidden_layer, number_of_neurons_output)).T - 1
# print(self.output_layer)
self.delta_weights_output_layer = numpy.zeros((number_of_neurons_hidden_layer, number_of_neurons_output)).T
# jesli wybralismy że bias ma byc to tworzymy dla każdej warstwy wektor wag biasu
if is_bias:
self.bias_hidden_layer = (2 * numpy.random.random(number_of_neurons_hidden_layer) - 1)
self.bias_output_layer = (2 * numpy.random.random(number_of_neurons_output) - 1)
# jesli nie ma byc biasu to tworzymy takie same warstwy ale zer. Nie ingerują one potem w obliczenia w żaden sposób
else:
self.bias_hidden_layer = numpy.zeros(number_of_neurons_hidden_layer)
self.bias_output_layer = numpy.zeros(number_of_neurons_output)
# taka sama warstwa delty jak dla layerów
self.bias_output_layer_delta = numpy.zeros(number_of_neurons_output)
self.bias_hidden_layer_delta = numpy.zeros(number_of_neurons_hidden_layer)
# szukamy sigm ze wzorów dla każdego neuronu radialnego
def find_sigma(self):
for i in range(numpy.size(self.hidden_layer, 0)):
max_dist = 0
for j in range(numpy.size(self.hidden_layer, 0)):
dist = distance.euclidean(self.hidden_layer[i], self.hidden_layer[j])
if dist > max_dist:
max_dist = dist
self.scale_coefficient[i] = \
max_dist / (numpy.sqrt(2 * numpy.size(self.hidden_layer, 0)))
# najpierw liczymy wynik z warstwy ukrytej i potem korzystając z niego liczymy wynik dla neuronów wyjścia
# Jak wiadomo bias to przesunięcie wyniku o stałą więc jeżeli wybraliśmy
# że bias istnieje to on jest po prostu dodawany do odpowiedniego wyniku iloczynu skalarnego
# bias istnieje tylko dla output layer aktualnie
def calculate_outputs(self, inputs):
hidden_layer_output = []
for i in range(numpy.size(self.hidden_layer, 0)):
# ze wzoru, prezentacja 6, koło 20 strony, wynik dla warstwy radialnej
dist = (distance.euclidean(self.hidden_layer[i], inputs) ** 2)
denominator = 2 * (self.scale_coefficient[i] ** 2)
value = numpy.exp(-1 * (dist / denominator))
hidden_layer_output.append(value)
# wynik dla warstwy wyjsciowej
output_layer_output = numpy.dot(hidden_layer_output, self.output_layer.T) + self.bias_output_layer
return hidden_layer_output, output_layer_output
# trening, tyle razy ile podamy epochów
# dla każdego epochu shufflujemy nasze macierze i przechodzimy przez nie po każdym wierszu z osobna
def train(self, epoch_count):
error_list = []
for it in range(epoch_count):
# Shuffle once each iteration
joined_arrays = numpy.vstack((self.input_data, self.expected_outputs)).T
numpy.random.shuffle(joined_arrays)
joined_arrays_left, joined_arrays_right = numpy.hsplit(joined_arrays, 2)
mean_squared_error = 0
ite = 0
for k, j in zip(joined_arrays_left, joined_arrays_right):
ite += 1
# epoka zwraca błąd
mean_squared_error += self.epoch(k, j)
mean_squared_error = mean_squared_error / ite
error_list.append(mean_squared_error)
print("OSTATNI BLAD", error_list[-1])
# po przejściu przez wszystkie epoki zapisujemy błędy średniokwadratowe do pliku
# with open("mean_squared_error.txt", "w") as file:
with open("mean_squared_error.txt", "w") as file:
for i in error_list:
file.write(str(i) + "\n")
def epoch(self, k, j):
join_k_j = numpy.concatenate((k, j), axis=None)
# print(join_k_j)
hidden_layer_output, output_layer_output = self.calculate_outputs(k)
# błąd dla wyjścia to różnica pomiędzy oczekiwanym wynikiem a otrzymanym
output_error = output_layer_output - j
mean_squared_error = output_error.dot(output_error) / 2
# output_delta - współczynnik zmiany wagi dla warstwy wyjściowej. Otrzymujemy jeden współczynnik dla każdego neronu.
# aby potem wyznaczyć zmianę wag przemnażamy go przez input odpowiadający wadze neuronu
# Pochodna funkcji liniowej = 1
output_delta = output_error * 1
output_layer_adjustment = []
for i in output_delta:
value = [i * j for j in hidden_layer_output]
output_layer_adjustment.append(value)
output_layer_adjustment = numpy.asarray(output_layer_adjustment)
# jeżeli wybraliśmy żeby istniał bias to teraz go modyfikujemy
if self.is_bias:
output_bias_adjustment = eta * output_delta + alfa * self.bias_output_layer_delta
self.bias_output_layer -= output_bias_adjustment
self.bias_output_layer_delta = output_bias_adjustment
output_layer_adjustment = eta * output_layer_adjustment + alfa * self.delta_weights_output_layer
# modyfikujemy wagi w warstwach
self.output_layer -= output_layer_adjustment
# zapisujemy zmianę wag by użyć ją w momentum
self.delta_weights_output_layer = output_layer_adjustment
return mean_squared_error
# otwieramy plik errorów i go plotujemy
def plot_file():
with open("mean_squared_error.txt", "r") as file:
lines = file.read().splitlines()
values = []
for i in lines:
values.append(float(i))
plt.plot(values, markersize=1)
plt.xlabel('Epoch')
plt.ylabel('Error for epoch')
plt.title("Mean square error change")
plt.show()
def plot_function(siec, title, neurons, points=None):
if points is not None:
values = read_2d_float_array_from_file(points)
values2 = numpy.zeros_like(values)
indexes = numpy.argsort(values[:, 0])
for i in range(len(indexes)):
values2[i] = values[indexes[i]]
points = values2
values = []
plt.plot(points[:, 0], points[:, 1], label="original function")
points = points[:, 0]
for i in points:
values.append(siec.calculate_outputs(i)[1][0])
plt.plot(points, values, 'o', markersize=1, label="aproximation")
plt.xlabel('X')
plt.ylabel('Y')
plt.title("File: " + title[:-4] + ", neuron count = " + str(neurons))
plt.legend()
plt.tight_layout()
plt.show()
# funkcja zwraca 2d array floatów w postaci arraya z paczki numpy.
def read_2d_float_array_from_file(file_name):
two_dim_list_of_return_values = []
with open(file_name, "r") as file:
lines = file.read().splitlines()
for i in lines:
one_dim_list = []
for j in list(map(float, i.split())):
one_dim_list.append(j)
two_dim_list_of_return_values.append(one_dim_list)
return numpy.asarray(two_dim_list_of_return_values)
def main():
numpy.random.seed(0)
neurons = 7
train_file = "approximation_train_1.txt"
test_file = "approximation_test.txt"
# ilość neuronów, ilość wyjść, ilość wejść, czy_bias
siec = NeuralNetwork(neurons, 1, False, read_2d_float_array_from_file(train_file)[:, 0],
read_2d_float_array_from_file(train_file)[:, 1])
iterations = 100
# dane wejściowe, dane wyjściowe, ilość epochów
siec.train(iterations)
plot_file()
plot_function(siec, train_file, neurons, test_file)
if __name__ == "__main__":
main()
|
python
|
import torch
import matplotlib.pyplot as plt
from torchsummary import summary
import yaml
from pprint import pprint
import random
import numpy as np
import torch.nn as nn
from torchvision import datasets, transforms
from itertools import product
def imshow(img):
# functions to show an image
fig, ax = plt.subplots(figsize=(12, 12))
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
def unnormalize(img):
mean = (0.49139968, 0.48215841, 0.44653091)
std = (0.24703223, 0.24348513, 0.26158784)
# mean,std = calculate_mean_std("CIFAR")
img = img.cpu().numpy().astype(dtype=np.float32)
for i in range(img.shape[0]):
img[i] = (img[i]*std[i])+mean[i]
return np.transpose(img, (1,2,0))
def calculate_mean_std(dataset):
if dataset == 'CIFAR10':
train_transform = transforms.Compose([transforms.ToTensor()])
train_set = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
mean = train_set.data.mean(axis=(0,1,2))/255
std = train_set.data.std(axis=(0,1,2))/255
return mean, std
def set_seed(seed,cuda_available):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if cuda_available:
torch.cuda.manual_seed(seed)
def process_config(file_name):
with open(file_name, 'r') as config_file:
try:
config = yaml.safe_load(config_file)
print(" loading Configuration of your experiment ..")
return config
except ValueError:
print("INVALID yaml file format.. Please provide a good yaml file")
exit(-1)
def model_summary(model, input_size):
result = summary(model, input_size=input_size)
print(result)
def class_level_accuracy(model, loader, device, classes):
class_correct = list(0. for i in range(len(classes)))
class_total = list(0. for i in range(len(classes)))
with torch.no_grad():
for _, (images, labels) in enumerate(loader, 0):
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(len(labels)):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))
def compute_confusion_matrix(model, data_loader, device):
all_targets, all_predictions = [], []
with torch.no_grad():
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets
logits = model(features)
_, predicted_labels = torch.max(logits, 1)
all_targets.extend(targets.to('cpu'))
all_predictions.extend(predicted_labels.to('cpu'))
all_predictions = all_predictions
all_predictions = np.array(all_predictions)
all_targets = np.array(all_targets)
class_labels = np.unique(np.concatenate((all_targets, all_predictions)))
if class_labels.shape[0] == 1:
if class_labels[0] != 0:
class_labels = np.array([0, class_labels[0]])
else:
class_labels = np.array([class_labels[0], 1])
n_labels = class_labels.shape[0]
lst = []
z = list(zip(all_targets, all_predictions))
for combi in product(class_labels, repeat=2):
lst.append(z.count(combi))
mat = np.asarray(lst)[:, None].reshape(n_labels, n_labels)
return mat
|
python
|
from models.mlm_wrapper import MLMWrapper
from transformers import BertForMaskedLM, BertTokenizer
class BertWrapper(MLMWrapper):
def __init__(self, tokenizer: BertTokenizer, model: BertForMaskedLM, device: int = None):
super().__init__(tokenizer, model, device=device)
|
python
|
import csv
import clueUtils
import guess
suspects = clueUtils.suspects
weapons = clueUtils.weapons
rooms = clueUtils.rooms
allCards = clueUtils.allCards
playerNames = clueUtils.playerNames
numPlayers = clueUtils.numPlayers
numSuspects = clueUtils.numSuspects
numWeapons = clueUtils.numWeapons
numRooms = clueUtils.numRooms
numCards = clueUtils.numCards
numPlayerCards = clueUtils.numPlayerCards
mysteryIndex = numPlayers
epsilon = 0.0001
class clueGrid:
def __init__(self):
self.grid = []
for i in range(numSuspects):
suspectRow = []
for j in range(numPlayers):
suspectRow.append(numPlayerCards[j]/numCards)
suspectRow.append(1/numSuspects)
self.grid.append(suspectRow)
for i in range(numWeapons):
weaponRow = []
for j in range(numPlayers):
weaponRow.append(numPlayerCards[j]/numCards)
weaponRow.append(1/numWeapons)
self.grid.append(weaponRow)
for i in range(numRooms):
roomRow = []
for j in range(numPlayers):
roomRow.append(numPlayerCards[j]/numCards)
roomRow.append(1/numRooms)
self.grid.append(roomRow)
def at(self, card, playerName):
cardIndex = clueUtils.allCards.index(card)
if playerName == "mystery":
playerIndex = mysteryIndex
else:
playerIndex = clueUtils.playerNames.index(playerName)
return self.grid[cardIndex][playerIndex]
def show(self, playerName, card):
cardIndex = clueUtils.allCards.index(card)
playerIndex = clueUtils.playerNames.index(playerName)
self.grid[cardIndex][playerIndex] = 1
def playerPassed(self, playerName, theGuess):
playerIndex = clueUtils.playerNames.index(playerName)
cards = theGuess.cardList()
for card in cards:
cardIndex = allCards.index(card)
self.grid[cardIndex][playerIndex] = 0
def readGuessLog(self):
with open("public/guessLog.csv") as csvfile:
csvReader = csv.reader(csvfile)
header = True
for row in csvReader:
if header:
#do nothing
header = False
else:
#print(row)
self.processGuessLogRow(row)
def readPrivateLog(self, filename):
with open(filename) as csvfile:
csvReader = csv.reader(csvfile)
for row in csvReader:
self.processPrivateLogRow(row)
def processPrivateLogRow(self, row):
playerName = row[0]
card = row[1]
playerIndex = clueUtils.playerNames.index(playerName)
cardIndex = clueUtils.allCards.index(card)
self.grid[cardIndex][playerIndex] = 1
self.updateCardProbability(cardIndex)
def processGuessLogRow(self, row):
suspect = row[0]
weapon = row[1]
room = row[2]
suspectIndex = clueUtils.allCards.index(suspect)
weaponIndex = clueUtils.allCards.index(weapon)
roomIndex = clueUtils.allCards.index(room)
playerResponses = []
for playerIndex in range(clueUtils.numPlayers):
colIndex = playerIndex + 3
playerResponse = row[colIndex]
playerResponses.append(playerResponse)
if playerResponse == "passed":
self.grid[suspectIndex][playerIndex] = 0
self.grid[weaponIndex][playerIndex] = 0
self.grid[roomIndex][playerIndex] = 0
elif playerResponse == "showed":
if (self.grid[suspectIndex][playerIndex] == 0) and (self.grid[weaponIndex][playerIndex] == 0):
self.grid[roomIndex][playerIndex] = 1
elif (self.grid[suspectIndex][playerIndex] == 0) and (self.grid[roomIndex][playerIndex] == 0):
self.grid[weaponIndex][playerIndex] = 1
elif (self.grid[weaponIndex][playerIndex] == 0) and (self.grid[roomIndex][playerIndex] == 0):
self.grid[suspectIndex][playerIndex] = 1
def updateCardProbability(self, cardIndex):
# Return False unless something is changed
changedSomething = False
# Set all other probabilities to zero if owner is known
for playerIndex in range(numPlayers + 1):
value = self.grid[cardIndex][playerIndex]
if value == 1:
for i in range(numPlayers + 1):
if (i != playerIndex) and (self.grid[cardIndex][i] != 0):
self.grid[cardIndex][i] = 0
changedSomething = True
return changedSomething
# Sum probabilities
sumOfProbabilities = 0
for playerIndex in range(numPlayers + 1):
value = self.grid[cardIndex][playerIndex]
sumOfProbabilities = sumOfProbabilities + value
# Check for invalid condition
if sumOfProbabilities == 0:
print("Error: Zero probability for %s" % (clueUtils.allCards[cardIndex]))
return changedSomething
# Update probabilities so all nonzero probabilities add up to one
for playerIndex in range(numPlayers + 1):
value = self.grid[cardIndex][playerIndex]
newValue = value/sumOfProbabilities
if ((newValue - value) >= 0.0001):
self.grid[cardIndex][playerIndex] = newValue
changedSomething = True
return changedSomething
def updateCardProbabilities(self):
loopCount = 0
while True:
changeCount = 0
loopCount = loopCount + 1
changeCount = changeCount + self.ifAllPlayerCardsKnownPlayerDoesNotHaveAnyOtherCards()
changeCount = changeCount + self.ifSuspectKnownElimateAllOtherCandidates()
changeCount = changeCount + self.ifWeaponKnownElimateAllOtherCandidates()
changeCount = changeCount + self.ifRoomKnownElimateAllOtherCandidates()
for cardIndex in range(clueUtils.numCards):
changedSomething = self.updateCardProbability(cardIndex)
if changedSomething == True:
changeCount = changeCount + 1
if changeCount == 0:
break
if loopCount >= 100:
break
return loopCount
def knownPlayerCards(self, playerName):
knownHand = []
for card in allCards:
if self.at(card, playerName) == 1:
knownHand.append(card)
return knownHand
def ifAllPlayerCardsKnownPlayerDoesNotHaveAnyOtherCards(self):
changeCount = 0
for playerName in playerNames:
playerIndex = playerNames.index(playerName)
knownCardsInPlayerHand = self.knownPlayerCards(playerName)
if len(knownCardsInPlayerHand) == numPlayerCards[playerIndex]:
for card in allCards:
cardIndex = allCards.index(card)
if (self.grid[cardIndex][playerIndex] != 1) and (self.grid[cardIndex][playerIndex] != 0):
self.grid[cardIndex][playerIndex] = 0
changeCount = changeCount + 1
return changeCount
def ifSuspectKnownElimateAllOtherCandidates(self):
changeCount = 0
candidateSuspects = self.suspectCandidates()
for card in candidateSuspects:
cardIndex = allCards.index(card)
if self.grid[cardIndex][mysteryIndex] == 1:
for cardToZero in candidateSuspects:
if cardToZero != card:
cardToZeroIndex = allCards.index(cardToZero)
if (self.grid[cardToZeroIndex][mysteryIndex] != 0):
self.grid[cardToZeroIndex][mysteryIndex] = 0
changeCount = changeCount + 1
return changeCount
def ifWeaponKnownElimateAllOtherCandidates(self):
changeCount = 0
candidateWeapons = self.weaponCandidates()
for card in candidateWeapons:
cardIndex = allCards.index(card)
if self.grid[cardIndex][mysteryIndex] == 1:
for cardToZero in candidateWeapons:
if cardToZero != card:
cardToZeroIndex = allCards.index(cardToZero)
if (self.grid[cardToZeroIndex][mysteryIndex] != 0):
self.grid[cardToZeroIndex][mysteryIndex] = 0
changeCount = changeCount + 1
return changeCount
def ifRoomKnownElimateAllOtherCandidates(self):
changeCount = 0
candidateRooms = self.roomCandidates()
for card in candidateRooms:
cardIndex = allCards.index(card)
if self.grid[cardIndex][mysteryIndex] == 1:
for cardToZero in candidateRooms:
if cardToZero != card:
cardToZeroIndex = allCards.index(cardToZero)
if (self.grid[cardToZeroIndex][mysteryIndex] != 0):
self.grid[cardToZeroIndex][mysteryIndex] = 0
changeCount = changeCount + 1
return changeCount
def display(self):
for i in range(len(self.grid)):
for j in range(len(self.grid[0])):
print("%8.2f" % (self.grid[i][j]), end='')
print("\n")
def displayPretty(self):
print("Suspects: %d candidate(s) %s" % (self.numSuspectCandidates(), self.suspectCandidates()))
for card in suspects:
for playerName in clueUtils.playerNames:
print("%8.2f" % (self.at(card, playerName)), end='')
print("%8.2f\t%s\n" % (self.at(card, "mystery"), card))
print("Weapons: %d candidate(s) %s" % (self.numWeaponCandidates(), self.weaponCandidates()))
for card in weapons:
for playerName in clueUtils.playerNames:
print("%8.2f" % (self.at(card, playerName)), end='')
print("%8.2f\t%s\n" % (self.at(card, "mystery"), card))
print("Rooms: %d candidate(s) %s" % (self.numRoomCandidates(), self.roomCandidates()))
for card in rooms:
for playerName in clueUtils.playerNames:
print("%8.2f" % (self.at(card, playerName)), end='')
print("%8.2f\t%s\n" % (self.at(card, "mystery"), card))
def suspectCandidates(self):
candidates = []
for card in clueUtils.suspects:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
candidates.append(card)
return candidates
def weaponCandidates(self):
candidates = []
for card in clueUtils.weapons:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
candidates.append(card)
return candidates
def roomCandidates(self):
candidates = []
for card in clueUtils.rooms:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
candidates.append(card)
return candidates
def numCandidates(self):
numCandidates = 0
for card in allCards:
cardIndex = allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
numCandidates = numCandidates + 1
return numCandidates
def numSuspectCandidates(self):
numCandidates = 0
for card in clueUtils.suspects:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
numCandidates = numCandidates + 1
return numCandidates
def numWeaponCandidates(self):
numCandidates = 0
for card in clueUtils.weapons:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
numCandidates = numCandidates + 1
return numCandidates
def numRoomCandidates(self):
numCandidates = 0
for card in clueUtils.rooms:
cardIndex = clueUtils.allCards.index(card)
if (self.grid[cardIndex][mysteryIndex] >= epsilon):
numCandidates = numCandidates + 1
return numCandidates
def displayCandidates(self):
for card in allCards:
print("%8.2f %s\n" % (self.at(card,"mystery"), card))
#Test code
if __name__ == "__main__":
myTestGrid = clueGrid()
myTestGrid.display()
myTestGrid.readGuessLog()
loopCount = myTestGrid.updateCardProbabilities()
print("Loop Count: %d" % (loopCount))
myTestGrid.displayPretty()
# print(clueUtils.numPlayerCards)
|
python
|
# This file is part of the scanning-squid package.
#
# Copyright (c) 2018 Logan Bishop-Van Horn
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os
import numpy as np
from typing import Dict, List, Optional, Sequence, Any, Union, Tuple, Callable
import qcodes as qc
from qcodes.instrument.parameter import ArrayParameter
from scipy import io
from collections import OrderedDict
import json
#: Tell the UnitRegistry what a Phi0 is, and that ohm and Ohm are the same thing.
with open('squid_units.txt', 'w') as f:
f.write('Phi0 = 2.067833831e-15 * Wb\n')
f.write('Ohm = ohm\n')
class Counter(object):
"""Simple counter used to keep track of progress in a Loop.
"""
def __init__(self):
self.count = 0
def advance(self):
self.count += 1
def load_json_ordered(filename: str) -> OrderedDict:
"""Loads json file as an ordered dict.
Args:
filename: Path to json file to be loaded.
Returns:
OrderedDict: odict
OrderedDict containing data from json file.
"""
with open(filename) as f:
odict = json.load(f, object_pairs_hook=OrderedDict)
return odict
def next_file_name(fpath: str, extension: str) -> str:
"""Appends an integer to fpath to create a unique file name:
fpath + {next unused integer} + '.' + extension
Args:
fpath: Path to file you want to create (no extension).
extension: Extension of file you want to create.
Returns:
str: next_file_name
Unique file name starting with fpath and ending with extension.
"""
i = 0
while os.path.exists('{}{}.{}'.format(fpath, i, extension)):
i += 1
return '{}{}.{}'.format(fpath, i, extension)
def make_scan_vectors(scan_params: Dict[str, Any], ureg: Any) -> Dict[str, Sequence[float]]:
"""Creates x and y vectors for given scan parameters.
Args:
scan_params: Scan parameter dict
ureg: pint UnitRegistry, manages units.
Returns:
Dict: scan_vectors
{axis_name: axis_vector} for x, y axes.
"""
Q_ = ureg.Quantity
center = []
size = []
rng = []
for ax in ['x', 'y']:
center.append(Q_(scan_params['center'][ax]).to('V').magnitude)
size.append(scan_params['scan_size'][ax])
rng.append(Q_(scan_params['range'][ax]).to('V').magnitude)
x = np.linspace(center[0] - 0.5 * rng[0], center[0] + 0.5 * rng[0], size[0])
y = np.linspace(center[1] - 0.5 * rng[1], center[1] + 0.5 * rng[1], size[1])
return {'x': x, 'y': y}
def make_scan_grids(scan_vectors: Dict[str, Sequence[float]], slow_ax: str,
fast_ax: str, fast_ax_pts: int, plane: Dict[str, float],
height: float) -> Dict[str, Any]:
"""Makes meshgrids of scanner positions to write to DAQ analog outputs.
Args:
scan_vectors: Dict of {axis_name: axis_vector} for x, y axes (from make_scan_vectors).
slow_ax: Name of the scan slow axis ('x' or 'y').
fast_ax: Name of the scan fast axis ('x' or 'y').
fast_ax_pts: Number of points to write to DAQ analog outputs to scan fast axis.
plane: Dict of x, y, z values defining the plane to scan (provided by scanner.get_plane).
height: Height above the sample surface (in DAQ voltage) at which to scan.
More negative means further from sample; 0 means 'in contact'.
Returns:
Dict: scan_grids
{axis_name: axis_scan_grid} for x, y, z, axes.
"""
slow_ax_vec = scan_vectors[slow_ax]
fast_ax_vec = np.linspace(scan_vectors[fast_ax][0],
scan_vectors[fast_ax][-1],
fast_ax_pts)
if fast_ax == 'y':
X, Y = np.meshgrid(slow_ax_vec, fast_ax_vec, indexing='ij')
else:
X, Y = np.meshgrid(fast_ax_vec, slow_ax_vec, indexing='xy')
Z = X * plane['x'] + Y * plane['y'] + plane['z'] + height
return {'x': X, 'y': Y, 'z': Z}
def make_scan_surface(surface_type: str, scan_vectors: Dict[str, Sequence[float]], slow_ax: str,
fast_ax: str, fast_ax_pts: int, plane: Dict[str, float], height: float,
interpolator: Optional[Callable]=None):
"""Makes meshgrids of scanner positions to write to DAQ analog outputs.
Args:
surface_type: Either 'plane' or 'surface'.
scan_vectors: Dict of {axis_name: axis_vector} for x, y axes (from make_scan_vectors).
slow_ax: Name of the scan slow axis ('x' or 'y').
fast_ax: Name of the scan fast axis ('x' or 'y').
fast_ax_pts: Number of points to write to DAQ analog outputs to scan fast axis.
plane: Dict of x, y, z values defining the plane to scan (provided by scanner.get_plane).
height: Height above the sample surface (in DAQ voltage) at which to scan.
More negative means further from sample; 0 means 'in contact'.
interpolator: Instance of scipy.interpolate.Rbf used to interpolate touchdown points.
Only required if surface_type == 'surface'. Default: None.
Returns:
Dict: scan_grids
{axis_name: axis_scan_grid} for x, y, z, axes.
"""
if surface_type.lower() not in ['plane', 'surface']:
raise ValueError('surface_type must be "plane" or "surface".')
plane_grids = make_scan_grids(scan_vectors, slow_ax, fast_ax, fast_ax_pts, plane, height)
if surface_type.lower() == 'plane':
return plane_grids
else:
if interpolator is None:
msg = 'surface_type == "surface", so you must specify an instance of scipy.interpolate.Rbf'
msg += '(namely microscope.scanner.surface_interp).'
raise ValueError(msg)
Z = interpolator(plane_grids['x'], plane_grids['y'])
surface_grids = {'x': plane_grids['x'], 'y': plane_grids['y'], 'z': Z + height}
return surface_grids
def make_xy_grids(scan_vectors: Dict[str, Sequence[float]], slow_ax: str,
fast_ax: str) -> Dict[str, Any]:
"""Makes meshgrids from x, y scan_vectors (used for plotting, etc.).
Args:
scan_vectors: Dict of {axis_name: axis_vector} for x, y axes (from make_scan_vectors).
slow_ax: Name of scan slow axis ('x' or 'y').
fast_ax: Name of scan fast axis ('x' or 'y').
Returns:
Dict: xy_grids
{axis_name: axis_grid} for x, y axes.
"""
slow_ax_vec = scan_vectors[slow_ax]
fast_ax_vec = scan_vectors[fast_ax]
if fast_ax == 'y':
X, Y = np.meshgrid(slow_ax_vec, fast_ax_vec, indexing='ij')
else:
X, Y = np.meshgrid(fast_ax_vec, slow_ax_vec, indexing='xy')
return {'x': X, 'y': Y}
def validate_scan_params(scanner_config: Dict[str, Any], scan_params: Dict[str, Any],
scan_grids: Dict[str, Any], pix_per_line: int, pts_per_line: int,
temp: str, ureg: Any, logger: Any) -> None:
"""Checks whether requested scan parameters are consistent with microscope limits.
Args:
scanner_config: Scanner configuration dict as defined in microscope configuration file.
scan_params: Scan parameter dict as defined in measurements configuration file.
scan_grids: Dict of x, y, z scan grids (from make_scan_grids).
pix_per_line: Number of pixels per line of the scan.
pts_per_line: Number of points per line sampled by the DAQ (to be averaged down to pix_per_line)
temp: Temperature mode of the microscope ('LT' or 'RT').
ureg: pint UnitRegistry, manages physical units.
logger: Used to log the fact that the scan was validated.
Returns:
None
"""
Q_ = ureg.Quantity
voltage_limits = scanner_config['voltage_limits'][temp]
unit = scanner_config['voltage_limits']['unit']
for ax in ['x', 'y', 'z']:
limits = [(lim * ureg(unit)).to('V').magnitude for lim in voltage_limits[ax]]
if np.min(scan_grids[ax]) < min(limits) or np.max(scan_grids[ax]) > max(limits):
err = 'Requested {} axis position is outside of allowed range: {} V.'
raise ValueError(err.format(ax, limits))
if pts_per_line % pix_per_line != 0:
err = 'Current per-channel DAQ rate, line time, and number of channels '
err += 'are incompatible with requested number of fast axis pixels. '
err += 'Please adjust your scan parameters and/or DAQ rate.'
raise ValueError(err)
logger.info('Scan parameters are valid. Starting scan.')
def to_real_units(data_set: Any, ureg: Any=None) -> Any:
"""Converts DataSet arrays from DAQ voltage to real units using recorded metadata.
Preserves shape of DataSet arrays.
Args:
data_set: qcodes DataSet created by Microscope.scan_plane
ureg: Pint UnitRegistry. Default None.
Returns:
np.ndarray: data
ndarray like the DataSet array, but in real units as prescribed by
factors in DataSet metadata.
"""
if ureg is None:
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.load_definitions('./squid_units.txt')
meta = data_set.metadata['loop']['metadata']
data = np.full_like(data_set.daq_ai_voltage, np.nan, dtype=np.double)
for i, ch in enumerate(meta['channels'].keys()):
array = data_set.daq_ai_voltage[:,i,:] * ureg('V')
unit = meta['channels'][ch]['unit']
data[:,i,:] = (array * ureg.Quantity(meta['prefactors'][ch])).to(unit)
return data
def scan_to_arrays(scan_data: Any, ureg: Optional[Any]=None, real_units: Optional[bool]=True,
xy_unit: Optional[str]=None) -> Dict[str, Any]:
"""Extracts scan data from DataSet and converts to requested units.
Args:
scan_data: qcodes DataSet created by Microscope.scan_plane
ureg: pint UnitRegistry, manages physical units.
real_units: If True, converts z-axis data from DAQ voltage into
units specified in measurement configuration file.
xy_unit: String describing quantity with dimensions of length.
If xy_unit is not None, scanner x, y DAQ ao voltage will be converted to xy_unit
according to scanner constants defined in microscope configuration file.
Returns:
Dict: arrays
Dict of x, y vectors and grids, and measured data in requested units.
"""
if ureg is None:
from pint import UnitRegistry
ureg = UnitRegistry()
#: Tell the UnitRegistry what a Phi0 is, and that ohm and Ohm are the same thing.
with open('squid_units.txt', 'w') as f:
f.write('Phi0 = 2.067833831e-15 * Wb\n')
f.write('Ohm = ohm\n')
ureg.load_definitions('./squid_units.txt')
Q_ = ureg.Quantity
meta = scan_data.metadata['loop']['metadata']
scan_vectors = make_scan_vectors(meta, ureg)
slow_ax = 'x' if meta['fast_ax'] == 'y' else 'y'
grids = make_xy_grids(scan_vectors, slow_ax, meta['fast_ax'])
arrays = {'X': grids['x'] * ureg('V'), 'Y': grids['y']* ureg('V')}
arrays.update({'x': scan_vectors['x'] * ureg('V'), 'y': scan_vectors['y'] * ureg('V')})
for ch, info in meta['channels'].items():
array = scan_data.daq_ai_voltage[:,info['idx'],:] * ureg('V')
if real_units:
pre = meta['prefactors'][ch]
arrays.update({ch: (Q_(pre) * array).to(info['unit'])})
else:
arrays.update({ch: array})
if real_units and xy_unit is not None:
bendc = scan_data.metadata['station']['instruments']['benders']['metadata']['constants']
for ax in ['x', 'y']:
grid = (grids[ax] * ureg('V') * Q_(bendc[ax])).to(xy_unit)
vector = (scan_vectors[ax] * ureg('V') * Q_(bendc[ax])).to(xy_unit)
arrays.update({ax.upper(): grid, ax: vector})
return arrays
def td_to_arrays(td_data: Any, ureg: Optional[Any]=None, real_units: Optional[bool]=True) -> Dict[str, Any]:
"""Extracts scan data from DataSet and converts to requested units.
Args:
td_data: qcodes DataSet created by Microscope.td_cap
ureg: pint UnitRegistry, manages physical units.
real_units: If True, converts data from DAQ voltage into
units specified in measurement configuration file.
Returns:
Dict: arrays
Dict of measured data in requested units.
"""
if ureg is None:
from pint import UnitRegistry
ureg = UnitRegistry()
#: Tell the UnitRegistry what a Phi0 is, and that ohm and Ohm are the same thing.
with open('squid_units.txt', 'w') as f:
f.write('Phi0 = 2.067833831e-15 * Wb\n')
f.write('Ohm = ohm\n')
ureg.load_definitions('./squid_units.txt')
Q_ = ureg.Quantity
meta = td_data.metadata['loop']['metadata']
h = [Q_(val).to('V').magnitude for val in meta['range']]
dV = Q_(meta['dV']).to('V').magnitude
heights = np.linspace(h[0], h[1], int((h[1]-h[0])/dV))
arrays = {'height': heights * ureg('V')}
for ch, info in meta['channels'].items():
array = td_data.daq_ai_voltage[:,info['idx'],0] * ureg('V')
if real_units:
pre = meta['prefactors'][ch]
arrays.update({ch: (Q_(pre) * array).to(info['unit'])})
else:
arrays.update({ch: array})
return arrays
def scan_to_mat_file(scan_data: Any, real_units: Optional[bool]=True, xy_unit: Optional[bool]=None,
fname: Optional[str]=None, interpolator: Optional[Callable]=None) -> None:
"""Export DataSet created by microscope.scan_surface to .mat file for analysis.
Args:
scan_data: qcodes DataSet created by Microscope.scan_plane
real_units: If True, converts z-axis data from DAQ voltage into
units specified in measurement configuration file.
xy_unit: String describing quantity with dimensions of length.
If xy_unit is not None, scanner x, y DAQ ao voltage will be converted to xy_unit
according to scanner constants defined in microscope configuration file.
fname: File name (without extension) for resulting .mat file.
If None, uses the file name defined in measurement configuration file.
interpolator: Instance of scipy.interpolate.Rbf, used to interpolate touchdown points.
Default: None.
"""
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.load_definitions('./squid_units.txt')
Q_ = ureg.Quantity
meta = scan_data.metadata['loop']['metadata']
arrays = scan_to_arrays(scan_data, ureg=ureg, real_units=real_units, xy_unit=xy_unit)
mdict = {}
for name, arr in arrays.items():
if real_units:
if xy_unit:
unit = meta['channels'][name]['unit'] if name.lower() not in ['x', 'y'] else xy_unit
else:
unit = meta['channels'][name]['unit'] if name.lower() not in ['x', 'y'] else 'V'
else:
unit = 'V'
if meta['fast_ax'] == 'y':
arr = arr.T
mdict.update({name: {'array': arr.to(unit).magnitude, 'unit': unit}})
if interpolator is not None:
surf = interpolator(arrays['X'], arrays['Y'])
surf = surf if meta['fast_ax'] == 'x' else surf.T
mdict.update({'surface': {'array': surf, 'unit': 'V'}})
mdict.update({'prefactors': meta['prefactors'], 'location': scan_data.location})
if fname is None:
fname = meta['fname']
fpath = scan_data.location + '/'
io.savemat(next_file_name(fpath + fname, 'mat'), mdict)
def td_to_mat_file(td_data: Any, real_units: Optional[bool]=True, fname: Optional[str]=None) -> None:
"""Export DataSet created by microscope.td_cap to .mat file for analysis.
Args:
td_data: qcodes DataSet created by Microscope.td_cap
real_units: If True, converts data from DAQ voltage into
units specified in measurement configuration file.
fname: File name (without extension) for resulting .mat file.
If None, uses the file name defined in measurement configuration file.
"""
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.load_definitions('./squid_units.txt')
Q_ = ureg.Quantity
meta = td_data.metadata['loop']['metadata']
arrays = td_to_arrays(td_data, ureg=ureg, real_units=real_units)
mdict = {}
for name, arr in arrays.items():
if name is not 'height':
unit = meta['channels'][name]['unit'] if real_units else 'V'
mdict.update({name: {'array': arr.to(unit).magnitude, 'unit': unit}})
mdict.update({'height': {'array': arrays['height'].to('V').magnitude, 'unit': 'V'}})
mdict.update({
'prefactors': meta['prefactors'],
'location': td_data.location
})
try:
mdict.update({'td_height': td_data.metadata['loop']['metadata']['td_height']})
except KeyError:
pass
if fname is None:
fname = meta['fname']
fpath = td_data.location + '/'
io.savemat(next_file_name(fpath + fname, 'mat'), mdict)
def moving_avg(x: Union[List, np.ndarray], y: Union[List, np.ndarray],
window_width: int) -> Tuple[np.ndarray]:
"""Given 1D arrays x and y, calculates the moving average of y.
Args:
x: x data (1D array).
y: y data to be averaged (1D array).
window_width: Width of window over which to average.
Returns:
Tuple[np.ndarray]: x, ymvg_avg
x data with ends trimmed according to width_width, moving average of y data
"""
cs_vec = np.cumsum(np.insert(y, 0, 0))
ymvg_avg = (cs_vec[window_width:] - cs_vec[:-window_width]) / window_width
xs = int(np.ceil(window_width / 2)) - 1
xf = -xs if window_width % 2 else -(xs + 1)
return x[xs:xf], ymvg_avg
def fit_line(x: Union[list, np.ndarray], y: Union[list, np.ndarray]) -> Tuple[np.ndarray, float]:
"""Fits a line to x, y(x) and returns (polynomial_coeffs, rms_residual).
Args:
x: List or np.ndarry, independent variable.
y: List or np.ndarry, dependent variable.
Returns:
Tuple[np.ndarray, float]: p, rms
Array of best-fit polynomial coefficients, rms of residuals.
"""
p, residuals, _, _, _ = np.polyfit(x, y, 1, full=True)
rms = np.sqrt(np.mean(np.square(residuals)))
return p, rms
def clear_artists(ax):
for artist in ax.lines + ax.collections:
artist.remove()
|
python
|
"""
Feb 23
Like net_feb23_1 but with faster affine transform and more filters and DNN (~15s faster)
363 | 0.678831 | 0.869813 | 0.780434 | 74.74% | 69.6s
Early stopping.
Best valid loss was 0.846821 at epoch 262.
Finished training. Took 25459 seconds
Accuracy test score is 0.7608
Multiclass log loss test score is 0.8297
Model saved to models/net-net_feb24_1-0.829659233298-2015-02-26-07-32-43.pickle
scale_choices = [ 0.85 1. 1.15]
rotation_choices = [0, 45, 90, 135, 180, 225, 270, 315]
translate_y_choices = [0]
translate_x_choices = [0]
Finished predicting all 130400 images. Took 3417 seconds in total
Saving prediction to submissions/2015-02-26-09-38-17.csv
Done. Took 19 seconds
Ziping up submission...
adding: submissions/2015-02-26-09-38-17.csv (deflated 56%)
Zip file created at submissions/2015-02-26-09-38-17.zip. Took 25 seconds
0.984513 on kaggle
"""
import theano
from nolearn.lasagne import NeuralNet
from lasagne import layers
# from lasagne.layers.cuda_convnet import Conv2DCCLayer, MaxPool2DCCLayer
from lasagne.layers.dnn import Conv2DDNNLayer, MaxPool2DDNNLayer
from lasagne.updates import rmsprop
from lasagne.nonlinearities import softmax
from lasagne.objectives import multinomial_nll
from .augment_iterators import *
from .net_utils import *
class TrainBatchIterator(MeanSubtractMixin,
AffineTransformIteratorMixin,
VerticalFlipBatchIteratorMixin,
HorizontalFlipBatchIteratorMixin,
ShuffleBatchIteratorMixin,
BaseBatchIterator):
pass
class TestBatchIterator(MeanSubtractMixin,
BaseBatchIterator):
pass
train_iterator = TrainBatchIterator(batch_size=128,
vflip_n=2, hflip_n=2, affine_n=2,
angle_choices=list(range(0, 360, 90)),
scale_choices=np.linspace(.9, 1.1, 10),
translate_choices=list(range(0, 1)))
test_iterator = TestBatchIterator(batch_size=128)
net = NeuralNet(
eval_size=0.05,
layers=[
('input', layers.InputLayer),
('l1c', Conv2DDNNLayer),
('l1p', MaxPool2DDNNLayer),
('l1d', layers.DropoutLayer),
('l2c', Conv2DDNNLayer),
('l2p', MaxPool2DDNNLayer),
('l2d', layers.DropoutLayer),
('l3c', Conv2DDNNLayer),
('l3p', MaxPool2DDNNLayer),
('l3d', layers.DropoutLayer),
('l5f', layers.DenseLayer),
('l5p', layers.FeaturePoolLayer),
('l5d', layers.DropoutLayer),
('l6f', layers.DenseLayer),
('l6p', layers.FeaturePoolLayer),
('l6d', layers.DropoutLayer),
('l7f', layers.DenseLayer),
('l7p', layers.FeaturePoolLayer),
('l7d', layers.DropoutLayer),
('output', layers.DenseLayer),
],
input_shape=(None, 1, 48, 48),
l1c_num_filters=128, l1c_filter_size=(3, 3),
l1p_ds=(2, 2),
l1d_p=0.2,
l2c_num_filters=256, l2c_filter_size=(3, 3),
l2p_ds=(2, 2),
l2d_p=0.3,
l3c_num_filters=512, l3c_filter_size=(3, 3),
l3p_ds=(2, 2),
l3d_p=0.4,
l5f_num_units=2048,
l5p_ds=2,
l5d_p=0.5,
l6f_num_units=2048,
l6p_ds=2,
l6d_p=0.5,
l7f_num_units=2048,
l7p_ds=2,
l7d_p=0.5,
output_num_units=121,
output_nonlinearity=softmax,
loss=multinomial_nll,
batch_iterator_train=train_iterator,
batch_iterator_test=test_iterator,
update=rmsprop,
update_learning_rate=theano.shared(float32(1e-4)),
update_rho=0.9,
update_epsilon=1e-6,
regression=False,
on_epoch_finished=[
StepDecay('update_learning_rate', start=1e-4, stop=1e-7),
EarlyStopping(patience=100)
],
max_epochs=1500,
verbose=1
)
|
python
|
# cat train.info | grep "Test net output #0: accuracy =" | awk '{print $11}'
import re
import os
import matplotlib.pyplot as plt
import numpy as np
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--traininfo', type=str, required=True)
args = parser.parse_args()
traininfo = open(args.traininfo,'r')
error = []
for line in traininfo:
if re.match(".*(Test net output \#0\: accuracy =).*", line):
error.append(1-float(line.split()[10]))
print error
plt.subplot(121)
plt.plot(error)
plt.subplot(122)
plt.plot( np.log10(error))
#plt.ylim((0.1, 0.5))
file = os.path.dirname(args.traininfo)+'/accu.png'
plt.savefig(file)
#plt.show()
|
python
|
'''
Perform Object Classification (SGCLS only)
Input is the pointcloud of the BOX, its location and heading is known
Output the predicted class of the BOX
'''
import torch
from torch import nn
from torch.nn import functional as F
from model.modeling.detector.pointnet2.pointnet2_modules import PointnetSAModuleVotes, PointnetFPModule
from model.structure.pc_list import PcList
from model.structure.box3d_list import Box3dList
from model.dataset.rscan_utils import extract_pc_in_box3d
from model.modeling.detector.models.backbone_module import Pointnet2Backbone
class cls_predictor(nn.Module):
def __init__(self, in_dim, num_class):
'''
:param in_dim: input feature dim, if only XYZ is provided, then in_dim == 0
:param num_class: number of foreground classes
'''
super().__init__()
self.input_dim = in_dim
self.num_class = num_class
self.sa1 = PointnetSAModuleVotes( # 修改一下超参数
npoint=128,
radius=0.2,
nsample=32,
mlp=[self.input_dim, 64, 64, 128],
use_xyz=True,
normalize_xyz=True
).cuda()
self.sa2 = PointnetSAModuleVotes(
npoint=32,
radius=0.4,
nsample=64,
mlp=[128, 128, 128, 256],
use_xyz=True,
normalize_xyz=True
).cuda()
self.sa3 = PointnetSAModuleVotes( # 只要npoint给的是None,就算作是group_all了,radius和nsample也全部置None
npoint=None,
radius=None,
nsample=None,
mlp=[256, 128, 128, 256],
use_xyz=True,
normalize_xyz=True
).cuda()
self.post_SA = torch.nn.Sequential(
nn.Linear(256, 128),
nn.ReLU(inplace=True),
nn.Linear(128, self.num_class),
).cuda()
def _break_up_pc(self, pc):
xyz = pc[..., 0:3].contiguous()
features = (
pc[..., 3:].transpose(1, 2).contiguous() # (B,C,N)
if pc.size(-1) > 3 else None
)
return xyz, features
def forward(self, pclist):
assert (isinstance(pclist, PcList))
if self.input_dim>0:
in_xyz, features = self._break_up_pc(
pc=pclist.xyz
)
else:
in_xyz = pclist.xyz
features = None
if features is None:
xyz, features, _ = self.sa1(in_xyz.float().cuda())
else:
xyz, features, _ = self.sa1(in_xyz.float().cuda(), features.transpose(1, 2).float().cuda())
xyz, features, _ = self.sa2(xyz.cuda(), features.cuda())
xyz, features, _ = self.sa3(xyz.cuda(), features.cuda()) # (batch_pc_size, 128)
output = self.post_SA(features.cuda()) # (batch_pc_size , num_class)
return output
|
python
|
# Copyright 2016 Intel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from oslo_config import cfg
import syntribos
from syntribos._i18n import _
from syntribos.checks.header import cors
from syntribos.clients.http import client
from syntribos.clients.http import parser
from syntribos.tests import base
CONF = cfg.CONF
class CorsHeader(base.BaseTestCase):
"""Test for CORS wild character vulnerabilities in HTTP header."""
test_name = "CORS_WILDCARD_HEADERS"
parameter_location = "headers"
client = client()
failures = []
@classmethod
def get_test_cases(cls, filename, file_content, meta_vars):
request_obj = parser.create_request(
file_content, CONF.syntribos.endpoint, meta_vars
)
prepared_copy = request_obj.get_prepared_copy()
cls.test_resp, cls.test_signals = cls.client.send_request(
prepared_copy)
cls.test_req = request_obj.get_prepared_copy()
yield cls
def test_case(self):
self.test_signals.register(cors(self))
cors_slugs = [
slugs for slugs in self.test_signals.all_slugs
if "HEADER_CORS" in slugs]
for slug in cors_slugs:
if "ORIGIN" in slug:
test_severity = syntribos.HIGH
else:
test_severity = syntribos.MEDIUM
self.register_issue(
defect_type="CORS_HEADER",
severity=test_severity,
confidence=syntribos.HIGH,
description=(
_("CORS header vulnerability found.\n"
"Make sure that the header is not assigned "
"a wildcard character.")))
|
python
|
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy ps.psycopg2 ps.requests ps.websockets])"
import sys
import threading
from tenmoTypes import *
from tenmoGraph import universe_print_dot
import select
import time
import datetime
import pprint
import traceback
import io
import json
import psycopg2
import psycopg2.extensions
from psycopg2.extras import Json, DictCursor, RealDictCursor
def json_default(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
class PgJson(Json):
def dumps(self, o):
return json.dumps(o, default=json_default)
conn = None
def getPgConn(pgUri: str):
global conn
if conn is None:
conn = psycopg2.connect(pgUri, cursor_factory=RealDictCursor)
return conn
def send(events : Sequence[Event], pgUri: str):
conn = getPgConn(pgUri)
for e in events:
event_type = type(e).__name__
with conn:
with conn.cursor() as cur:
cur.execute("INSERT INTO events(ulid, created_at, event_type, payload) VALUES (%s, %s, %s, %s)",
[e.event_ulid, e.timestamp, event_type, PgJson(e._asdict())])
def listen(pgUri: str, cb):
conn = getPgConn(pgUri)
listenConn(conn, cb)
def listenConn(conn, cb):
curs = conn.cursor()
curs.execute("LISTEN events_changed;")
seconds_passed = 0
while True:
conn.commit()
if select.select([conn],[],[],5) == ([],[],[]):
seconds_passed += 5
print("{} seconds passed without a notification...".format(seconds_passed))
else:
seconds_passed = 0
conn.poll()
conn.commit()
while conn.notifies:
notify = conn.notifies.pop()
cb(notify, conn)
def print_notify(notify, conn):
print("Got NOTIFY:", datetime.datetime.now(), notify.pid, notify.channel, notify.payload)
def ensure_entity(conn, curs, event):
p = event['payload']
if 'entity_id' in p:
curs.execute("INSERT INTO entities (entity_id, description) VALUES (%s, %s) ON CONFLICT DO NOTHING",
[p['entity_id'], p.get('entity_description', '')])
def ensure_process(conn, curs, event):
p = event['payload']
if 'process_id' in p and p['process_id'] is not None:
curs.execute("INSERT INTO process (process_id) VALUES (%s) ON CONFLICT DO NOTHING",
[p['process_id']])
def ensure_incarnation(conn, curs, event):
p = event['payload']
creator_id = p['execution_id']
if p['type'] == 'r':
creator_id = None
curs.execute("""INSERT INTO incarnations AS old (incarnation_id, entity_id, parent_id, creator_id, description)
VALUES (%s, %s, %s, %s, %s) ON CONFLICT (incarnation_id)
DO UPDATE SET creator_id = COALESCE(old.creator_id, EXCLUDED.creator_id)""",
[p['incarnation_id'], p.get('entity_id', None), p.get('parent_id', None), creator_id, p.get('incarnation_description', None)])
def insert_execution(conn, curs, event):
p = event['payload']
curs.execute("""INSERT INTO executions AS old
(execution_id, begin_timestamp, parent_id, creator_id, process_id, description)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT DO NOTHING""",
[p['execution_id'],
p['timestamp'],
p.get('parent_id', None),
p.get('creator_id', None),
p.get('process_id', None),
p.get('description', '')])
def finish_execution(conn, curs, event):
p = event['payload']
with conn.cursor() as c:
c.execute("""UPDATE executions AS old
SET end_timestamp = %s
WHERE execution_id = %s
RETURNING execution_id""",
[p['timestamp'], p['execution_id']])
return c.rowcount == 1
def insert_operation(conn, curs, event):
p = event['payload']
curs.execute("""INSERT INTO operations AS old
( operation_id
, ts
, execution_id
, op_type
, entity_id
, incarnation_id
, entity_description
, incarnation_description)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT DO NOTHING""",
[p.get('operation_id', event['ulid'].strip()),
p.get('timestamp', event['created_at']),
p['execution_id'],
p['type'],
p.get('entity_id', None),
p['incarnation_id'],
p.get('entity_description', ''),
p.get('incarnation_description', '')])
def ensure_interaction(conn, curs, event):
p = event['payload']
curs.execute("""INSERT INTO interactions AS old
(interaction_id, ts, initiator_participant, responder_participant, description)
VALUES (%s, %s, %s, %s, %s) ON CONFLICT (interaction_id)
DO UPDATE
SET ts = COALESCE(old.ts, EXCLUDED.ts),
initiator_participant = COALESCE(old.initiator_participant, EXCLUDED.initiator_participant),
responder_participant = COALESCE(old.responder_participant, EXCLUDED.responder_participant),
description = COALESCE(old.description, EXCLUDED.description)""",
[p['interaction_id'],
p.get('timestamp', event['created_at']),
p['sender'],
p['target'],
p.get('interaction_description', None)])
def insert_message(conn, curs, event):
p = event['payload']
curs.execute("""INSERT INTO messages AS old
( message_id
, interaction_id
, ts
, sender
, target
, payload
, incarnations_ids)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT DO NOTHING""",
[p.get('message_id', event['ulid'].strip()),
p['interaction_id'],
p.get('timestamp', event['created_at']),
p['sender'],
p['target'],
p.get('payload', None),
p.get('incarnations_ids', None)])
def process_one_event(conn, curs, event):
print('process_one_event: ', event['ulid'])
pprint.pprint(event)
try:
if event['event_type'] == 'EventExecutionBegins':
ensure_process(conn, curs, event)
insert_execution(conn, curs, event)
return True
elif event['event_type'] == 'EventExecutionEnds':
return finish_execution(conn, curs, event)
elif event['event_type'] == 'EventOperation':
ensure_entity(conn, curs, event)
ensure_incarnation(conn, curs, event)
insert_operation(conn, curs, event)
return True
elif event['event_type'] == 'EventMessage':
ensure_interaction(conn, curs, event)
insert_message(conn, curs, event)
return True
except Exception as e:
pprint.pprint(e)
print(traceback.format_exc())
return False
def process_events_batch(pgUri, signal):
conn = psycopg2.connect(pgUri, cursor_factory=RealDictCursor)
n = 0
print('process_events_batch')
while True:
processed = 0
with conn.cursor() as curs:
print('select one to process')
curs.execute("SELECT * FROM events WHERE status = 'i' AND attempts < 50 LIMIT 1 FOR UPDATE")
for r in curs:
print('got', r['ulid'])
processed += 1
with conn.cursor() as c:
c.execute("UPDATE events SET status = 'c', attempts = attempts + 1 WHERE ulid = %s", [r['ulid']])
print('claimed', c.rowcount)
conn.commit()
with conn.cursor() as c:
if process_one_event(conn, c, r):
print('releasing')
c.execute("UPDATE events SET status = 'p' WHERE ulid = %s", [r['ulid']])
conn.commit()
print('comitted')
if processed == 0:
with conn.cursor() as curs:
print('populating graph')
curs.execute('call populate_graph()')
conn.commit()
signal.wait(30)
signal.clear()
continue
def clean_events(pgUri: str):
"""
Repeatedly unclaims events which stay in claimed mode longer than 5 seconds.
"""
conn = psycopg2.connect(pgUri, cursor_factory=RealDictCursor)
while True:
processed = 0
with conn:
with conn.cursor() as curs:
curs.execute("UPDATE events SET status = 'i' WHERE status = 'c' AND (clock_timestamp() - modified) > interval '00:00:05'")
processed = curs.rowcount
if processed > 0:
print('Un-claimed %d rows' % processed)
continue
time.sleep(5)
def process_events_forever(pgUri: str):
conn = getPgConn(pgUri)
curs = conn.cursor()
curs.execute("LISTEN events_changed;")
conn.commit()
signal = threading.Event()
worker = threading.Thread(target=process_events_batch, args=(pgUri,signal,))
worker.start()
cleaner = threading.Thread(target=clean_events, args=(pgUri,))
cleaner.start()
seconds_passed = 0
while True:
conn.commit()
if select.select([conn],[],[],5) == ([],[],[]):
seconds_passed += 5
print("{} seconds passed without a notification...".format(seconds_passed))
else:
seconds_passed = 0
conn.poll()
conn.commit()
while conn.notifies:
print('Got notification')
notify = conn.notifies.pop()
signal.set()
# cb(notify, conn)
worker.join()
cleaner.join()
def fromPgDict(r):
d = dict(r)
if 'stored_at' in d:
del d['stored_at']
return d
def entityFromPg(row):
ent = Entity(**fromPgDict(row))
return (row['entity_id'], ent._replace(incarnations = []))
def processFromPg(row):
return (row['process_id'], Process(**fromPgDict(row)))
def incarnationFromPg(row):
return (row['incarnation_id'], Incarnation(**fromPgDict(row)))
def operationFromPg(row):
return (row['operation_id'], Operation(**fromPgDict(row)))
def executionFromPg(row):
return (row['execution_id'], Execution(**fromPgDict(row)))
def interactionFromPg(row):
inter = Interaction(**fromPgDict(row))
return (row['interaction_id'], inter._replace(messages = []))
def messageFromPg(row):
return (row['message_id'], Message(**fromPgDict(row)))
def assertFromPg(row):
return Assert(**fromPgDict(row))
def load_universe(pgUri: str):
conn = getPgConn(pgUri)
with conn:
with conn.cursor() as c:
c.execute("SELECT * FROM executions")
executions = dict( executionFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM incarnations")
incarnations = dict( incarnationFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM operations")
operations = dict( operationFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM processes")
processes = dict( processFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM entities")
entities = dict( entityFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM interactions")
interactions = dict( interactionFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM messages")
messages = dict( messageFromPg(r) for r in c )
with conn.cursor() as c:
c.execute("SELECT * FROM asserts")
asserts = set( assertFromPg(r) for r in c )
for iid, i in incarnations.items():
entities[i.entity_id].incarnations.append(i.incarnation_id)
for mid, m in messages.items():
interactions[m.interaction_id].messages.append(m.message_id)
u = Universe(executions=executions, operations=operations, incarnations=incarnations, entities=entities, processes=processes, interactions=interactions, messages=messages, asserts=asserts)
# pprint.pprint(u)
return u
def serve(pgUri):
import tenmoServe
def serveUniverse(pgUri):
print('serving dot')
output = io.BytesIO()
u = load_universe(pgUri)
universe_print_dot(u, output)
return output.getvalue()
tenmoServe.serve(pgUri, '/dot', serveUniverse)
if __name__ == "__main__":
if sys.argv[2] == 'listen':
listen(sys.argv[1], print_notify)
elif sys.argv[2] == 'dot':
universe_print_dot(load_universe(sys.argv[1]))
elif sys.argv[2] == 'serve':
serve(sys.argv[1])
elif sys.argv[2] == 'process':
process_events_forever(sys.argv[1])
|
python
|
from django.urls import path
from django.contrib.auth import views as auth_views
from account import views as account_views
urlpatterns = [
path('login',
auth_views.LoginView.as_view(
template_name='account/login.html',
extra_context={
'title': 'Account login'}),
name='login'),
path('logout',
auth_views.LogoutView.as_view(
template_name='account/logout.html',
extra_context={
'title': 'Account logout'}),
name='logout'),
path('register',
auth_views.LoginView.as_view(
template_name='account/register.html',
extra_context={
'title': 'Account register'}),
name='register'),
path('profile',
account_views.ProfileView.as_view(),
name='profile'),
path('profile/edit',
account_views.ProfileEditView.as_view(),
name='profile_edit'),
path('password_change',
auth_views.PasswordChangeView.as_view(
template_name='account/password_change.html',
extra_context={
'title': 'Account password change'}),
name='password_change'),
path('password_change/done',
auth_views.PasswordChangeDoneView.as_view(
template_name='account/password_change_done.html',
extra_context={
'title': 'Account change password done'}),
name='password_change_done'),
path('password_reset',
auth_views.PasswordResetView.as_view(
template_name='account/password_reset.html',
extra_context={
'title': 'Account change password reset'}),
name='password_reset'),
path('password_reset/done',
auth_views.PasswordResetDoneView.as_view(
template_name='account/password_reset_done.html',
extra_context={
'title': 'Account change password done'}),
name='password_reset_done'),
path('password_reset/confirm',
auth_views.PasswordResetConfirmView.as_view(
template_name='account/password_reset_confirm.html',
extra_context={
'title': 'Account change password confirm'}),
name='password_reset_confirm'),
path('password_reset/complete/<uidb64>/<token>/',
auth_views.PasswordResetCompleteView.as_view(
template_name='account/password_reset_complete.html',
extra_context={
'title': 'Account change password complete'}),
name='password_reset_complete')
]
|
python
|
'''
This is based on cnn35_64. This is after the first pilot.
Changes:
-don't filter out # in the tokenizer, tokenize both together. or save tokenizer https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring
-use 'number' w2v as representation for any digit
-shuffling problem should be check before advancing: plot random selection of conv1 layers. theys should all be 14 or 15.
-tune hyperparameters.
'''
import datetime
import sys
import numpy as np
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Input, Dense, Embedding, Conv2D, MaxPool2D
from keras.layers import Reshape, Flatten, Dropout
from keras.models import Model
import os
import data_helpers
import config
import pickle
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from keras.utils import np_utils
from numpy.random import seed
seed(123)
from tensorflow import set_random_seed
set_random_seed(123)
# Parameters
# =====================================================================
categories = config.categories
verbose = config.verbose
toy = config.toy
save_checkpoints = config.save_checkpoints
plot_RSA = config.plot_RSA
if toy:
# categories = categories[:4]
epochs = 1 #it will probably need more.
else:
epochs = config.epochs # it will probably need more.
if config.local_or_cluster:
categories = categories[:3]
epochs=1
verbose=1
# epochs = 6
#
save_checkpoints=False
print('running for '+str(epochs)+' epochs')
if config.local_or_cluster:
directory_name = '18-06-09-15-46-19'
# directory_name = datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S")
file_name = 'cnn'
else:
directory_name = '18-06-09-15-46-19'
# directory_name = datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S")
file_name = os.path.basename(__file__)
print('running '+directory_name+' '+file_name)
# Model parameters
activation = 'elu'
conv2_size = 2 #conv1_size=3
pool_size = (3, 1)
stride_size = (2, 1)
padding = 'same' #same: classic, you go until end of zero pad, valid: you truncate end if it doesnt fit in filter.
filter_sizes = [3] #[3,4,7] #Takes up to three.
batch_size = config.batch_size
# sequence_length = x.shape[1] # 56
sequence_length = config.sequence_length
embedding_dim = 300
def get_output(model, layer_name, batch_size=batch_size, Xvalidation=None, layer_2d_or_1d='2d'):
intermediate_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output)
layer_output = intermediate_layer_model.predict(Xvalidation, batch_size=batch_size, verbose=verbose)
if layer_2d_or_1d=='2d':
layer_output = np.reshape(layer_output,(len(Xvalidation), int(layer_output.shape[1])*int(layer_output.shape[3])))
layer_output = pd.DataFrame(layer_output)
return layer_output
# layer_name = 'kmaxpool_1'
# intermediate_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output_shape)
# Load data
##============================================================================================
#
# importlib.reload(data_helpers)
# Xtrain, Ytrain = data_helpers.load_all_data(config.train_path,config.validation_path, categories, shuffle=False) # I changed this so it combines train and validation
# Xvalidation, Yvalidation = data_helpers.load_data(config.validation_path, categories)
# Xvalidation_raw, Yvalidation_raw = data_helpers.load_data_raw(config.validation_path, categories)
Xtrain, Ytrain = data_helpers.load_data(config.train_path, categories)
Xvalidation, Yvalidation = data_helpers.load_data(config.validation_path, categories)
Xvalidation_raw, Yvalidation_raw = data_helpers.load_data_raw(config.validation_path, categories)
## Encode Ytrain
# =====================================================================================
#one hot encode and integer encode
Ytrain_encoded = np_utils.to_categorical(Ytrain)
Ytrain_integer = np.array(Ytrain)
Yvalidation_encoded = np_utils.to_categorical(Yvalidation)
Yvalidation_integer = np.array(Yvalidation)
# Zero pad (encode) Xtrain and Xvalidation
# ==================================================================================================
tokenizer = Tokenizer(filters='!"$%&()*+,-./:;<=>?@[\]^_`{|}~') #TODO depending on word embedding, set lower=False.
tokenizer.fit_on_texts(np.append(np.array(Xtrain), np.array(Xvalidation)))
# tokenizer.fit_on_texts(Xtrain)
sequences = tokenizer.texts_to_sequences(Xtrain)
sequences2 = tokenizer.texts_to_sequences(Xvalidation)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
Xtrain_encoded = pad_sequences(sequences, maxlen=sequence_length, padding='post')
Xvalidation_encoded = pad_sequences(sequences2, maxlen=sequence_length, padding='post')
#define max length of doc
# l1 = []
# for text in Xtrain:
# l1.append(len(text_to_word_sequence(text)))
# def roundup(x):
# return int(math.ceil(x / 100.0)) * 100
#
# sequence_length = roundup(np.max(l1)) #
## embedding layer https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html
# =====================================================================================
# Creating the model
#
# from gensim.models.keyedvectors import KeyedVectors
# it_model = KeyedVectors.load_word2vec_format(config.word_embeddings_path+'wiki.it.vec')
#
# # Getting the tokens
# words = []
# for word in it_model.vocab:
# words.append(word)
#
# # Printing out number of tokens available
# print("Number of Tokens: {}".format(len(words)))
# # Printing out the dimension of a word vector
# print("Dimension of a word vector: {}".format(len(it_model[words[0]])))
# # Print out the vector of a word
# embeddings_index = {}
# for i in range(len(words)):
# embeddings_index[words[i]] = it_model[words[i]]
#
# def save_obj(obj, path_and_filename):
# with open(path_and_filename + '.pkl', 'wb+') as f:
# pickle.dump(obj, f)
#
# save_obj(embeddings_index,'/Users/danielmlow/Dropbox/cnn/data/wiki.it/gensim_it_w2v')
def load_obj(path_and_filename):
with open(path_and_filename, 'rb') as f:
return pickle.load(f)
embeddings_index = load_obj(config.word_embeddings_path+'/gensim_it_w2v.pkl') #dictionary embeddings_index.get('è') returns word embedding
# from scipy import spatial
# res = spatial.distance.cosine(embeddings_index.get('uno'), embeddings_index.get('dieci'))
# embeddings_index = {}
# # with open(os.path.join(config.word_embeddings_path,'GoogleNews-vectors-negative300.bin')) as f:
# with open(os.path.join(config.word_embeddings_path,'glove.6B.'+str(embedding_dim)+'d.txt')) as f:
# for line in f:
# values = line.split()
# word = values[0]
# coefs = np.asarray(values[1:], dtype='float32')
# embeddings_index[word] = coefs
#
# print('Found %s word vectors.' % len(embeddings_index))
embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim)) #this will be all embeddings for my vocabulary
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
# # leverage our embedding_index dictionary and our word_index to compute our embedding matrix
# # ============================================================================================================
# embedding_matrix = np.zeros((len(word_index) + 1, embedding_dim))
#
# for word, i in word_index.items():
# embedding_vector = embeddings_index.get(word)
# if embedding_vector is not None:
# # words not found in embedding index will be all-zeros.
# embedding_matrix[i] = embedding_vector
#
path_to_dir = os.path.join(config.save_to, directory_name + '/')
try: os.makedirs(path_to_dir)
except: pass
print('directory_name: '+directory_name)
print('path_to_dir: '+path_to_dir)
# Model
## ======================================================================================================
print("Creating Model...")
def cnn(drop, batch_size, optimizer, num_filters, activation1, activation2, dense_1_neurons, dense_final_neurons, dense_2_layer):
inputs = Input(shape=(sequence_length,), dtype='int32')
embedding = Embedding(input_dim=len(word_index) + 1, weights=[embedding_matrix],output_dim=embedding_dim, input_length=sequence_length,trainable=True)(inputs)
dropout_1 = Dropout(drop)(embedding)
reshape1 = Reshape((sequence_length,embedding_dim,1))(dropout_1)
conv_1 = Conv2D(num_filters, kernel_size=(filter_sizes[0], embedding_dim),use_bias=True, strides=1, padding='valid', activation=activation1, name='conv_1')(reshape1)
maxpool_1 = MaxPool2D(pool_size=pool_size, strides=stride_size, padding=padding,name='pool_1')(conv_1)
maxpool_1_reshape = Reshape( (int(maxpool_1.shape[1]),int(maxpool_1.shape[3]),1), name='pool_1_reshaped')(maxpool_1)
dropout_2 = Dropout(drop)(maxpool_1_reshape)
conv_2 = Conv2D(num_filters*2, kernel_size=(conv2_size, int(maxpool_1_reshape.shape[2])), padding='valid', kernel_initializer='normal', activation=activation1, name='conv_2')(dropout_2)
maxpool_2 = MaxPool2D(pool_size=pool_size, strides=stride_size, padding='valid',name='pool_2')(conv_2)
maxpool_2_reshape = Reshape((int(maxpool_2.shape[1]),int(maxpool_2.shape[3]),1),name='pool_2_reshaped')(maxpool_2)
flatten = Flatten()(maxpool_2_reshape)
dropout_3 = Dropout(drop)(flatten)
dense_1 = Dense(units=dense_1_neurons, activation=activation2,name='dense_1')(dropout_3)
dropout_4 = Dropout(drop)(dense_1)
if dense_2_layer == 'yes':
dense_2 = Dense(units=dense_1_neurons, activation=activation2, name='dense_2')(dropout_4)
dropout_5 = Dropout(drop)(dense_2)
dense_final = Dense(units=512, activation=activation2, name='dense_final')(dropout_5)
else:
dense_final = Dense(units=dense_final_neurons, activation=activation2, name='dense_final')(dropout_4)
dropout_6 = Dropout(drop)(dense_final)
softmax_final = Dense(units=len(categories), activation='softmax', name='softmax_final')(dropout_6)
model = Model(inputs=inputs, outputs=softmax_final)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(Xtrain_encoded, Ytrain_encoded, batch_size=batch_size, epochs=epochs,
verbose=verbose) # starts training
return model
with open(path_to_dir + 'log.txt', 'a+') as f:
f.write(file_name + '\n')
f.write(directory_name+ '\n\n')
# dropout_rates = [0.1, 0.2, 0.3, 0.4, 0.5]
# batch_sizes = [64,128, 256,512]
# optimizers = ['RMSprop','Adam']
# activations2 = ['elu','relu']
# num_filters = 64
# dense_1_neurons = 1024
# dense_final_neurons = 64
num_filters_all = [16,32,64,128]
dense_1_neurons_all= [2048,1024]
dense_2_layer_all = ['yes', 'no']
dense_final_neurons_all = [128]
drop = 0.3
batch_size=256
optimizer = 'Adam'
activation1 = 'elu'
activation2 = 'elu'
# l=[]
# for drop in dropout_rates:
# for batch_size in batch_sizes:
# for optimizer in optimizers:
# for activation2 in activations2:
# l.append([drop, batch_size, optimizer,activation2])
# l[]
l=[]
for num_filters in num_filters_all:
for dense_1_neurons in dense_1_neurons_all:
for dense_final_neurons in dense_final_neurons_all:
for dense_2_layer in dense_2_layer_all:
l.append([num_filters, dense_1_neurons, dense_final_neurons, dense_2_layer])
gs_numb = int(sys.argv[1])
i = int(sys.argv[1])
print(i)
for parameters in l[gs_numb:gs_numb+6]:
print(parameters)
# drop, batch_size, optimizer, activation2 = parameters
num_filters, dense_1_neurons, dense_final_neurons, dense_2_layer = parameters
model = cnn(drop, batch_size, optimizer, num_filters, activation1, activation2, dense_1_neurons, dense_final_neurons, dense_2_layer)
accuracy = model.evaluate(Xvalidation_encoded, Yvalidation_encoded,verbose=verbose)
print(i)
with open(path_to_dir + 'log.txt', 'a+') as f:
f.write(str(i)+'=================\n')
f.write('Parameters: '+str(parameters)+'\n')
f.write('Loss and Accuracy: ' +str(accuracy)+'\n')
f.write(str(np.round(accuracy[1],4)) + '\n\n')
i += 1
# if save_checkpoints:
# filepath = path_to_dir+"weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5" #https://machinelearningmastery.com/check-point-deep-learning-models-keras/
# checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=verbose, save_best_only=True, mode='auto')
#
# print("Training Model...")
# if save_checkpoints:
# history = model.fit(Xtrain_encoded, Ytrain_encoded, batch_size=batch_size, epochs=epochs, verbose=verbose, callbacks=[checkpoint]) # starts training
# else:
# history = model.fit(Xtrain_encoded,Ytrain_encoded, batch_size=batch_size, epochs=epochs, verbose=verbose) # starts training
# outputs:
# ============================================================================================================================
# SAVE
# model.save(path_to_dir + 'model.h5', overwrite=True) #Save model #TODO: not working nor checkpoint save model
# model.save_weights(path_to_dir +"model_weights.h5", overwrite=True)
# # plot_model(model, to_file=path_to_dir + 'model.png') # Save plot of model
# np.save(path_to_dir + 'history_dict.npy', history.history) #Save history
# plot_outputs.learning_curve(history.history, path_to_dir) #'loss' 'both'
# accuracy = model.evaluate(Xvalidation_encoded,Yvalidation_encoded,verbose=verbose) # TODO:change to validation set for final model.
# Ypredict = model.predict(Xvalidation_encoded, batch_size=batch_size, verbose=verbose) # TODO:change to validation set for final model.
# Ypredict_encoded = np_utils.to_categorical(Ypredict.argmax(axis=-1))
# Ypredict_integer = Ypredict.argmax(axis=-1)
# np.save(path_to_dir+'Ypredict_integer',Ypredict_integer)
# clas_rep = classification_report(Yvalidation_encoded, Ypredict_encoded,target_names=categories) # TODO:change to validation set for final model.
# df_clas_rep, df_clas_rep_latex = plot_outputs.classification_report_df(clas_rep)
# cm = confusion_matrix(y_true=Yvalidation_integer, y_pred=Ypredict_integer,sample_weight=None) # TODO:change to validation set for final model
# pd.DataFrame(cm, columns=categories, index=categories).to_csv(path_to_dir+'cm.csv')
# index_min = df_clas_rep['f1_score'].idxmin()
# index_max = df_clas_rep['f1_score'].idxmax()
#
# a2 = conv_1.shape[:]
# a2 = str(a2[1])+'*'+str(a2[3])+'='+str(a2[1]*a2[3])
# a3 = maxpool_1.shape[1:3]
# a3 = str(a3[0])+'*'+str(a3[1])+'='+str(a3[0]*a3[1])
# a4 = conv_2.shape[:]
# a4 = str(a4[1])+'*'+str(a4[3])+'='+str(a4[1]*a4[3])
# a5 = maxpool_2.shape[1:3]
# a5 = str(a5[0])+'*'+str(a5[1])+'='+str(a5[0]*a5[1])
#
# reporting = [len(categories),sequence_length,embedding.shape[1:],a2,a3,a4,a5,[''], dense_final_neurons,[''],activation, num_filters, filter_sizes,padding, pool_size, stride_size, drop, epochs, [''], df_clas_rep['f1_score'][len(categories)], [df_clas_rep['class'][index_min],df_clas_rep['f1_score'][index_min]], [df_clas_rep['class'][index_max],df_clas_rep['f1_score'][index_max]]]
# # reporting = [len(categories),sequence_length,embedding.shape[1:], dense_final_neurons,[''],activation, num_filters, filter_sizes,padding, pool_size, stride_size, drop, epochs, [''], df_clas_rep['f1_score'][len(categories)], [df_clas_rep['class'][index_min],df_clas_rep['f1_score'][index_min]], [df_clas_rep['class'][index_max],df_clas_rep['f1_score'][index_max]]]
#
# with open(path_to_dir + 'log.txt', 'a+') as f:
# f.write(file_name+'\n')
# f.write(directory_name)
# f.write('\n\n')
# model.summary(print_fn=lambda x: f.write(x + '\n'))
# f.write('\n\n')
# for i, name in enumerate(model.metrics_names):
# f.write(name+': '+str(np.round(accuracy[i], 2))+'\n')
# # f.write('accuracy: %f ' % (accuracy * 100))
# # f.write('loss: %f ' % (loss))
# f.write('\n\n')
# f.write('Classification Report: \n'+df_clas_rep_latex)
# for i in reporting:
# f.write(str(i)+'\n')
# # Save output_layers
# # loaded_model = load_model(path_to_dir+'model.h5')
# # model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])
# conv_1 = get_output(model, 'conv_1', layer_2d_or_1d='2d', Xvalidation=Xvalidation_encoded)
# # kmaxpool_1 = get_output(model, 'kmaxpool_1', layer_2d_or_1d='2d', Xvalidation=Xvalidation_encoded)
# pool_1 = get_output(model, 'pool_1', layer_2d_or_1d='2d', Xvalidation=Xvalidation_encoded)
# conv_2 = get_output(model, 'conv_2', layer_2d_or_1d='2d', Xvalidation=Xvalidation_encoded)
# pool_2 = get_output(model, 'pool_2', layer_2d_or_1d='2d', Xvalidation=Xvalidation_encoded)
# dense_1 = get_output(model, 'dense_1', layer_2d_or_1d='1d', Xvalidation=Xvalidation_encoded)
# dense_final = get_output(model, 'dense_final', layer_2d_or_1d='1d', Xvalidation=Xvalidation_encoded)
# softmax_final = get_output(model, 'softmax_final', layer_2d_or_1d='1d', Xvalidation=Xvalidation_encoded)
#
# # np.savez_compressed(path_to_dir+'output_layers.npz', a=conv_1, b=pool_1,c=dense_general,d=conv_2, e=pool_2, f=dense_final)
# np.savez_compressed(path_to_dir+'output_layers.npz', a=conv_1, b=pool_1,c=conv_2, d=pool_2, e=dense_1, f=dense_final, g=softmax_final)
# # np.savez_compressed(path_to_dir+'output_layers.npz', a=conv_1, b=kmaxpool_1,c=conv_2, d=pool_2, e=dense_1, f=dense_final)
#
# # import importlib
# # importlib.reload(corr_between_layers)
#
# # Log.txt
# models = [directory_name]
# statistic = 'spearman'
#
# # layers= data_helpers.load_output_layers(path_to_dir)
# layers = [conv_1, pool_1, conv_2, pool_2, dense_1, dense_final, softmax_final]
#
# zeros1 = []
# zeros2 = []
# zeros3 = []
#
# for layer in layers:
# zero1 = (np.count_nonzero(layer.round(1) == 0)) / (layer.shape[0] * layer.shape[1])
# zeros1.append(np.round(zero1,3))
# zero2 = (np.count_nonzero(layer.round(2) == 0)) / (layer.shape[0] * layer.shape[1])
# zeros2.append(np.round(zero2, 3))
# zero3 = (np.count_nonzero(layer.round(3) == 0)) / (layer.shape[0] * layer.shape[1])
# zeros3.append(np.round(zero3, 3))
#
# with open(path_to_dir + 'log.txt', 'a+') as f:
# f.write('zeros round to 1 decimal: '+str(zeros1)+'\n')
# f.write('zeros round to 2 decimals: '+str(zeros2)+'\n')
# f.write('zeros round to 3 decimals: '+str(zeros3)+'\n')
#
#
# # corr_between_layers1 = corr_between_layers.corr_between_layers_method(statistic,models,layers, config.save_to,Xvalidation, categories, model_type=file_name)
# # reporting.append(list(np.round(corr_between_layers1.iloc[-1, :-1], 2)))
#
#
# # ===================================================================================================================
# import random
# # Generate random sequence so you always compare same sentences
# amount_sent = int(len(Xvalidation)/len(categories))
# # sentences_index = list(range(amount_sent))
# # random.shuffle(sentences_index)
# sentences_index = [767, 445, 551, 566, 224, 853, 836, 564, 575, 793, 730, 759, 82, 390, 110, 804, 615, 577, 815, 290, 190, 239, 255, 731, 851, 186, 799, 628, 940, 209, 580, 13, 533, 926, 125, 2, 285, 784, 130, 171, 181, 599, 500, 457, 432, 753, 847, 118, 795, 570, 729, 56, 769, 929, 701, 64, 387, 687, 144, 33, 325, 423, 828, 657, 166, 96, 175, 664, 671, 87, 9, 315, 204, 741, 57, 588, 245, 407, 433, 326, 902, 820, 916, 187, 416, 882, 357, 105, 693, 349, 520, 501, 676, 698, 737, 267, 910, 899, 327, 362, 320, 478, 309, 198, 346, 824, 734, 678, 529, 523, 240, 652, 884, 351, 356, 89, 462, 283, 466, 116, 287, 258, 833, 219, 591, 381, 74, 900, 915, 241, 37, 4, 430, 605, 498, 141, 220, 494, 376, 601, 849, 379, 688, 506, 644, 164, 864, 424, 414, 957, 422, 810, 686, 363, 92, 233, 102, 595, 717, 380, 579, 908, 126, 297, 319, 496, 228, 733, 52, 524, 377, 0, 221, 632, 199, 8, 642, 256, 858, 143, 119, 299, 821, 145, 448, 848, 611, 188, 817, 463, 403, 368, 140, 685, 700, 806, 68, 935, 567, 919, 619, 440, 742, 123, 232, 114, 608, 23, 76, 304, 903, 775, 932, 259, 493, 720, 948, 223, 251, 542, 340, 77, 237, 460, 665, 812, 360, 639, 640, 323, 749, 450, 578, 782, 208, 196, 863, 773, 797, 475, 625, 331, 288, 850, 61, 563, 798, 139, 527, 479, 316, 277, 525, 402, 12, 598, 722, 473, 149, 574, 101, 162, 860, 586, 172, 715, 941, 272, 616, 662, 270, 62, 585, 375, 373, 807, 339, 877, 46, 173, 284, 526, 163, 825, 248, 594, 857, 866, 622, 808, 868, 497, 572, 231, 88, 249, 117, 67, 518, 881, 573, 788, 385, 453, 956, 435, 874, 544, 438, 839, 593, 311, 505, 394, 568, 545, 943, 904, 781, 613, 442, 41, 246, 648, 179, 276, 292, 397, 787, 689, 834, 182, 38, 42, 274, 582, 345, 94, 928, 597, 242, 732, 111, 511, 534, 716, 726, 624, 324, 337, 875, 756, 571, 160, 294, 289, 951, 441, 65, 831, 467, 286, 206, 790, 225, 418, 404, 413, 282, 446, 508, 661, 39, 569, 250, 663, 18, 637, 485, 837, 539, 461, 895, 213, 439, 675, 543, 630, 658, 487, 855, 491, 476, 822, 838, 587, 378, 561, 924, 28, 865, 44, 428, 826, 7, 727, 844, 384, 469, 654, 60, 829, 348, 763, 152, 672, 695, 449, 230, 764, 128, 938, 129, 301, 452, 426, 709, 32, 590, 159, 631, 918, 192, 528, 34, 897, 468, 612, 19, 40, 547, 516, 482, 408, 194, 382, 623, 330, 106, 419, 168, 703, 207, 437, 724, 465, 431, 776, 271, 536, 75, 170, 934, 670, 744, 275, 85, 15, 358, 841, 81, 515, 254, 553, 667, 842, 679, 750, 71, 765, 43, 655, 712, 805, 819, 761, 811, 191, 614, 310, 937, 36, 723, 950, 21, 883, 161, 747, 169, 321, 263, 214, 336, 714, 830, 659, 617, 552, 51, 954, 406, 10, 234, 474, 183, 146, 405, 603, 6, 484, 581, 458, 873, 604, 522, 770, 328, 636, 861, 156, 548, 707, 499, 746, 813, 354, 257, 222, 11, 393, 708, 540, 684, 79, 618, 401, 133, 713, 803, 789, 22, 876, 489, 927, 153, 682, 268, 70, 791, 920, 556, 681, 303, 786, 513, 921, 792, 706, 913, 507, 852, 260, 280, 54, 645, 412, 420, 100, 361, 53, 415, 115, 308, 127, 514, 886, 565, 471, 896, 892, 800, 859, 740, 490, 939, 584, 945, 226, 592, 949, 823, 26, 550, 338, 131, 602, 626, 350, 878, 854, 953, 470, 495, 748, 777, 367, 210, 683, 641, 562, 158, 492, 55, 486, 344, 421, 802, 785, 372, 136, 107, 73, 690, 151, 455, 725, 669, 879, 643, 780, 90, 366, 719, 621, 923, 84, 147, 371, 177, 306, 692, 589, 610, 867, 779, 743, 383, 634, 893, 31, 554, 137, 503, 649, 718, 174, 193, 391, 5, 334, 755, 898, 946, 197, 298, 216, 176, 739, 370, 930, 472, 889, 751, 609, 78, 291, 558, 124, 318, 754, 48, 521, 512, 705, 809, 157, 396, 653, 203, 447, 300, 178, 801, 880, 451, 132, 47, 353, 925, 399, 417, 646, 436, 342, 794, 890, 481, 333, 738, 796, 165, 955, 244, 647, 952, 409, 905, 721, 80, 771, 121, 313, 189, 517, 870, 596, 103, 329, 185, 425, 656, 3, 359, 560, 894, 519, 374, 99, 541, 480, 355, 269, 1, 135, 783, 205, 235, 843, 835, 58, 25, 247, 530, 108, 236, 215, 252, 410, 386, 633, 17, 50, 483, 958, 557, 936, 607, 832, 914, 389, 93, 760, 818, 735, 150, 872, 218, 906, 211, 459, 650, 942, 752, 546, 532, 454, 699, 762, 278, 745, 72, 138, 279, 704, 14, 109, 364, 766, 200, 395, 69, 302, 535, 758, 83, 184, 907, 846, 917, 862, 365, 434, 660, 97, 728, 95, 845, 606, 901, 668, 576, 531, 774, 217, 265, 314, 477, 195, 600, 909, 305, 444, 694, 322, 227, 86, 559, 549, 29, 398, 510, 91, 266, 45, 167, 814, 201, 295, 154, 388, 509, 347, 816, 651, 538, 148, 691, 180, 261, 343, 638, 155, 400, 122, 456, 891, 49, 443, 293, 711, 736, 944, 464, 933, 772, 113, 24, 212, 59, 243, 332, 666, 710, 312, 768, 66, 273, 238, 856, 696, 296, 335, 427, 134, 635, 778, 63, 502, 317, 112, 35, 98, 827, 307, 20, 429, 697, 947, 488, 341, 702, 680, 264, 871, 620, 911, 352, 583, 202, 757, 262, 885, 673, 504, 887, 677, 411, 16, 912, 30, 922, 392, 369, 27, 229, 120, 281, 840, 142, 537, 555, 931, 629, 627, 959, 253, 888, 869, 104, 674]
#
# def corr_layers(n=None, layers=None, layer_names=None, statistic='spearman'):
# corr_matrices = []
# a = np.zeros((len(layers),len(layers)))
# corr_between_layers = pd.DataFrame(a, columns=layer_names, index=layer_names)
# # obtain N sentences from each category
# for layer in layers:
# randomN_sentences = pd.DataFrame()
# Nsentences = sentences_index[:n]
# for i in range(len(categories)):
# category_start_number = i*amount_sent
# Nsentences_1category= [n+category_start_number for n in Nsentences]
# randomN_sentences_1category = layer.iloc[Nsentences_1category, :]
# randomN_sentences = pd.concat([pd.DataFrame(randomN_sentences), randomN_sentences_1category],axis=0)
# corr_matrix_lX = randomN_sentences.T.corr(method=statistic)
# corr_matrix_lX_triu = pd.DataFrame(np.triu(corr_matrix_lX, k=1)).replace(0, np.nan)
# corr_matrices.append(corr_matrix_lX_triu)
# for j in range(0,len(layers)):
# for i in range(0,len(layers)):
# res = corr_matrices[j].corrwith(corr_matrices[i]).mean() #TODO: Pearson. correlation between layers. # res = corr_matrices[j].apply(lambda col: col.corr(corr_matrices[i], method=statistic), axis=0)
# corr_between_layers.iloc[j,i] = res
# return corr_between_layers
#
# statistic='spearman'
# sentences = 40
# # layer_names = ['lstm1', 'dense1', 'dense2', 'dense_final', 'softmax_final']
# layer_names = ['conv_1', 'pool_1', 'conv_2', 'pool_2', 'dense_1', 'dense_final', 'softmax_final']
# layers = [conv_1, pool_1, conv_2, pool_2, dense_1, dense_final, softmax_final]
# corr_between_layers1 = corr_layers(n=sentences, layers=layers, layer_names=layer_names)
# random.shuffle(sentences_index)
# corr_between_layers2 = corr_layers(n=sentences, layers=layers, layer_names=layer_names)
#
# with open(path_to_dir + 'log.txt', 'a+') as f:
# f.write('\nCorrelation between layers' +str(sentences)+ 'sentences (spearman)\n')
# f.write(str(corr_between_layers1.round(2)) + '\n')
# f.write('\nCorrelation between layers' +str(sentences)+ 'different sentences (spearman)\n')
# f.write(str(corr_between_layers2.round(2)) + '\n')
# # f.write('\nCorrelation between layers (kendall)\n')
# # f.write(str(corr_between_layers2.round(2)) + '\n')
# # f.write('\nCorrelation between layers (kendall)\n')
# # f.write(str(corr_between_layers2.round(2)) + '\n')
#
# corr_between_layers0 = pd.concat([corr_between_layers1.round(2), corr_between_layers2.round(2)])
# corr_between_layers0.to_csv(path_to_dir+'corr_between_layers0.csv', index=True, header=True)
#
#
#
#
# # path_to_dir = '/Users/danielmlow/Dropbox/cnn/thesis/runs_cluster/cnn10/'
# # RSA_arr_dense_final = np.load(path_to_dir+'RSA_arr_dense_final.npy')
# # layer_name='dense_finalb'
# #
# # from scipy.spatial import distance
# # from scipy.cluster import hierarchy
# # import seaborn as sns
# # # correlations = df.corr()
# # # correlations_array = np.asarray(df.corr())
# #
# # correlations = pd.DataFrame(RSA_arr_dense_final, columns=categories, index=categories)
# # correlations_array = RSA_arr_dense_final[:]
# #
# # row_linkage = hierarchy.linkage(
# # distance.pdist(correlations_array, metric='euclidean'), method='ward', optimal_ordering=True)
# #
# # col_linkage = hierarchy.linkage(
# # distance.pdist(correlations_array.T, metric='euclidean'), method='ward', optimal_ordering=True)
# # #
# # # sns.clustermap(correlations, row_linkage=row_linkage, col_linkage=col_linkage, row_colors=network_colors, method="average",
# # # col_colors=network_colors, figsize=(13, 13), cmap=cmap)
# # sns.set(font_scale=0.5)
# # cg = sns.clustermap(correlations, row_linkage=row_linkage, col_linkage=col_linkage,cmap="RdBu_r", vmin = -0.8, vmax=0.8, cbar_kws={"ticks":[-0.8,-0.4,0.0, 0.4, 0.8]})
# # plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
# # plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
# # cg.savefig(path_to_dir + 'RSA_ward_'+ layer_name + '.eps', format='eps', dpi=100)
# #
# # rsa.plot_rsm(path_to_dir, RSA_arr_dense_final, categories, layer_name='dense_finalb')
#
# conv_1_shape = sequence_length - filter_sizes[0] + 1
# pool_1_shape = int(conv_1_shape/stride_size[0])
# #
# # # TODO: choose short and long sentence from new dataset.
# #
# # for i in range(len(Xvalidation)):
# # length = len(Xvalidation[i].split())
# # if length == 20:
# # print(i)
# # break
#
# # 51 has 10 words, 10 has 20 words
# for sentence_id in [51]:
# for layer, layer_name in zip(layers[:2], layer_names[:2]):
# plt.clf()
# sentence_length = len(Xvalidation[sentence_id].split())
# sentence = np.array(layer.T[sentence_id])
# sns.set(font_scale=0.5)
# if layer_name =='conv_1':
# reshaped = np.reshape(sentence, [conv_1_shape, num_filters])
# elif layer_name =='pool_1':
# reshaped = np.reshape(sentence, [pool_1_shape, num_filters])
# elif layer_name =='conv_2':
# reshaped = np.reshape(sentence, [pool_1_shape-2, num_filters*2])
# elif layer_name =='pool_2':
# reshaped = np.reshape(sentence, [int((pool_1_shape-2)/2), num_filters*2])
# else:
# reshaped = np.reshape(sentence, [1,layer.shape[1]])
# cg = sns.heatmap(reshaped, cmap="RdBu_r", vmin=-1., vmax=1.,
# cbar_kws={"ticks": [-1., -0.5, 0.0, 0.5, 1.0]})
# # cg = sns.heatmap(reshaped, cmap="RdBu_r")
# # cg = sns.heatmap(reshaped, cmap="Reds")
# plt.xticks(rotation=90)
# plt.ylabel('Words')
# plt.yticks(rotation=0)
# plt.xlabel('Filters/Channels')
# plt.title(layer_name+' - Single Sentence \n')
# plt.savefig(path_to_dir+'single_sent_heatmap_'+layer_name+'_'+str(sentence_length)+'words.png')
#
# # TODO: careful when using layer[-1] because I want to use dense_final[-2] not softmax_final [-1]
# df_prototypical, df_prototypical_score, df_prototypical_sentences = corr_between_layers.prototypical_sentences(statistic, Xvalidation,Xvalidation_raw, path_to_dir, layer=layers[-2], validation_size= len(Xvalidation), amount_sent=int(len(Xvalidation)/len(categories)),nan='', categories=categories)
#
# if plot_RSA:
# # rsa.plot_RSA(path_to_dir, categories, layer=conv_1, layer_name='conv_1',
# # amount_sent=int(conv_1.shape[0] / len(categories)))
# # rsa.plot_RSA(path_to_dir, categories, layer=pool_1, layer_name='pool_1',
# # amount_sent=int(conv_1.shape[0] / len(categories)))
# # rsa.plot_RSA(path_to_dir, categories, layer=conv_2, layer_name='conv_2', amount_sent=int(conv_1.shape[0]/len(categories)))
# # rsa.plot_RSA(path_to_dir, categories, layer=pool_2, layer_name='pool_2',
# # amount_sent=int(conv_1.shape[0] / len(categories)))
# rsa.plot_RSA(path_to_dir, categories, layer=dense_1, layer_name='dense_1', amount_sent=int(conv_1.shape[0]/len(categories)))
# rsa.plot_RSA(path_to_dir, categories, layer=dense_final, layer_name='dense_final',
# amount_sent=int(len(Xvalidation) / len(categories)))
# rsa.plot_RSA(path_to_dir, categories, layer=softmax_final, layer_name='softmax_final',
# amount_sent=int(len(Xvalidation)/ len(categories)))
# # rsa.plot_RSA(path_to_dir, categories, layer=dense_general, layer_name='dense_general',amount_sent=int(conv_1.shape[0] / len(categories)))
# # rsa.plot_RSA(path_to_dir, categories, layer=softmax_final_sigmoid, layer_name='softmax_final_sigmoig')
# # rsa.plot_RSA(path_to_dir, categories, layer=softmax_final_elu, layer_name='softmax_final_elu')
#
#
# # def Nsentences_a_k_length(n,a, k, layer, amount_sent_per_category, Xvalidation):
# # layer_sample = pd.DataFrame()
# # for i in range(0,layer.shape[0], amount_sent_per_category):
# # n_sentences_same_length = pd.DataFrame()
# # sentences = 0
# # # loop through sentences in categories
# # for j in range(i,i+amount_sent_per_category):
# # if (len(Xvalidation[j].split())>=a & len(Xvalidation[j].split())<=k):
# # n_sentences_same_length = n_sentences_same_length.append(layer.T[j])
# # sentences+=1
# # if sentences == n:
# # print('a category does not have enough')
# # break
# # if n_sentences_same_length.shape[0] < n:
# # print('not enough sentences of that length. Try again.')
# # break
# # else:
# # layer_sample = layer_sample.append(n_sentences_same_length)
# # return layer_sample
#
#
# def Nsentences(n, layer, amount_sent_per_category):
# layer_sample = pd.DataFrame()
# for i in range(0,layer.shape[0], amount_sent_per_category):
# n_sentences_1category = layer.iloc[i:i+amount_sent_per_category]
# n_sentences_1category = n_sentences_1category.sample(frac=1).iloc[:n]
# layer_sample = layer_sample.append(n_sentences_1category)
# return layer_sample
#
# # RSA single sentences
# # =====================================================================================================================================
# amount_sent_per_category = int(len(Xvalidation)/len(categories))
# n = 5
#
# layer_names = ['conv_1', 'pool_1', 'conv_2', 'pool_2','dense_1' ,'dense_final', 'softmax_final']
# for layer, layer_name in zip(layers, layer_names):
# # layer_sample = Nsentences_a_k_length(n, 10, 14, layer, amount_sent_per_category, Xvalidation)
# layer_sample = Nsentences(n, layer, amount_sent_per_category)
# # Clustermap
# df = pd.DataFrame(layer_sample)
# # df[(df >= -0.08) & (df <= 0.09)] = np.nan
# statistic = 'spearman'
# df = df.T.corr(method=statistic)
# columns = [[i] * n for i in categories] # TODO: categories or categories_wrong.
# # columns = [[i]*n for i in config.categories_wrong]
# columns = [i for j in columns for i in j]
# df.columns = columns
# df.index = columns
# sns.set(font_scale=0.08)
# cg = sns.clustermap(df, method='ward', cmap="RdBu_r", vmin=-1., vmax=1.,cbar_kws={"ticks": [-1., -0.5, 0.0, 0.5, 1.0]})
# plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0, )
# plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
# # tick_locator = ticker.MaxNLocator(int(df.shape[0]))
# # plt.setp(cg.ax_heatmap.xaxis.set_major_locator(tick_locator))
# # plt.setp(cg.ax_heatmap.yaxis.set_major_locator(tick_locator))
# cg.savefig(path_to_dir+ '/RSA_ward_clustermap_' + layer_name + '_single_sentences_'+statistic+'.eps', format='eps', dpi=100)
#
# # With NaNs just first two layers
# for layer, layer_name in zip(layers[:2], layer_names[:2]):
# # layer_sample = Nsentences_a_k_length(n, 10, 14, layer, amount_sent_per_category, Xvalidation)
# layer_sample = Nsentences(n, layer, amount_sent_per_category)
# # Clustermap
# df = pd.DataFrame(layer_sample)
# df[(df >= -0.09) & (df <= 0.09)] = np.nan
# statistic = 'spearman'
# df = df.T.corr(method=statistic)
# columns = [[i] * n for i in categories] # TODO: categories or categories_wrong.
# # columns = [[i]*n for i in config.categories_wrong]
# columns = [i for j in columns for i in j]
# df.columns = columns
# df.index = columns
# sns.set(font_scale=0.08)
# try:
# cg = sns.clustermap(df, method='ward', cmap="RdBu_r", vmin=-1., vmax=1.,
# cbar_kws={"ticks": [-1., -0.5, 0.0, 0.5, 1.0]})
# plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0, )
# plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
# # tick_locator = ticker.MaxNLocator(int(df.shape[0]))
# # plt.setp(cg.ax_heatmap.xaxis.set_major_locator(tick_locator))
# # plt.setp(cg.ax_heatmap.yaxis.set_major_locator(tick_locator))
# cg.savefig(path_to_dir+ '/RSA_ward_clustermap_' + layer_name + '_single_sentences_'+statistic+'_with_NaNs.eps', format='eps', dpi=100)
# except:
# pass
#
#
# layer_names = ['conv_1_nans', 'pool_1_nans', 'conv_2_nans', 'pool_2_nans', 'dense_final_nans']
# layers_nans=[]
# for layer, layer_name in zip(layers, layer_names):
# df = pd.DataFrame(layer)
# df[(df>=-0.09) & (df<=0.09)] = np.nan
# layers_nans.append(df)
# with open(path_to_dir + 'log.txt', 'a+') as f:
# f.write(layer_name+': amount of nans: ')
# f.write(str(df.isnull().sum().sum())+ ' ')
# f.write('rel. amount: '+str((df.isnull().sum().sum()/(df.shape[0]*df.shape[1])).round(2)))
# f.write('\n')
# # rsa.plot_RSA(path_to_dir, categories, layer=df, layer_name=layer_name, amount_sent=int(layer.shape[0]/len(categories)))
#
# #
# # corr_between_layers1 = corr_between_layers.corr_between_layers_method(statistic,models,layers_nans,config.save_to,Xvalidation, categories,nan='with_nans_', model_type=file_name)
# #
#
# # corr_between_layers1 = corr_layers(n_random_sentences, df_prototypical,layers, df_prototypical_sentences, layer_names, statistic, categories=categories)
#
# def Nsentences_Klength(n, sentence_length, layer, amount_sent_per_category, Xvalidation):
# layer_sample = pd.DataFrame()
# for i in range(0,layer.shape[0], amount_sent_per_category):
# n_sentences_same_length = pd.DataFrame()
# sentences = 0
# # loop through sentences in categories
# for j in range(i,i+amount_sent_per_category):
# if len(Xvalidation[j].split())==sentence_length:
# n_sentences_same_length = n_sentences_same_length.append(layer.T[j])
# sentences+=1
# if sentences == n:
# break
# if n_sentences_same_length.shape[0] < n:
# print('not enough sentences of that length. Try again.')
# break
# else:
# layer_sample = layer_sample.append(n_sentences_same_length)
# return layer_sample
#
# for layer, layer_name in zip(layers[:2], layer_names[:2]):
# amount_sent_per_category = int(len(Xvalidation)/len(categories))
# n = 5
# k = [8,28]
# layer_sample_small = Nsentences_Klength(n, k[0], layer, amount_sent_per_category, Xvalidation)
# layer_sample_large = Nsentences_Klength(n, k[1], layer, amount_sent_per_category, Xvalidation)
# statistic = 'spearman'
# sentences_from_each = len(categories)*n
# layer_sample = pd.concat([layer_sample_small, layer_sample_large])
# df = pd.DataFrame(layer_sample)
# df = df.T.corr(method=statistic) #TODO: should I transpose like this?
# df.index= range(0,sentences_from_each*2)
# df.columns= range(0,sentences_from_each*2)
# df_triu = pd.DataFrame(np.triu(df, k=1)).replace(0, np.nan)
#
# zeros = pd.DataFrame(np.ones([sentences_from_each,sentences_from_each]))
# a15 = pd.DataFrame(np.full([sentences_from_each, sentences_from_each], 20))
# sentence_len1 = pd.concat([zeros, a15])
# sentence_len2 = pd.concat([a15, zeros])
# sentence_len = pd.concat([sentence_len1 ,sentence_len2], axis=1)
# sentence_len.index=range(sentences_from_each*2)
# sentence_len.columns=range(sentences_from_each*2)
# sentence_len_triu= pd.DataFrame(np.triu(sentence_len, k=0)).replace(0, np.nan)
# sentence_len_triu = sentence_len_triu.replace(1,0)
# # zeros = pd.DataFrame(np.zeros([3,3]))
# # a15 = pd.DataFrame(np.full([3, 3], 15 ))
# # sentence_len.to_csv(output_dir+'sentence_len_distance_matrix.csv', header=False, index=False)
# # sentence_len_triu.to_csv(output_dir+'sentence_len_distance_matrix.csv', header=False, index=False)
#
# with open(path_to_dir + 'log.txt', 'a+') as f:
# f.write('Sentence_len_triu_dist effect '+layer_name+' '+str(k)+': \n')
# f.write(str(sentence_len_triu.corrwith(df_triu).mean())+'\n')
# f.write(str(categories)+'\n')
#
#
#
|
python
|
#!/usr/bin/env python
import os
import sqlite3
import cherrypy
from collections import namedtuple
import tweepy
import random
import twitterkeys
# setup twitter authentication and api
twitter_auth = tweepy.OAuthHandler(twitterkeys.consumer_key, twitterkeys.consumer_secret)
twitter_auth.set_access_token(twitterkeys.access_key, twitterkeys.access_secret)
twitter_api = tweepy.API(twitter_auth)
database_file = 'sentiments.db'
def namedtuple_select(table, nt_type):
return "SELECT %s FROM %s" % (",".join(nt_type._fields), table)
class TweetRecord(namedtuple("TweetRecord", "id, status, message, message_p, q")):
""" Helper for twitter records """
@classmethod
def _empty(cls):
return TweetRecord(**dict(zip(TweetRecord._fields, [None] * len(TweetRecord._fields))))
class SentimentRecord(namedtuple("SentimentRecord", "id, username, sentiment, energy")):
""" Helper for sentiment records """
@classmethod
def _empty(cls):
return SentimentRecord(**dict(zip(SentimentRecord._fields, [None] * len(SentimentRecord._fields))))
class database:
""" Helper for database connections """
def __enter__(self):
self.conn = sqlite3.connect(database_file)
return self.conn
def __exit__(self, type, value, traceback):
if value is None:
self.conn.commit()
self.conn.close()
class Sentimentor(tweepy.StreamListener):
""" Handles twitter interfacing and sentiment retrieval/sending """
def __init__(self, api=None):
super(Sentimentor, self).__init__(api=api)
self.stream = None
self.q = None
self.lang = None
self.counter = 0
def load_ids(self):
if not hasattr(self, "ids"):
with database() as db:
self.ids = [ int(x[0]) for x in db.cursor().execute("SELECT id FROM tweets").fetchall() ]
return self.ids
def start_receiving(self, q, lang='en'):
""" Start receiving new tweets from twitter for the given query """
self.q = [ x.strip() for x in q.split(",") ]
if len(self.q) == 0:
raise ValueError("Query required")
self.lang = lang
self.counter = 0
self.stream = tweepy.Stream(auth=twitter_api.auth, listener=self)
self.stream.filter(track=self.q, async=True, languages=[self.lang])
def stop_receiving(self):
""" Stop receiving tweets """
if self.stream is not None:
self.stream.disconnect()
self.stream = None
if hasattr(self, "ids"):
del self.ids # rebuild cache
def on_status(self, status):
""" Handle new message """
print "- received:", status.text, "lang:", status.lang
if status.lang == self.lang and status.retweeted is False: # avoid retweets
with database() as db:
sql = "INSERT INTO tweets (message, q) VALUES (?, ?)"
data = (status.text, ",".join(self.q))
db.cursor().execute(sql, data)
self.counter += 1
def on_error(self, status_code):
""" Handle error from twitter """
print "Got Twitter error code", status_code, "stopping stream."
self.stop_receiving()
return False
def on_exception(self, e):
print "Exception", e.message
self.stop_receiving()
def load_next(self, username=None):
with database() as db:
c = db.cursor()
c.execute("SELECT id FROM sentiments WHERE username = ?", (username,))
completed_ids = [ int(x[0]) for x in c.fetchall() ]
incomplete = set(self.load_ids())
incomplete.difference_update(completed_ids)
# print "incomplete", incomplete
# print "completed", completed_ids
if len(incomplete) < 1:
return None
next_id = random.sample(incomplete, 1)[0]
return TweetRecord._make(c.execute("SELECT * FROM tweets WHERE id = ?", (next_id,)).fetchone())._asdict()
def save_sentiment(self, tweets_id, username, sentiment, energy=1):
sql = "INSERT INTO sentiments (id, username, sentiment, energy) VALUES (?, ?, ?, ?)"
data = (tweets_id, username, sentiment, energy)
with database() as db:
db.cursor().execute(sql, data)
class MainPage(object):
def __init__(self):
self.s = Sentimentor(twitter_api)
@cherrypy.expose()
@cherrypy.tools.json_out()
def tweet(self, username):
return self.s.load_next(username)
@cherrypy.expose()
@cherrypy.tools.json_out()
def start(self, q, lang='en'):
self.s.start_receiving(q, lang)
return {"status": "Running"}
@cherrypy.expose()
def stop(self):
self.s.stop_receiving()
@cherrypy.expose()
@cherrypy.tools.json_out()
def status(self):
if self.s.stream is not None:
return {"status": "running", "q": self.s.q, "lang": self.s.lang, "counter": self.s.counter}
else:
return {"status": "stopped"}
@cherrypy.expose()
def sentiment(self, tweet_id, username, sentiment, energy=1):
self.s.save_sentiment(tweet_id, username, sentiment, energy)
if __name__ == "__main__":
""" Main entry of program """
""" configure cherrypy """
cherrypy.config.update({
"server.socket_host": "127.0.0.1",
"server.socket_port": 5001
})
public_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "public")
conf = {
"/": {
"tools.staticdir.root": public_path,
},
"/public": {
"tools.staticdir.on": True,
"tools.staticdir.dir": public_path,
}
}
""" startup cherrypy """
cherrypy.quickstart(MainPage(), "/", conf)
|
python
|
#!/usr/bin/env python3
import xml.etree.ElementTree as ET
CSPROJ_FILE = 'Uri/Uri.csproj'
ENV_VARIABLE_FILE = '.env'
ENV_VARIABLE_NAME = 'URI_VERSION'
csproj_tree = ET.parse(CSPROJ_FILE)
version_tag = csproj_tree.getroot().find('PropertyGroup').find('Version')
version_parts = version_tag.text.split('.', 2)
version_parts[-1] = str(int(version_parts[-1]) + 1)
new_version = '.'.join(version_parts)
with open(ENV_VARIABLE_FILE, 'w') as f:
f.write(ENV_VARIABLE_NAME + '=' + new_version + '\n')
version_tag.text = new_version
csproj_tree.write(CSPROJ_FILE, encoding='UTF-8')
with open(CSPROJ_FILE, 'a') as f:
f.write('')
|
python
|
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
stack = []
for num in nums2:
stack.append(num)
while len(stack) >= 2:
if stack[-1] > stack[-2]:
dic[stack[-2]] = stack[-1]
tmp = stack.pop()
stack.pop()
stack.append(tmp)
else:
break
return [dic.get(num, -1) for num in nums1]
### cleaned version
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
stack = []
for num in nums2:
while stack and num > stack[-1]:
dic[stack.pop()] = num
stack.append(num)
return [dic.get(num, -1) for num in nums1]
|
python
|
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from torch.nn import BatchNorm1d
from ncc.models import register_model
from ncc.models.ncc_model import (
NccEncoder,
NccEncoderModel,
)
from ncc.modules.base.layers import (
Embedding,
Linear,
)
class DeepTuneEncoder(NccEncoder):
def __init__(self, dictionary, embed_dim,
# rnn config
rnn_cell, rnn_hidden_dim, rnn_dropout=None,
rnn_num_layers=2, rnn_bidirectional=False,
# auxiliary input
aux_dim=2,
inner_dim=32, out_dim=2,
):
super(DeepTuneEncoder, self).__init__(dictionary)
self.embed = Embedding(len(dictionary), embed_dim)
# LSTM
self.rnn_dropout = rnn_dropout
self.rnn = getattr(nn, str.upper(rnn_cell))(
embed_dim, rnn_hidden_dim, num_layers=rnn_num_layers,
dropout=self.rnn_dropout, # rnn inner dropout between layers
bidirectional=rnn_bidirectional, batch_first=True,
)
self.src_out_proj = nn.Sequential(
Linear(rnn_hidden_dim, out_dim),
nn.Sigmoid(),
)
# Auxiliary inputs. wgsize and dsize
self.bn = BatchNorm1d(rnn_hidden_dim + aux_dim)
self.hybrid_out_proj = nn.Sequential(
Linear(rnn_hidden_dim + aux_dim, inner_dim),
nn.ReLU(),
Linear(inner_dim, out_dim),
nn.Sigmoid(),
)
def forward(self, src_tokens, src_lengths=None, src_aux=None, **kwargs):
src_embed = self.embed(src_tokens)
src_embed, _ = self.rnn(src_embed)
src_embed = src_embed[:, -1, :] # get the last hidden state at last RNN layer
src_out = self.src_out_proj(src_embed)
hybrid_embed = torch.cat([src_aux, src_embed], dim=-1)
hybrid_embed = self.bn(hybrid_embed)
hybrid_out = self.hybrid_out_proj(hybrid_embed)
return hybrid_out, src_out
@register_model('deeptune')
class DeepTune(NccEncoderModel):
def __init__(self, args, encoder):
super(DeepTune, self).__init__(encoder)
self.args = args
@classmethod
def build_model(cls, args, config, task):
encoder = DeepTuneEncoder(
dictionary=task.source_dictionary,
embed_dim=args['model']['code_embed'],
rnn_cell=args['model'].get('rnn_cell', 'LSTM'),
rnn_hidden_dim=args['model']['rnn_hidden_dim'],
rnn_num_layers=args['model']['rnn_layers'],
rnn_dropout=args['model']['rnn_dropout'],
rnn_bidirectional=args['model'].get('rnn_bidirectional', False),
aux_dim=args['model'].get('aux_dim', 2),
inner_dim=args['model']['inner_dim'],
out_dim=len(task.target_dictionary),
)
return cls(args, encoder)
def forward(self, src_tokens, src_lengths, **kwargs):
return self.encoder.forward(src_tokens, src_lengths, **kwargs)
|
python
|
# MAP WARMPUP
# Given the two lists of numbers below, produce a new iterable of their element-wise sums
# In this example, that'd be (21, 33, 3, 60...)
# Hint: look for a `from operator import ...`
one = [1, 2, 3, 40, 5, 66]
two = [20, 31, 0, 20, 55, 10]
# FILTER WARMPUP
# Take the following iterable, and filter out / remove any `(x, y)` elements where `x` is greater than `y`
# It's fine to use a lambda on this one
from itertools import count
b_iterable = enumerate(count(30, 4), start=500)
# Given the below iterable, produce a generator containing ONLY the next element of each iterator in the iterable
# For this example, that'd be (900, 4, 10, 0)
# Hint: the most important word in the above sentences was "next"
iterables = [
(x**2 for x in range(30, 40)),
(x**x for x in range(2, 10)),
(x-4 for x in [14, 3, 11]),
iter(range(20))
]
# Take the following iterable, and filter out / remove ALL `(x, y)` elements where `x` is LESS than `y`. Convert the result to a list.
# Hint: you'll want `from itertools import takewhile`, instead of just `filter`
from itertools import count
a_iterable = enumerate(count(30, 4), start=500)
|
python
|
"""
This is templates for common data structures and algorithms.
Frequently used in my leetcode practices.
"""
"""
Binary search
"""
nums, target
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
# might need modification to fit the problem.
if nums[mid] < target:
left = mid
elif nums[mid] > target:
right = mid
"""
Two-pointer
"""
"""
Manacher's algorithm: find longest palindromic substring
"""
"""
Voting: Boyer-Moore alg: find majority element
array A, find the element that appears more than n // 2 times.
"""
majority, count = None, 0
for num in A:
if count == 0:
majority, count = num, 1
elif num == majority:
count += 1
else:
count -= 1
# check again if majority is valid.
if sum(1 for num in A if num == majority) <= len(A) // 2:
majority = None
"""
quick select
"""
# for kth smallest item.
def quick_select(nums, begin, end, k):
# find the k+1th smallest element, whose idx == k.
if begin == end:
return nums[begin]
pivot_idx = partition(nums, begin, end)
if k == pivot_idx:
return nums[k]
if k < pivot_idx: # find in left side
return quick_select(nums, begin, pivot_idx - 1, k)
return quick_select(nums, pivot_idx + 1, end, k)
def partition(nums, begin, end):
# could choose any pivot, even with randomness
pivot_idx = (begin + end) // 2
pivot_val = nums[pivot_idx]
nums[pivot_idx], nums[end] = nums[end], nums[pivot_idx]
# scan from `begin` to `end`-1, only leave elements smaller
# than `pivot_val` on the left side.
write_pos = begin
for i in range(begin, end):
if nums[i] < pivot_val:
nums[i], nums[write_pos] = nums[write_pos], nums[i]
write_pos += 1
# move the pivot back to where it should be.
nums[write_pos], nums[end] = nums[end], nums[write_pos]
return write_pos
"""
BST iterator (generator function, class)
"""
def bst_itertor(root):
stack = []
node = root
while node:
stack.append(node)
node = node.left
while len(stack) > 0:
yield stack[-1]
node = stack.pop()
if node.right:
node = node.right
while node:
stack.append(node)
node = node.left
continue
# else
while len(stack) > 0 and stack[-1].right == node:
node = stack.pop()
class BSTIterator:
def __init__(self, root):
self.stack = []
node = root
while node:
self.stack.append(node)
node = node.left
def hasNext(self):
return len(self.stack) > 0
def peak(self):
return self.stack[-1]
def next(self):
node = self.stack.pop()
ret = node
if node.right:
# goto the right subtree, then go all the way to left.
node = node.right
while node:
self.stack.append(node)
node = node.left
else:
# node is rightmost. go to the ancestor that `node` is in its left subtree.
while len(self.stack) > 0 and self.stack[-1].right == node:
node = self.stack.pop()
return ret
"""
Represent a Graph (with built-in types)
"""
edges = defaultdict(list)
# for example, edges[u] = [v1, v2, v3]
# there exist edges from `u` to `v1`, `v2`, `v3`.
"""
BFS
"""
from collections import deque
visited = set()
queue = deque()
queue.append(root)
visited.add(root)
while len(queue) > 0:
node = queue.popleft()
print(node)
for ne in node.neighbors:
if ne not in visited:
queue.append(ne)
"""
DFS, preorder, inorder postorder
"""
def inorder(node, order):
if node is None:
return
order.append(node.val)
inorder(node.left)
inorder(node.right)
order = []
inorder(root, order)
# This is a common trick to collect results with recursion.
# list are mutable in python, so all recusion calls will
# operate on the same instance of list.
"""
Combinations & Permutation
usually works when the problem asks for every solution.
"""
# iterators for combinations, permuations, ...
from itertools import product, permutations
# combination
def search(nums, pos, combo, solutions):
# termination condition
if done:
solutions.append()
return
while pos < len(nums):
combo.append(nums[pos])
search(nums, pos+1, combo, solutions)
combo.pop()
pos += 1
# permutation
def search(nums, visited, perm, solutions):
# termination condition
if done:
solutions.append()
return
for i in range(len(nums)):
if i in visited:
continue
visited.add(i)
perm.append(nums[i])
search(nums, visited, perm, solutions)
visited.remove(i)
perm.pop()
"""
Heap / Priority Queue
- insert(H, x): O(log n)
- extract_min(H): O(1) amortized
- decrease_key(H, x, k): O(log n)
- meld(H1, H2): O(n)
- find_min(H, x): O(1)
- delete(H, x): O(log n)
"""
import heapq
# default is min heap. to use a max heap, invert the numbers.
# we could also use a tuple to store objects. first element of
# tuple will be used for comparison.
# obtain heap from existing iterable.
unordered_list = [6,3,9,4,2]
heapq.heapify(unordered_list)
# built heaps
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 9)
heapq.heappush(heap, 6)
heapq.heappop(heap)
heapq.nsmallest(list, )
# sometimes the ordering rule for a data structure might be
# a bit complicated. We could create a class for the specidfic
# ordering rule.
class HeapNode:
def __init__(val1, val2):
self.val1 = val1
self.val2 = val2
def __lt__(self, other):
if self.val1 < other.val1:
return True
return self.val2 > other.val2
"""
Union Find
- make_set(x): O(1)
- find(x): m O(log* n) (where m: total # of operations, n: # of elements)
- union(x, y): same as find(x, y)
"""
class Node:
def __init__(self, val):
self.val = val
class UnionFind:
def __init__(self):
self.node_2_parent = {}
self.node_2_rank = {}
def make_set(x):
self.node_to_parent[x] = x
self.node_to_rank[x] = 0
def find(x):
if self.node_2_parent[x] != x:
self.node_2_parent[x] = self.find(self.node_2_parent[x])
return self.node_2_parent[x]
def union(x, y):
x_repr, y_repr = self.find(x), self.find(y)
if x_repr == y_repr:
return
x_rank, y_rank = self.node_2_rank[x_repr], self.node_2_rank[y_repr]
if x_rank > y_rank:
self.node_2_parent[y_repr] = x_repr
elif x_rank < y_rank:
self.node_2_parent[x_repr] = y_repr
else:
self.node_2_parent[y_repr] = x_repr
self.node_2_rank[x_repr] += 1
uf = UnionFind()
uf.make_set(1)
uf.make_set(2)
uf.make_set(3)
uf.make_set(4)
uf.union(1,3)
print(uf.find(2) == uf.find(4))
print(uf.find(1) == uf.find(3))
"""
Trie
"""
class TrieNode:
def __init__(self, char):
self.char = char
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode(None)
def add_word(self, word):
node = self.rot
for char in word:
if char in node.children:
node = node.children[char]
else:
new_node = TrieNode(char)
node.children[char] = new_node
node = new_node
node.is_word = True
|
python
|
from __future__ import (absolute_import, division,print_function, unicode_literals)
from builtins import *
import numpy as np
import cv2
import SimpleITK as sitk
from builtins import *
from scipy.spatial import distance
from scipy import stats
import sys
import time
############### FUNCTIONS ##########################
def imcomplement(im):
if np.max(im)>1:
imout=255-im
else:
imout=1-im
return imout
def mat2gray(img):
max_img=np.max(img)
min_img=np.min(img)
imgout=(img-min_img)/(max_img-min_img)
return imgout
def im2double(img):
imgout=img.astype('float32')
imgout= mat2gray(imgout)
return imgout
def imreconstruct(marker,mask):
markeritk=sitk.GetImageFromArray(marker)
maskitk=sitk.GetImageFromArray(mask)
recfilt=sitk.ReconstructionByDilationImageFilter()
rectoutitk=recfilt.Execute(markeritk,maskitk)
rectout=sitk.GetArrayFromImage(rectoutitk)
return rectout
def eigen_cov(x,y):
mx=np.mean(x)
my=np.mean(y)
x=x-mx
y=y-my
cxx=np.var(x)
cxy=0
cyy=np.var(y);
nx=len(x)
for ct in range(nx):
cxy=cxy+x[ct]*y[ct];
cxy=cxy/nx;
C=np.zeros((2,2))
C[0,0]=cxx
C[0,1]=cxy
C[1,0]=cxy
C[1,1]=cyy
D,V=np.linalg.eig(C)
return V,D
def is_inside(img,x,y):
x=int(x)
y=int(y)
if(x>0 and y>0 and x<img.shape[1] and y<img.shape[0]):
return True
else:
return False
def improfile(img,x,y,n):
xm=x[0]
x0=x[1]
ym=y[0]
y0=y[1]
a = np.arctan((y0 - ym) / (x0 - xm))
i=range(0,100,int(100/n))
cx=np.squeeze(np.zeros((1,len(i))))
cy=np.squeeze(np.zeros((1,len(i))))
c=np.squeeze(np.zeros((1,len(i))))
ct=0
for t in range(0,100,int(100/30)):
tf=t/100.0
cx[ct] = int(xm + (x0 - xm)*tf)
cy[ct] = int(ym + (y0 - ym)*tf)
if(is_inside(img,cx[ct],cy[ct])):
c[ct]=img[int(cy[ct]), int(cx[ct])]
else:
c[ct]=1;
ct=ct+1
return c,cx,cy
def filter_result3(img,bw_result,ths,thm):
bw_result_orig=np.copy(bw_result);
points=np.where(bw_result>0)
points=np.reshape(points,np.shape(points))
points=np.transpose(points)
npoints=np.shape(points)[0]
k=20
step=5
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
sat=hsv[:,:,1]/255
bw_result_filter=np.zeros(np.shape(bw_result))
xc=points[:,1]
yc=points[:,0]
for ct in range(0,npoints,step):
#print(ct/npoints)
ystart=max(0,yc[ct]-k);
xstart=max(0,xc[ct]-k);
yend=min(np.shape(img)[0],yc[ct]+k);
xend=min(np.shape(img)[1],xc[ct]+k);
p=points[ct,:]
p=np.reshape(p,(1,2))
Dpoints=distance.cdist(p,points)
Dpoints=np.squeeze(Dpoints)
ipoints=np.squeeze(np.where(Dpoints<40))
xneigh=points[ipoints,1];
yneigh=points[ipoints,0];
V,D=eigen_cov(xneigh,yneigh)
vmin=V[:,0];
if D[1]<D[0]:
vmin=V[:,1];
x1=xc[ct]-k*vmin[0];
y1=yc[ct]-k*vmin[1];
x2=xc[ct]+k*vmin[0];
y2=yc[ct]+k*vmin[1];
p,px,py=improfile(sat,np.array([x1,x2]),np.array([y1,y2]),30);
s=np.abs(np.mean(p[0:5])-np.mean(p[len(p)-5:len(p)]));
s=round(s*100);
m=np.max([p[0:5],p[len(p)-5:len(p)]]);
if(s<ths and m<thm):
bw_result_filter[ystart:yend,xstart:xend]=bw_result_orig[ystart:yend,xstart:xend];
return bw_result_filter
def min_openings(im,LEN,DEG_NUM):
imo=[];
for i in range(DEG_NUM):
#DEG=(i)*((360/DEG_NUM)/2)
filtername=str(i+1)+'se.txt'
se=np.loadtxt('filters/videos/filters/'+filtername)
if(i==0):
se=np.reshape(se,(1,len(se)))
if(i==6):
se=np.reshape(se,(len(se),1))
se=se.astype('uint8')
imoi=cv2.erode(im,se)
imoi=cv2.dilate(imoi,se)
imo.append(imoi)
imB=imo[0]
for i in range(DEG_NUM-1):
k=i+1
imB=np.minimum(imB,imo[k])
return imB
def smooth_cross_section(imV,LEN_diff,DEG_NUM):
imV_c=imcomplement(imV)
imd=[]
for i in range(12):
k=i+1
se1=np.loadtxt('filters/videos/filters/'+str(k)+'linekernel1.txt')
se2=np.loadtxt('filters/videos/filters/'+str(k)+'linekernel2.txt')
if(i==0):
se1=np.reshape(se1,(1,len(se1)))
se2=np.reshape(se2,(len(se2),1))
if(i==6):
se1=np.reshape(se1,(len(se1),1))
se2=np.reshape(se2,(1,len(se2)))
temp=cv2.filter2D(imV_c.astype('float32'),-1,se1)
imdi=cv2.filter2D(temp,-1,se2)
imdi[imdi<0]=0
imd.append(imdi)
imDiff=imd[0]
for i in range(11):
k=i+1
imDiff=np.maximum(imDiff,imd[k])
imDiff=mat2gray(imDiff)
return imDiff
def reconstruction_by_dilation(im,LEN,DEG_NUM):
imo=[];
for i in range(DEG_NUM):
#DEG=(i)*((360/DEG_NUM)/2)
filtername=str(i+1)+'se.txt'
se=np.loadtxt('filters/videos/filters/'+filtername)
if(i==0):
se=np.reshape(se,(1,len(se)))
if(i==6):
se=np.reshape(se,(len(se),1))
se=se.astype('uint8')
imoi=cv2.erode(im,se)
imoi=cv2.dilate(imoi,se)
imo.append(imoi)
imC=imo[0]
for i in range(DEG_NUM-1):
k=i+1
imC=np.maximum(imC,imo[k])
imC2=imreconstruct(imC,im)
imC2=mat2gray(imC2)
return imC2
def reconstruction_by_erosion(im,LEN,DEG_NUM):
im_close=[];
for i in range(DEG_NUM):
#DEG=(i)*((360/DEG_NUM)/2)
filtername=str(i+1)+'se.txt'
se=np.loadtxt('filters/videos/filters/'+filtername)
if(i==0):
se=np.reshape(se,(1,len(se)))
if(i==6):
se=np.reshape(se,(len(se),1))
se=se.astype('uint8')
im_closei=cv2.dilate(im,se)
im_closei=cv2.erode(im_closei,se)
im_close.append(im_closei);
imTemp39=im_close[0]
for i in range(DEG_NUM-1):
k=i+1
imTemp39=np.minimum(imTemp39,im_close[k])
marker=imcomplement(imTemp39)
mask=imcomplement(im)
imF=imreconstruct(marker,mask)
imF=mat2gray(imF)
imF=imcomplement(imF)
return imF
def find_th(x):
#mode= stats.mode(x)
(_, idx, counts) = np.unique(x, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mx = x[index]
sx=np.std(x)
thl=mx+3*sx
thh=mx+4*sx
return thl,thh
############ MAIN ##############
if len(sys.argv)<3:
print('example usage : python crack_detection2 images_milestone2/1.jpg 50 ( optional images_milestone2/output/1.jpg)')
width_cm=int(sys.argv[2])
if len(sys.argv)==5:
img_file_out=sys.argv[3]
img_file_out_bin=sys.argv[4]
else:
img_file_out='/Applications/XAMPP/xamppfiles/htdocs/bd/uploads/raw/output.png'
img_file_out_bin='/Applications/XAMPP/xamppfiles/htdocs/bd/uploads/raw/output_bin.png'
img_file=sys.argv[1]
print('processing '+img_file)
imgorig=cv2.imread(img_file)
start_time = time.time()
size_orig=np.shape(imgorig)
print(size_orig)
## resize if the original size is different from dataset images
## so we can keep the same parameters for the filters
res=size_orig[1]/float(width_cm);
res_opt=65; # optimal resolution for bilateral filter
scale = float(res_opt)/float(res);
print(scale)
d=int(51/scale)
sigmaColor=int(201)
sigmaSpace =int(201/scale);
if scale < 5:
resize_scale=1.8
rows_dataset=int(2448/resize_scale)
cols_dataset=int(3264/resize_scale)
img_blur = cv2.bilateralFilter(cv2.resize(imgorig,(cols_dataset,rows_dataset)) ,int(d/resize_scale),sigmaColor,int(sigmaSpace/resize_scale))
img_blur=cv2.resize(img_blur,(size_orig[1],size_orig[0]))
#img_blur = cv2.bilateralFilter(imgorig ,d,sigmaColor,sigmaSpace)
else:
img_blur =imgorig
##
print("bilateral filter --- %s seconds ---" % (time.time() - start_time))
res_opt=16 # optimal resolution for bilateral filter
scale = float(res_opt)/float(res)
img=cv2.resize(img_blur,(int(size_orig[1]*scale),int(size_orig[0]*scale)))
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
im=hsv[:,:,2]
bw_mask=np.zeros(np.shape(im))
bw_mask_offr=0;#round(np.shape(im)[0]/20)
bw_mask_offc=0;#round(np.shape(im)[1]/20)
bw_mask[bw_mask_offr:np.shape(im)[0]-bw_mask_offr, bw_mask_offc:np.shape(im)[1]-bw_mask_offc]=1;
im=mat2gray(im) #*mat2gray(bw_mask)
im=imcomplement(im)
im=im2double(im)
DEG_NUM=12;
LEN_c=11;
LEN_o=11;
LEN_diff=7;
ic1=reconstruction_by_dilation(im,LEN_c,DEG_NUM)
io1=min_openings(im,LEN_o,DEG_NUM)
iv=mat2gray(ic1-io1)
imDiff=smooth_cross_section(iv,LEN_diff,LEN_c)
imL=reconstruction_by_dilation(imDiff,LEN_c,DEG_NUM)
imF=reconstruction_by_erosion(imL,LEN_c,DEG_NUM)
F=np.squeeze(np.reshape(imF,(1,imF.size)))
TH_LOW,TH_HIGH=find_th(F)
#TH_LOW=0.12;
#TH_HIGH=0.2;
min_obj=5;
min_hole=10;
mask=np.zeros(np.shape(imF))
marker=np.zeros(np.shape(imF))
mask[imF>TH_LOW]=1
marker[imF>TH_HIGH]=1
bw_result=imreconstruct(marker,mask)
bw_result=filter_result3(img,bw_result,4,0.2)
bw_result=cv2.resize(bw_result,(size_orig[1],size_orig[0]))
imgr=imgorig[:,:,2];
imgr[bw_result>0]=255;
imgorig[:,:,2]=imgr;
print("completed --- %s seconds ---" % (time.time() - start_time))
print('saving output file: '+img_file_out)
cv2.imwrite(img_file_out,imgorig)
cv2.imwrite(img_file_out_bin,bw_result*255)
print('done ')
|
python
|
import tempfile
import pickle
import os
import sys
import time
import zipfile
import inspect
import binaryninja as binja
from binaryninja.binaryview import BinaryViewType, BinaryView
from binaryninja.filemetadata import FileMetadata, SaveSettings
from binaryninja.datarender import DataRenderer
from binaryninja.function import InstructionTextToken, DisassemblyTextLine
from binaryninja.enums import InstructionTextTokenType, SaveOption
import subprocess
import re
# Dear people from the future: If you're adding tests or debuging an
# issue where python2 and python3 are producing different output
# for the same function and it's a issue of `longs`, run the output
# through this function. If it's a unicode/bytes issue, fix it in
# api/python/
def fixOutput(outputList):
# Apply regular expression to detect python2 longs
splitList = []
for elem in outputList:
if isinstance(elem, str):
splitList.append(re.split(r"((?<=[\[ ])0x[\da-f]+L|[\d]+L)", elem))
else:
splitList.append(elem)
# Resolve application of regular expression
result = []
for elem in splitList:
if isinstance(elem, list):
newElem = []
for item in elem:
if len(item) > 1 and item[-1] == 'L':
newElem.append(item[:-1])
else:
newElem.append(item)
result.append(''.join(newElem))
else:
result.append(elem)
return result
# Alright so this one is here for Binja functions that output <in set([blah, blah, blah])>
def fixSet(string):
# Apply regular expression
splitList = (re.split(r"((?<=<in set\(\[).*(?=\]\)>))", string))
if len(splitList) > 1:
return splitList[0] + ', '.join(sorted(splitList[1].split(', '))) + splitList[2]
else:
return string
def fixStrRepr(string):
# Python 2 and Python 3 represent Unicode character reprs differently
return string.replace(b"\xe2\x80\xa6".decode("utf8"), "\\xe2\\x80\\xa6")
def get_file_list(test_store_rel):
test_store = os.path.join(os.path.dirname(__file__), test_store_rel)
all_files = []
for root, _, files in os.walk(test_store):
for file in files:
all_files.append(os.path.join(root, file))
return all_files
def remove_low_confidence(type_string):
low_confidence_types = ["int32_t", "void"]
for lct in low_confidence_types:
type_string = type_string.replace(lct + " ", '') # done to resolve confidence ties
return type_string
class Builder(object):
def __init__(self, test_store):
self.test_store = test_store
# binja.log.log_to_stdout(binja.LogLevel.DebugLog) # Uncomment for more info
def methods(self):
methodnames = []
for methodname, _ in inspect.getmembers(self, predicate=inspect.ismethod):
if methodname.startswith("test_"):
methodnames.append(methodname)
return methodnames
def unpackage_file(self, filename):
path = os.path.join(os.path.dirname(__file__), self.test_store, filename)
if not os.path.exists(path):
with zipfile.ZipFile(path + ".zip", "r") as zf:
zf.extractall(path = os.path.dirname(__file__))
assert os.path.exists(path)
return os.path.relpath(path)
def delete_package(self, filename):
path = os.path.join(os.path.dirname(__file__), self.test_store, filename)
os.unlink(path)
class BinaryViewTestBuilder(Builder):
""" The BinaryViewTestBuilder is for test that are verified against a binary.
The tests are first run on your dev machine to base line then run again
on the build machine to verify they are correct.
- Function that are tests should start with 'test_'
- Function doc string used as 'on error' message
- Should return: list of strings
"""
def __init__(self, filename, options=None):
self.filename = os.path.join(os.path.dirname(__file__), filename)
if options is None:
self.bv = BinaryViewType.get_view_of_file(self.filename)
else:
self.bv = BinaryViewType.get_view_of_file_with_options(self.filename, options=options)
if self.bv is None:
print("%s is not an executable format" % filename)
return
def test_available_types(self):
"""Available types don't match"""
return ["Available Type: " + x.name for x in BinaryView(FileMetadata()).open(self.filename).available_view_types]
def test_function_starts(self):
"""Function starts list doesnt match"""
result = []
for x in self.bv.functions:
result.append("Function start: " + hex(x.start))
return fixOutput(result)
def test_function_symbol_names(self):
"""Function.symbol.name list doesnt match"""
result = []
for x in self.bv.functions:
result.append("Symbol: " + x.symbol.name + ' ' + str(x.symbol.type) + ' ' + hex(x.symbol.address) + ' ' + str(x.symbol.namespace))
return fixOutput(result)
def test_function_can_return(self):
"""Function.can_return list doesnt match"""
result = []
for x in self.bv.functions:
result.append("function name: " + x.symbol.name + ' type: ' + str(x.symbol.type) + ' address: ' + hex(x.symbol.address) + ' can_return: ' + str(bool(x.can_return)))
return fixOutput(result)
def test_function_basic_blocks(self):
"""Function basic_block list doesnt match (start, end, has_undetermined_outgoing_edges)"""
bblist = []
for func in self.bv.functions:
for bb in func.basic_blocks:
bblist.append("basic block {} start: ".format(str(bb)) + hex(bb.start) + ' end: ' + hex(bb.end) + ' undetermined outgoing edges: ' + str(bb.has_undetermined_outgoing_edges) + ' incoming edges: ' + str(bb.incoming_edges) + ' outgoing edges: ' + str(bb.outgoing_edges))
for anno in func.get_block_annotations(bb.start):
bblist.append("basic block {} function annotation: ".format(str(bb)) + str(anno))
bblist.append("basic block {} test get self: ".format(str(bb)) + str(func.get_basic_block_at(bb.start)))
return fixOutput(bblist)
def test_function_low_il_basic_blocks(self):
"""Function low_il_basic_block list doesnt match"""
ilbblist = []
for func in self.bv.functions:
for bb in func.low_level_il.basic_blocks:
ilbblist.append("LLIL basic block {} start: ".format(str(bb)) + hex(bb.start) + ' end: ' + hex(bb.end) + ' outgoing edges: ' + str(len(bb.outgoing_edges)))
return fixOutput(ilbblist)
def test_function_med_il_basic_blocks(self):
"""Function med_il_basic_block list doesn't match"""
ilbblist = []
for func in self.bv.functions:
for bb in func.mlil.basic_blocks:
ilbblist.append("MLIL basic block {} start: ".format(str(bb)) + hex(bb.start) + ' end: ' + hex(bb.end) + ' outgoing_edges: ' + str(len(bb.outgoing_edges)))
return fixOutput(ilbblist)
def test_symbols(self):
"""Symbols list doesn't match"""
return ["Symbol: " + str(i) for i in sorted(self.bv.symbols)]
def test_symbol_namespaces(self):
"""Symbol namespaces don't match"""
return self.bv.namespaces
def test_internal_external_namespaces(self):
"""Symbol namespaces don't match"""
return [BinaryView.internal_namespace(), BinaryView.external_namespace()]
def test_strings(self):
"""Strings list doesn't match"""
return fixOutput(["String: " + str(x.value) + ' type: ' + str(x.type) + ' at: ' + hex(x.start) for x in self.bv.strings])
def test_low_il_instructions(self):
"""LLIL instructions produced different output"""
retinfo = []
for func in self.bv.functions:
for bb in func.low_level_il.basic_blocks:
for ins in bb:
retinfo.append("Function: {:x} Instruction: {:x} ADDR->LiftedILS: {}".format(func.start, ins.address, str(sorted(list(map(str, func.get_lifted_ils_at(ins.address)))))))
retinfo.append("Function: {:x} Instruction: {:x} ADDR->LLILS: {}".format(func.start, ins.address, str(sorted(list(map(str, func.get_llils_at(ins.address)))))))
retinfo.append("Function: {:x} Instruction: {:x} LLIL->MLIL: {}".format(func.start, ins.address, str(ins.mlil)))
retinfo.append("Function: {:x} Instruction: {:x} LLIL->MLILS: {}".format(func.start, ins.address, str(sorted(list(map(str, ins.mlils))))))
retinfo.append("Function: {:x} Instruction: {:x} LLIL->HLIL: {}".format(func.start, ins.address, str(ins.hlil)))
retinfo.append("Function: {:x} Instruction: {:x} LLIL->HLILS: {}".format(func.start, ins.address, str(sorted(list(map(str, ins.hlils))))))
retinfo.append("Function: {:x} Instruction: {:x} Mapped MLIL: {}".format(func.start, ins.address, str(ins.mapped_medium_level_il)))
retinfo.append("Function: {:x} Instruction: {:x} Value: {}".format(func.start, ins.address, str(ins.value)))
retinfo.append("Function: {:x} Instruction: {:x} Possible Values: {}".format(func.start, ins.address, str(ins.possible_values)))
prefixList = []
for i in ins.prefix_operands:
if isinstance(i, dict):
contents = []
for j in sorted(i.keys()):
contents.append((j, i[j]))
prefixList.append(str(contents))
else:
prefixList.append(i)
retinfo.append("Function: {:x} Instruction: {:x} Prefix operands: {}".format(func.start, ins.address, fixStrRepr(str(prefixList))))
postfixList = []
for i in ins.postfix_operands:
if isinstance(i, dict):
contents = []
for j in sorted(i.keys()):
contents.append((j, i[j]))
postfixList.append(str(contents))
else:
postfixList.append(i)
retinfo.append("Function: {:x} Instruction: {:x} Postfix operands: {}".format(func.start, ins.address, fixStrRepr(str(postfixList))))
retinfo.append("Function: {:x} Instruction: {:x} SSA form: {}".format(func.start, ins.address, str(ins.ssa_form)))
retinfo.append("Function: {:x} Instruction: {:x} Non-SSA form: {}".format(func.start, ins.address, str(ins.non_ssa_form)))
return fixOutput(retinfo)
def test_low_il_ssa(self):
"""LLIL ssa produced different output"""
retinfo = []
for func in self.bv.functions:
func = func.low_level_il
for reg_name in sorted(self.bv.arch.regs):
reg = binja.SSARegister(reg_name, 1)
retinfo.append("Function: {:x} Reg {} SSA definition: {}".format(func.source_function.start, reg_name, str(getattr(func.get_ssa_reg_definition(reg), 'instr_index', None))))
retinfo.append("Function: {:x} Reg {} SSA uses: {}".format(func.source_function.start, reg_name, str(list(map(lambda instr: instr.instr_index, func.get_ssa_reg_uses(reg))))))
retinfo.append("Function: {:x} Reg {} SSA value: {}".format(func.source_function.start, reg_name, str(func.get_ssa_reg_value(reg))))
for flag_name in sorted(self.bv.arch.flags):
flag = binja.SSAFlag(flag_name, 1)
retinfo.append("Function: {:x} Flag {} SSA uses: {}".format(func.source_function.start, flag_name, str(list(map(lambda instr: instr.instr_index, func.get_ssa_flag_uses(flag))))))
retinfo.append("Function: {:x} Flag {} SSA value: {}".format(func.source_function.start, flag_name, str(func.get_ssa_flag_value(flag))))
for bb in func.basic_blocks:
for ins in bb:
tempind = func.get_non_ssa_instruction_index(ins.instr_index)
retinfo.append("Function: {:x} Instruction: {:x} Non-SSA instruction index: {}".format(func.source_function.start, ins.address, str(tempind)))
retinfo.append("Function: {:x} Instruction: {:x} SSA instruction index: {}".format(func.source_function.start, ins.address, str(func.get_ssa_instruction_index(tempind))))
retinfo.append("Function: {:x} Instruction: {:x} MLIL instruction index: {}".format(func.source_function.start, ins.address, str(func.get_medium_level_il_instruction_index(ins.instr_index))))
retinfo.append("Function: {:x} Instruction: {:x} Mapped MLIL instruction index: {}".format(func.source_function.start, ins.address, str(func.get_mapped_medium_level_il_instruction_index(ins.instr_index))))
retinfo.append("Function: {:x} Instruction: {:x} LLIL_SSA->MLIL: {}".format(func.source_function.start, ins.address, str(ins.mlil)))
retinfo.append("Function: {:x} Instruction: {:x} LLIL_SSA->MLILS: {}".format(func.source_function.start, ins.address, str(sorted(list(map(str, ins.mlils))))))
retinfo.append("Function: {:x} Instruction: {:x} LLIL_SSA->HLIL: {}".format(func.source_function.start, ins.address, str(ins.hlil)))
retinfo.append("Function: {:x} Instruction: {:x} LLIL_SSA->HLILS: {}".format(func.source_function.start, ins.address, str(sorted(list(map(str, ins.hlils))))))
return fixOutput(retinfo)
def test_med_il_instructions(self):
"""MLIL instructions produced different output"""
retinfo = []
for func in self.bv.functions:
for bb in func.mlil.basic_blocks:
for ins in bb:
retinfo.append("Function: {:x} Instruction: {:x} Expression type: {}".format(func.start, ins.address, str(ins.expr_type)))
retinfo.append("Function: {:x} Instruction: {:x} MLIL->LLIL: {}".format(func.start, ins.address, str(ins.llil)))
retinfo.append("Function: {:x} Instruction: {:x} MLIL->LLILS: {}".format(func.start, ins.address, str(sorted(list(map(str, ins.llils))))))
retinfo.append("Function: {:x} Instruction: {:x} MLIL->HLIL: {}".format(func.start, ins.address, str(ins.hlil)))
retinfo.append("Function: {:x} Instruction: {:x} MLIL->HLILS: {}".format(func.start, ins.address, str(sorted(list(map(str, ins.hlils))))))
retinfo.append("Function: {:x} Instruction: {:x} Value: {}".format(func.start, ins.address, str(ins.value)))
retinfo.append("Function: {:x} Instruction: {:x} Possible values: {}".format(func.start, ins.address, str(ins.possible_values)))
retinfo.append("Function: {:x} Instruction: {:x} Branch dependence: {}".format(func.start, ins.address, str(sorted(ins.branch_dependence.items()))))
prefixList = []
for i in ins.prefix_operands:
if isinstance(i, float) and 'e' in str(i):
prefixList.append(str(round(i, 21)))
elif isinstance(i, float):
prefixList.append(str(round(i, 11)))
elif isinstance(i, dict):
contents = []
for j in sorted(i.keys()):
contents.append((j, i[j]))
prefixList.append(str(contents))
else:
prefixList.append(str(i))
retinfo.append("Function: {:x} Instruction: {:x} Prefix operands: {}".format(func.start, ins.address, fixStrRepr(str(sorted(prefixList)))))
postfixList = []
for i in ins.postfix_operands:
if isinstance(i, float) and 'e' in str(i):
postfixList.append(str(round(i, 21)))
elif isinstance(i, float):
postfixList.append(str(round(i, 11)))
elif isinstance(i, dict):
contents = []
for j in sorted(i.keys()):
contents.append((j, i[j]))
postfixList.append(str(contents))
else:
postfixList.append(str(i))
retinfo.append("Function: {:x} Instruction: {:x} Postfix operands: {}".format(func.start, ins.address, fixStrRepr(str(sorted(postfixList)))))
retinfo.append("Function: {:x} Instruction: {:x} SSA form: {}".format(func.start, ins.address, str(ins.ssa_form)))
retinfo.append("Function: {:x} Instruction: {:x} Non-SSA form: {}".format(func.start, ins.address, str(ins.non_ssa_form)))
return fixOutput(retinfo)
def test_med_il_vars(self):
"""Function med_il_vars doesn't match"""
varlist = []
for func in self.bv.functions:
func = func.mlil
for bb in func.basic_blocks:
for instruction in bb:
instruction = instruction.ssa_form
for var in (instruction.vars_read + instruction.vars_written):
if hasattr(var, "var"):
varlist.append("Function: {:x} Instruction {:x} SSA var definition: {}".format (func.source_function.start, instruction.address, str(getattr(func.get_ssa_var_definition(var), 'instr_index', None))))
varlist.append("Function: {:x} Instruction {:x} SSA var uses: {}".format (func.source_function.start, instruction.address, str(list(map(lambda instr: instr.instr_index, func.get_ssa_var_uses(var))))))
varlist.append("Function: {:x} Instruction {:x} SSA var value: {}".format (func.source_function.start, instruction.address, str(func.get_ssa_var_value(var))))
varlist.append("Function: {:x} Instruction {:x} SSA var possible values: {}".format (func.source_function.start, instruction.address, fixSet(str(instruction.get_ssa_var_possible_values(var)))))
varlist.append("Function: {:x} Instruction {:x} SSA var version: {}".format (func.source_function.start, instruction.address, str(instruction.get_ssa_var_version)))
return fixOutput(varlist)
def test_function_stack(self):
"""Function stack produced different output"""
funcinfo = []
for func in self.bv.functions:
func.stack_adjustment = func.stack_adjustment
func.reg_stack_adjustments = func.reg_stack_adjustments
func.create_user_stack_var(0, binja.Type.int(4), "testuservar")
func.create_auto_stack_var(4, binja.Type.int(4), "testautovar")
sl = func.stack_layout
for i in range(len(sl)):
funcinfo.append("Function: {:x} Stack position {}: ".format(func.start, i) + str(sl[i]))
funcinfo.append("Function: {:x} Stack content sample: {}".format(func.start, str(func.get_stack_contents_at(func.start + 0x10, 0, 0x10))))
funcinfo.append("Function: {:x} Stack content range sample: {}".format(func.start, str(func.get_stack_contents_after(func.start + 0x10, 0, 0x10))))
funcinfo.append("Function: {:x} Sample stack var: {}".format(func.start, str(func.get_stack_var_at_frame_offset(0, 0))))
func.delete_user_stack_var(0)
func.delete_auto_stack_var(0)
return funcinfo
def test_function_llil(self):
"""Function LLIL produced different output"""
retinfo = []
for func in self.bv.functions:
for llilbb in func.llil_basic_blocks:
retinfo.append("Function: {:x} LLIL basic block: {}".format(func.start, str(llilbb)))
for llilins in func.llil.instructions:
retinfo.append("Function: {:x} Instruction: {:x} LLIL instruction: {}".format(func.start, llilins.address, str(llilins)))
for mlilbb in func.mlil_basic_blocks:
retinfo.append("Function: {:x} MLIL basic block: {}".format(func.start, str(mlilbb)))
for mlilins in func.mlil.instructions:
retinfo.append("Function: {:x} Instruction: {:x} MLIL instruction: {}".format(func.start, mlilins.address, str(mlilins)))
for hlilins in func.hlil.instructions:
retinfo.append("Function: {:x} Instruction: {:x} HLIL instruction: {}".format(func.start, hlilins.address, str(hlilins)))
for ins in func.instructions:
retinfo.append("Function: {:x} Instruction: {}: {}".format(func.start, hex(ins[1]), ''.join([str(i) for i in ins[0]])))
return fixOutput(retinfo)
def test_function_hlil(self):
"""Function HLIL produced different output"""
retinfo = []
for func in self.bv.functions:
for line in func.hlil.root.lines:
retinfo.append("Function: {:x} HLIL line: {}".format(func.start, str(line)))
for hlilins in func.hlil.instructions:
retinfo.append("Function: {:x} Instruction: {:x} HLIL->LLIL instruction: {}".format(func.start, hlilins.address, str(hlilins.llil)))
retinfo.append("Function: {:x} Instruction: {:x} HLIL->MLIL instruction: {}".format(func.start, hlilins.address, str(hlilins.mlil)))
retinfo.append("Function: {:x} Instruction: {:x} HLIL->MLILS instruction: {}".format(func.start, hlilins.address, str(sorted(list(map(str, hlilins.mlils))))))
return fixOutput(retinfo)
def test_functions_attributes(self):
"""Function attributes don't match"""
funcinfo = []
for func in self.bv.functions:
func.comment = "testcomment " + func.name
func.name = func.name
func.can_return = func.can_return
func.function_type = func.function_type
func.return_type = func.return_type
func.return_regs = func.return_regs
func.calling_convention = func.calling_convention
func.parameter_vars = func.parameter_vars
func.has_variable_arguments = func.has_variable_arguments
func.analysis_skipped = func.analysis_skipped
func.clobbered_regs = func.clobbered_regs
func.set_user_instr_highlight(func.start, binja.highlight.HighlightColor(red=0xff, blue=0xff, green=0))
func.set_auto_instr_highlight(func.start, binja.highlight.HighlightColor(red=0xff, blue=0xfe, green=0))
for var in func.vars:
funcinfo.append("Function {} var: ".format(func.name) + str(var))
for branch in func.indirect_branches:
funcinfo.append("Function {} indirect branch: ".format(func.name) + str(branch))
funcinfo.append("Function {} session data: ".format(func.name) + str(func.session_data))
funcinfo.append("Function {} analysis perf length: ".format(func.name) + str(len(func.analysis_performance_info)))
for cr in func.clobbered_regs:
funcinfo.append("Function {} clobbered reg: ".format(func.name) + str(cr))
funcinfo.append("Function {} explicitly defined type: ".format(func.name) + str(func.explicitly_defined_type))
funcinfo.append("Function {} needs update: ".format(func.name) + str(func.needs_update))
funcinfo.append("Function {} global pointer value: ".format(func.name) + str(func.global_pointer_value))
funcinfo.append("Function {} comment: ".format(func.name) + str(func.comment))
funcinfo.append("Function {} too large: ".format(func.name) + str(func.too_large))
funcinfo.append("Function {} analysis skipped: ".format(func.name) + str(func.analysis_skipped))
funcinfo.append("Function {} first ins LLIL: ".format(func.name) + str(func.get_low_level_il_at(func.start)))
funcinfo.append("Function {} LLIL exit test: ".format(func.name) + str(func.get_low_level_il_exits_at(func.start+0x100)))
funcinfo.append("Function {} regs read test: ".format(func.name) + str(func.get_regs_read_by(func.start)))
funcinfo.append("Function {} regs written test: ".format(func.name) + str(func.get_regs_written_by(func.start)))
funcinfo.append("Function {} stack var test: ".format(func.name) + str(func.get_stack_vars_referenced_by(func.start)))
funcinfo.append("Function {} constant reference test: ".format(func.name) + str(func.get_constants_referenced_by(func.start)))
funcinfo.append("Function {} first ins lifted IL: ".format(func.name) + str(func.get_lifted_il_at(func.start)))
funcinfo.append("Function {} flags read by lifted IL ins: ".format(func.name) + str(func.get_flags_read_by_lifted_il_instruction(0)))
funcinfo.append("Function {} flags written by lifted IL ins: ".format(func.name) + str(func.get_flags_written_by_lifted_il_instruction(0)))
funcinfo.append("Function {} create graph: ".format(func.name) + str(func.create_graph()))
funcinfo.append("Function {} indirect branches test: ".format(func.name) + str(func.get_indirect_branches_at(func.start+0x10)))
funcinfo.append("Function {} test instr highlight: ".format(func.name) + str(func.get_instr_highlight(func.start)))
for token in func.get_type_tokens():
token = str(token)
token = remove_low_confidence(token)
funcinfo.append("Function {} type token: ".format(func.name) + str(token))
return fixOutput(funcinfo)
def test_BinaryView(self):
"""BinaryView produced different results"""
retinfo = []
for type in sorted([str(i) for i in self.bv.types.items()]):
retinfo.append("BV Type: " + str(type))
for segment in sorted([str(i) for i in self.bv.segments]):
retinfo.append("BV segment: " + str(segment))
for section in sorted(self.bv.sections):
retinfo.append("BV section: " + str(section))
for allrange in self.bv.allocated_ranges:
retinfo.append("BV allocated range: " + str(allrange))
retinfo.append("Session Data: " + str(self.bv.session_data))
for addr in sorted(self.bv.data_vars.keys()):
retinfo.append("BV data var: " + str(self.bv.data_vars[addr]))
retinfo.append("BV Entry function: " + repr(self.bv.entry_function))
for i in self.bv:
retinfo.append("BV function: " + repr(i))
retinfo.append("BV entry point: " + hex(self.bv.entry_point))
retinfo.append("BV start: " + hex(self.bv.start))
retinfo.append("BV length: " + hex(len(self.bv)))
return fixOutput(retinfo)
def test_dominators(self):
"""Dominators don't match oracle"""
retinfo = []
for func in self.bv.functions:
for bb in func:
for dom in sorted(bb.dominators, key=lambda x: x.start):
retinfo.append("Dominator: %x of %x" % (dom.start, bb.start))
for pdom in sorted(bb.post_dominators, key=lambda x: x.start):
retinfo.append("PostDominator: %x of %x" % (pdom.start, bb.start))
return fixOutput(retinfo)
class TestBuilder(Builder):
""" The TestBuilder is for tests that need to be checked against a
stored oracle data that isn't from a binary. These test are
generated on your local machine then run again on the build
machine to verify correctness.
- Function that are tests should start with 'test_'
- Function doc string used as 'on error' message
- Should return: list of strings
"""
def test_BinaryViewType_list(self):
"""BinaryViewType list doesnt match"""
return ["BinaryViewType: " + x.name for x in binja.BinaryViewType.list]
def test_deprecated_BinaryViewType(self):
"""deprecated BinaryViewType list doesnt match"""
file_name = self.unpackage_file("fat_macho_9arch.bndb")
if not os.path.exists(file_name):
return [""]
view_types = []
with binja.filemetadata.FileMetadata().open_existing_database(file_name, None) as bv:
for view_type in bv.available_view_types:
if view_type.is_deprecated:
view_types.append('BinaryViewType: %s (deprecated)' % view_type.name)
else:
view_types.append('BinaryViewType: %s' % view_type.name)
self.delete_package("fat_macho_9arch.bndb")
return view_types
def test_Architecture_list(self):
"""Architecture list doesnt match"""
return ["Arch name: " + x.name for x in binja.Architecture.list]
def test_Assemble(self):
"""unexpected assemble result"""
result = []
# success cases
strResult = binja.Architecture["x86"].assemble("xor eax, eax")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("x86 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("x86 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["x86_64"].assemble("xor rax, rax")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("x86_64 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("x86_64 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["mips32"].assemble("move $ra, $zero")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("mips32 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("mips32 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["mipsel32"].assemble("move $ra, $zero")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("mipsel32 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("mipsel32 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["armv7"].assemble("str r2, [sp, #-0x4]!")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("armv7 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("armv7 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["aarch64"].assemble("mov x0, x0")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("aarch64 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("aarch64 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["thumb2"].assemble("ldr r4, [r4]")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("thumb2 assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("thumb2 assembly: " + repr(str(strResult)))
strResult = binja.Architecture["thumb2eb"].assemble("ldr r4, [r4]")
if sys.version_info.major == 3 and not strResult[0] is None:
result.append("thumb2eb assembly: " + "'" + str(strResult)[2:-1] + "'")
else:
result.append("thumb2eb assembly: " + repr(str(strResult)))
# fail cases
try:
strResult = binja.Architecture["x86"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'x86'")
try:
strResult = binja.Architecture["x86_64"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'x86_64'")
try:
strResult = binja.Architecture["mips32"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'mips32'")
try:
strResult = binja.Architecture["mipsel32"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'mipsel32'")
try:
strResult = binja.Architecture["armv7"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'armv7'")
try:
strResult = binja.Architecture["aarch64"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'aarch64'")
try:
strResult = binja.Architecture["thumb2"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'thumb2'")
try:
strResult = binja.Architecture["thumb2eb"].assemble("thisisnotaninstruction")
except ValueError:
result.append("Assemble Failed As Expected; 'thisisnotaninstruction' is not an instruction on 'thumb2eb'")
return result
def test_Architecture(self):
"""Architecture failure"""
if not os.path.exists(os.path.join(os.path.expanduser("~"), '.binaryninja', 'plugins', 'nes.py')):
return [""]
retinfo = []
file_name = os.path.join(os.path.dirname(__file__), self.test_store, "..", "pwnadventurez.nes")
bv = binja.BinaryViewType["NES Bank 0"].open(file_name)
for i in bv.platform.arch.calling_conventions:
retinfo.append("Custom arch calling convention: " + str(i))
for i in bv.platform.arch.full_width_regs:
retinfo.append("Custom arch full width reg: " + str(i))
reg = binja.RegisterValue()
retinfo.append("Reg entry value: " + str(reg.entry_value(bv.platform.arch, 'x')))
retinfo.append("Reg constant: " + str(reg.constant(0xfe)))
retinfo.append("Reg constant pointer: " + str(reg.constant_ptr(0xcafebabe)))
retinfo.append("Reg stack frame offset: " + str(reg.stack_frame_offset(0x10)))
retinfo.append("Reg imported address: " + str(reg.imported_address(0xdeadbeef)))
retinfo.append("Reg return address: " + str(reg.return_address()))
bv.update_analysis_and_wait()
for func in bv.functions:
for bb in func.low_level_il.basic_blocks:
for ins in bb:
retinfo.append("Instruction info: " + str(bv.platform.arch.get_instruction_info(0x10, ins.address)))
retinfo.append("Instruction test: " + str(bv.platform.arch.get_instruction_text(0x10, ins.address)))
retinfo.append("Instruction: " + str(ins))
return retinfo
def test_Function(self):
"""Function produced different result"""
inttype = binja.Type.int(4)
testfunction = binja.Type.function(inttype, [inttype, inttype, inttype])
return ["Test_function params: " + str(testfunction.parameters), "Test_function pointer: " + str(testfunction.pointer(binja.Architecture["x86"], testfunction))]
def test_Simplifier(self):
"""Template Simplification"""
result = [binja.demangle.simplify_name_to_string(s) for s in [
# Minimal exhaustive examples of simplifier (these are replicated in testcommon)
"std::basic_string<T, std::char_traits<T>, std::allocator<T> >",
"std::vector<T, std::allocator<T> >",
"std::vector<T, std::allocator<T>, std::lessthan<T> >",
"std::deque<T, std::allocator<T> >",
"std::forward_list<T, std::allocator<T> >",
"std::list<T, std::allocator<T> >",
"std::stack<T, std::deque<T> >",
"std::queue<T, std::deque<T> >",
"std::set<T, std::less<T>, std::allocator<T> >",
"std::multiset<T, std::less<T>, std::allocator<T> >",
"std::map<T1, T2, std::less<T1>, std::allocator<std::pair<const T1, T2> > >",
"std::multimap<T1, T2, std::less<T1>, std::allocator<std::pair<const T1, T2> > >",
"std::unordered_set<T, std::hash<T>, std::equal_to<T>, std::allocator<T> >",
"std::unordered_multiset<T, std::hash<T>, std::equal_to<T>, std::allocator<T> >",
"std::unordered_map<T1, T2, std::hash<T1>, std::equal_to<T1>, std::allocator<std::pair<const T1, T2> > >",
"std::unordered_multimap<T1, T2, std::hash<T1>, std::equal_to<T1>, std::allocator<std::pair<const T1, T2> > >",
"std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >",
"std::basic_istringstream<char, std::char_traits<char>, std::allocator<char> >",
"std::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >",
"std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >",
"std::basic_stringbuf<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >",
"std::basic_istringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >",
"std::basic_ostringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >",
"std::basic_stringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >",
"std::basic_stringbuf<T, std::char_traits<T>, std::allocator<T> >",
"std::basic_istringstream<T, std::char_traits<T>, std::allocator<T> >",
"std::basic_ostringstream<T, std::char_traits<T>, std::allocator<T> >",
"std::basic_stringstream<T, std::char_traits<T>, std::allocator<T> >",
"std::basic_ios<char, std::char_traits<char> >",
"std::basic_streambuf<char, std::char_traits<char> >",
"std::basic_istream<char, std::char_traits<char> >",
"std::basic_ostream<char, std::char_traits<char> >",
"std::basic_iostream<char, std::char_traits<char> >",
"std::basic_filebuf<char, std::char_traits<char> >",
"std::basic_ifstream<char, std::char_traits<char> >",
"std::basic_ofstream<char, std::char_traits<char> >",
"std::basic_fstream<char, std::char_traits<char> >",
"std::basic_ios<wchar_t, std::char_traits<wchar_t> >",
"std::basic_streambuf<wchar_t, std::char_traits<wchar_t> >",
"std::basic_istream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_ostream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_iostream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_filebuf<wchar_t, std::char_traits<wchar_t> >",
"std::basic_ifstream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_ofstream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_fstream<wchar_t, std::char_traits<wchar_t> >",
"std::basic_ios<T, std::char_traits<T> >",
"std::basic_streambuf<T, std::char_traits<T> >",
"std::basic_istream<T, std::char_traits<T> >",
"std::basic_ostream<T, std::char_traits<T> >",
"std::basic_iostream<T, std::char_traits<T> >",
"std::basic_filebuf<T, std::char_traits<T> >",
"std::basic_ifstream<T, std::char_traits<T> >",
"std::basic_ofstream<T, std::char_traits<T> >",
"std::basic_fstream<T, std::char_traits<T> >",
"std::fpos<__mbstate_t>",
"std::_Ios_Iostate",
"std::_Ios_Seekdir",
"std::_Ios_Openmode",
"std::_Ios_Fmtflags",
"std::foo<T, std::char_traits<T> >",
"std::bar<T, std::char_traits<T> >::bar",
"std::foo<T, std::char_traits<T> >::~foo",
"std::foo<T, std::char_traits<T> >::bar",
"std::foo<bleh::T, std::char_traits<bleh::T> >",
"std::bar<bleh::T, std::char_traits<bleh::T> >::bar",
"std::foo<bleh::T, std::char_traits<bleh::T> >::~foo",
"std::foo<bleh::T, std::char_traits<bleh::T> >::bar",
"std::foo<foo::bleh::T, std::char_traits<foo::bleh::T> >",
"std::bar<foo::bleh::T, std::char_traits<foo::bleh::T> >::bar",
"std::foo<foo::bleh::T, std::char_traits<foo::bleh::T> >::~foo",
"std::foo<foo::bleh::T, std::char_traits<foo::bleh::T> >::bar",
# More complex examples:
"AddRequiredUIPluginDependency(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)",
"std::vector<std::vector<BinaryNinja::InstructionTextToken, std::allocator<BinaryNinja::InstructionTextToken> >, std::allocator<std::vector<BinaryNinja::InstructionTextToken, std::allocator<BinaryNinja::InstructionTextToken> > > >::_M_check_len(uint64_t, char const*) const",
"std::vector<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::array<uint32_t, 5ul> >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::array<uint32_t, 5ul> > > >::_M_default_append(uint64_t)",
"std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string",
"std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::~basic_string",
]]
# Test all the APIs
qName = binja.types.QualifiedName(["std", "__cxx11", "basic_string<T, std::char_traits<T>, std::allocator<T> >"])
result.append(binja.demangle.simplify_name_to_string(qName))
result.append(str(binja.demangle.simplify_name_to_qualified_name(qName)))
result.append(str(binja.demangle.simplify_name_to_qualified_name(str(qName))))
result.append(str(binja.demangle.simplify_name_to_qualified_name(str(qName), False).name))
result.append("::".join(binja.demangle_gnu3(binja.Architecture['x86_64'], "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_createERmm", False)[1]))
result.append("::".join(binja.demangle_gnu3(binja.Architecture['x86_64'], "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_createERmm", True)[1]))
return result
def test_Struct(self):
"""Struct produced different result"""
retinfo = []
inttype = binja.Type.int(4)
struct = binja.Structure()
struct.a = 1
struct.insert(0, inttype)
struct.append(inttype)
struct.replace(0, inttype)
struct.remove(1)
for i in struct.members:
retinfo.append("Struct member: " + str(i))
retinfo.append("Struct width: " + str(struct.width))
struct.width = 16
retinfo.append("Struct width after adjustment: " + str(struct.width))
retinfo.append("Struct alignment: " + str(struct.alignment))
struct.alignment = 8
retinfo.append("Struct alignment after adjustment: " + str(struct.alignment))
retinfo.append("Struct packed: " + str(struct.packed))
struct.packed = 1
retinfo.append("Struct packed after adjustment: " + str(struct.packed))
retinfo.append("Struct type: " + str(struct.type))
retinfo.append(str((struct == struct) and not (struct != struct)))
return retinfo
def test_Enumeration(self):
"""Enumeration produced different result"""
retinfo = []
enum = binja.Enumeration()
enum.a = 1
enum.append("a", 1)
enum.append("b", 2)
enum.replace(0, "a", 2)
enum.remove(0)
retinfo.append(str(enum))
retinfo.append(str((enum == enum) and not (enum != enum)))
return retinfo
def test_Types(self):
"""Types produced different result"""
file_name = self.unpackage_file("helloworld")
try:
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
preprocessed = binja.preprocess_source("""
#ifdef nonexistant
int foo = 1;
long long foo1 = 1;
#else
int bar = 2;
long long bar1 = 2;
#endif
""")
source = '\n'.join([i.decode('charmap') for i in preprocessed[0].split(b'\n') if not b'#line' in i and len(i) > 0])
source = str(source) #TODO: remove when PY2 support has ended
typelist = bv.platform.parse_types_from_source(source)
inttype = binja.Type.int(4)
namedtype = binja.NamedTypeReference()
tokens = inttype.get_tokens() + inttype.get_tokens_before_name() + inttype.get_tokens_after_name()
retinfo = []
for i in range(len(typelist.variables)):
for j in typelist.variables.popitem():
retinfo.append("Type: " + str(j))
retinfo.append("Named Type: " + str(namedtype))
retinfo.append("Type equality: " + str((inttype == inttype) and not (inttype != inttype)))
return retinfo
finally:
self.delete_package("helloworld")
def test_Plugin_bin_info(self):
"""print_syscalls plugin produced different result"""
file_name = self.unpackage_file("helloworld")
try:
bin_info_path = os.path.join(os.path.dirname(__file__), '..', 'python', 'examples', 'bin_info.py')
if sys.platform == "win32":
python_bin = ["py", "-3"]
else:
python_bin = ["python3"]
result = subprocess.Popen(python_bin + [bin_info_path, file_name], stdout=subprocess.PIPE).communicate()[0]
# normalize line endings and path sep
return [line for line in result.replace(b"\\", b"/").replace(b"\r\n", b"\n").decode("charmap").split("\n")]
finally:
self.delete_package("helloworld")
def test_linear_disassembly(self):
"""linear_disassembly produced different result"""
file_name = self.unpackage_file("helloworld")
try:
bv = binja.BinaryViewType['ELF'].open(file_name)
disass = bv.linear_disassembly
retinfo = []
for i in disass:
i = str(i)
i = remove_low_confidence(i)
retinfo.append(i)
return retinfo
finally:
self.delete_package("helloworld")
def test_data_renderer(self):
"""data renderer produced different result"""
file_name = self.unpackage_file("helloworld")
class ElfHeaderDataRenderer(DataRenderer):
def __init__(self):
DataRenderer.__init__(self)
def perform_is_valid_for_data(self, ctxt, view, addr, type, context):
return DataRenderer.is_type_of_struct_name(type, "Elf64_Header", context)
def perform_get_lines_for_data(self, ctxt, view, addr, type, prefix, width, context):
prefix.append(InstructionTextToken(InstructionTextTokenType.TextToken, "I'm in ur Elf64_Header"))
return [DisassemblyTextLine(prefix, addr)]
def __del__(self):
pass
try:
bv = binja.BinaryViewType['ELF'].open(file_name)
ElfHeaderDataRenderer().register_type_specific()
disass = bv.linear_disassembly
retinfo = []
for i in disass:
i = str(i)
i = remove_low_confidence(i)
retinfo.append(i)
return retinfo
finally:
self.delete_package("helloworld")
# def test_partial_register_dataflow(self):
# """partial_register_dataflow produced different results"""
# file_name = self.unpackage_file("partial_register_dataflow")
# result = []
# reg_list = ['ch', 'cl', 'ah', 'edi', 'al', 'cx', 'ebp', 'ax', 'edx', 'ebx', 'esp', 'esi', 'dl', 'dh', 'di', 'bl', 'bh', 'eax', 'dx', 'bx', 'ecx', 'sp', 'si']
# bv = binja.BinaryViewType.get_view_of_file(file_name)
# for func in bv.functions:
# llil = func.low_level_il
# for i in range(0, llil.__len__()-1):
# for x in reg_list:
# result.append("LLIL:" + str(i).replace('L', '') + ":" + x + ":" + str(llil[i].get_reg_value(x)).replace('L', ''))
# result.append("LLIL:" + str(i).replace('L', '') + ":" + x + ":" + str(llil[i].get_possible_reg_values(x)).replace('L', ''))
# result.append("LLIL:" + str(i).replace('L', '') + ":" + x + ":" + str(llil[i].get_reg_value_after(x)).replace('L', ''))
# result.append("LLIL:" + str(i).replace('L', '') + ":" + x + ":" + str(llil[i].get_possible_reg_values_after(x)).replace('L', ''))
# bv.file.close()
# del bv
# return result
def test_low_il_stack(self):
"""LLIL stack produced different output"""
file_name = self.unpackage_file("jumptable_reordered")
try:
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
# reg_list = ['ch', 'cl', 'ah', 'edi', 'al', 'cx', 'ebp', 'ax', 'edx', 'ebx', 'esp', 'esi', 'dl', 'dh', 'di', 'bl', 'bh', 'eax', 'dx', 'bx', 'ecx', 'sp', 'si']
flag_list = ['c', 'p', 'a', 'z', 's', 'o']
retinfo = []
for func in bv.functions:
for bb in func.low_level_il.basic_blocks:
for ins in bb:
retinfo.append("LLIL first stack element: " + str(ins.get_stack_contents(0,1)))
retinfo.append("LLIL second stack element: " + str(ins.get_stack_contents_after(0,1)))
retinfo.append("LLIL possible first stack element: " + str(ins.get_possible_stack_contents(0,1)))
retinfo.append("LLIL possible second stack element: " + str(ins.get_possible_stack_contents_after(0,1)))
for flag in flag_list:
retinfo.append("LLIL flag {} value at {}: {}".format(flag, hex(ins.address), str(ins.get_flag_value(flag))))
retinfo.append("LLIL flag {} value after {}: {}".format(flag, hex(ins.address), str(ins.get_flag_value_after(flag))))
retinfo.append("LLIL flag {} possible value at {}: {}".format(flag, hex(ins.address), str(ins.get_possible_flag_values(flag))))
retinfo.append("LLIL flag {} possible value after {}: {}".format(flag, hex(ins.address), str(ins.get_possible_flag_values_after(flag))))
return fixOutput(retinfo)
finally:
self.delete_package("jumptable_reordered")
def test_med_il_stack(self):
"""MLIL stack produced different output"""
file_name = self.unpackage_file("jumptable_reordered")
try:
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
reg_list = ['ch', 'cl', 'ah', 'edi', 'al', 'cx', 'ebp', 'ax', 'edx', 'ebx', 'esp', 'esi', 'dl', 'dh', 'di', 'bl', 'bh', 'eax', 'dx', 'bx', 'ecx', 'sp', 'si']
flag_list = ['c', 'p', 'a', 'z', 's', 'o']
retinfo = []
for func in bv.functions:
for bb in func.mlil.basic_blocks:
for ins in bb:
retinfo.append("MLIL stack begin var: " + str(ins.get_var_for_stack_location(0)))
retinfo.append("MLIL first stack element: " + str(ins.get_stack_contents(0, 1)))
retinfo.append("MLIL second stack element: " + str(ins.get_stack_contents_after(0, 1)))
retinfo.append("MLIL possible first stack element: " + str(ins.get_possible_stack_contents(0, 1)))
retinfo.append("MLIL possible second stack element: " + str(ins.get_possible_stack_contents_after(0, 1)))
for reg in reg_list:
retinfo.append("MLIL reg {} var at {}: {}".format(reg, hex(ins.address), str(ins.get_var_for_reg(reg))))
retinfo.append("MLIL reg {} value at {}: {}".format(reg, hex(ins.address), str(ins.get_reg_value(reg))))
retinfo.append("MLIL reg {} value after {}: {}".format(reg, hex(ins.address), str(ins.get_reg_value_after(reg))))
retinfo.append("MLIL reg {} possible value at {}: {}".format(reg, hex(ins.address), fixSet(str(ins.get_possible_reg_values(reg)))))
retinfo.append("MLIL reg {} possible value after {}: {}".format(reg, hex(ins.address), fixSet(str(ins.get_possible_reg_values_after(reg)))))
for flag in flag_list:
retinfo.append("MLIL flag {} value at {}: {}".format(flag, hex(ins.address), str(ins.get_flag_value(flag))))
retinfo.append("MLIL flag {} value after {}: {}".format(flag, hex(ins.address), str(ins.get_flag_value_after(flag))))
retinfo.append("MLIL flag {} possible value at {}: {}".format(flag, hex(ins.address), fixSet(str(ins.get_possible_flag_values(flag)))))
retinfo.append("MLIL flag {} possible value after {}: {}".format(flag, hex(ins.address), fixSet(str(ins.get_possible_flag_values(flag)))))
return fixOutput(retinfo)
finally:
self.delete_package("jumptable_reordered")
def test_events(self):
"""Event failure"""
file_name = self.unpackage_file("helloworld")
try:
with binja.BinaryViewType['ELF'].get_view_of_file(file_name) as bv:
bv.update_analysis_and_wait()
results = []
def simple_complete(self):
results.append("analysis complete")
_ = binja.AnalysisCompletionEvent(bv, simple_complete)
class NotifyTest(binja.BinaryDataNotification):
def data_written(self, view, offset, length):
results.append("data written: offset {0} length {1}".format(hex(offset), hex(length)))
def data_inserted(self, view, offset, length):
results.append("data inserted: offset {0} length {1}".format(hex(offset), hex(length)))
def data_removed(self, view, offset, length):
results.append("data removed: offset {0} length {1}".format(hex(offset), hex(length)))
def function_added(self, view, func):
results.append("function added: {0}".format(func.name))
def function_removed(self, view, func):
results.append("function removed: {0}".format(func.name))
def data_var_added(self, view, var):
results.append("data var added: {0}".format(hex(var.address)))
def data_var_removed(self, view, var):
results.append("data var removed: {0}".format(hex(var.address)))
def string_found(self, view, string_type, offset, length):
results.append("string found: offset {0} length {1}".format(hex(offset), hex(length)))
def string_removed(self, view, string_type, offset, length):
results.append("string removed: offset {0} length {1}".format(hex(offset), hex(length)))
def type_defined(self, view, name, type):
results.append("type defined: {0}".format(name))
def type_undefined(self, view, name, type):
results.append("type undefined: {0}".format(name))
test = NotifyTest()
bv.register_notification(test)
sacrificial_addr = 0x84fc
type, name = bv.parse_type_string("int foo")
type_id = type.generate_auto_type_id("source", name)
bv.define_type(type_id, name, type)
bv.undefine_type(type_id)
bv.update_analysis_and_wait()
bv.insert(sacrificial_addr, b"AAAA")
bv.update_analysis_and_wait()
bv.define_data_var(sacrificial_addr, binja.types.Type.int(4))
bv.update_analysis_and_wait()
bv.write(sacrificial_addr, b"BBBB")
bv.update_analysis_and_wait()
bv.add_function(sacrificial_addr)
bv.update_analysis_and_wait()
bv.remove_function(bv.get_function_at(sacrificial_addr))
bv.update_analysis_and_wait()
bv.undefine_data_var(sacrificial_addr)
bv.update_analysis_and_wait()
bv.remove(sacrificial_addr, 4)
bv.update_analysis_and_wait()
bv.unregister_notification(test)
return fixOutput(sorted(results))
finally:
self.delete_package("helloworld")
def test_type_xref(self):
"""Type xref failure"""
def dump_type_xref_info(type_name, code_refs, data_refs, type_refs, offset = None):
retinfo = []
if offset is None:
for ref in code_refs:
retinfo.append('type {} is referenced by code {}'.format(type_name, ref))
for ref in data_refs:
retinfo.append('type {} is referenced by data {}'.format(type_name, ref))
for ref in type_refs:
retinfo.append('type {} is referenced by type {}'.format(type_name, ref))
else:
for ref in code_refs:
retinfo.append('type field {}, offset {} is referenced by code {}'.format(type_name, hex(offset), ref))
for ref in data_refs:
retinfo.append('type field {}, offset {} is referenced by data {}'.format(type_name, hex(offset), ref))
for ref in type_refs:
retinfo.append('type field {}, offset {} is referenced by type {}'.format(type_name, hex(offset), ref))
return retinfo
retinfo = []
file_name = self.unpackage_file("type_xref.bndb")
if not os.path.exists(file_name):
return retinfo
with BinaryViewType.get_view_of_file(file_name) as bv:
if bv is None:
return retinfo
types = bv.types
test_types = ['A', 'B', 'C', 'D', 'E', 'F']
for test_type in test_types:
code_refs = bv.get_code_refs_for_type(test_type)
data_refs = bv.get_data_refs_for_type(test_type)
type_refs = bv.get_type_refs_for_type(test_type)
retinfo.extend(dump_type_xref_info(test_type, code_refs, data_refs, type_refs))
t = types[test_type]
if not t:
continue
for member in t.structure.members:
offset = member.offset
code_refs = bv.get_code_refs_for_type_field(test_type, offset)
data_refs = bv.get_data_refs_for_type_field(test_type, offset)
type_refs = bv.get_type_refs_for_type_field(test_type, offset)
retinfo.extend(dump_type_xref_info(test_type, code_refs, data_refs, type_refs, offset))
self.delete_package("type_xref.bndb")
return fixOutput(sorted(retinfo))
def test_variable_xref(self):
"""Variable xref failure"""
def dump_var_xref_info(var, var_refs):
retinfo = []
for ref in var_refs:
retinfo.append('var {} is referenced at {}'.format(repr(var), repr(ref)))
return retinfo
retinfo = []
file_name = self.unpackage_file("type_xref.bndb")
if not os.path.exists(file_name):
return retinfo
with BinaryViewType.get_view_of_file(file_name) as bv:
if bv is None:
return retinfo
func = bv.get_function_at(0x1169)
for var in func.vars:
mlil_refs = func.get_mlil_var_refs(var)
retinfo.extend(dump_var_xref_info(var, mlil_refs))
hlil_refs = func.get_hlil_var_refs(var)
retinfo.extend(dump_var_xref_info(var, hlil_refs))
mlil_range_var_refs = func.get_mlil_var_refs_from(0x1175, 0x8c)
for ref in mlil_range_var_refs:
retinfo.append("var {} is referenced at {}".format(ref.var, ref.src))
hlil_range_var_refs = func.get_hlil_var_refs_from(0x1175, 0x8c)
for ref in hlil_range_var_refs:
retinfo.append("var {} is referenced at {}".format(ref.var, ref.src))
self.delete_package("type_xref.bndb")
return fixOutput(sorted(retinfo))
class VerifyBuilder(Builder):
""" The VerifyBuilder is for tests that verify
Binary Ninja against expected output.
- Function that are tests should start with 'test_'
- Function doc string used as 'on error' message
- Should return: boolean
"""
def __init__(self, test_store):
super(VerifyBuilder, self).__init__(test_store)
def get_functions(self, bv):
return [x.start for x in bv.functions]
def get_comments(self, bv):
return bv.functions[0].comments
def test_possiblevalueset_parse(self):
""" Failed to parse PossibleValueSet from string"""
file_name = self.unpackage_file("helloworld")
try:
with binja.open_view(file_name) as bv:
# ConstantValue
lhs = bv.parse_possiblevalueset("0", binja.RegisterValueType.ConstantValue)
rhs = binja.PossibleValueSet.constant(0)
assert lhs == rhs
lhs = bv.parse_possiblevalueset("$here + 2", binja.RegisterValueType.ConstantValue, 0x2000)
rhs = binja.PossibleValueSet.constant(0x2000 + 2)
assert lhs == rhs
# ConstantPointerValue
lhs = bv.parse_possiblevalueset("0x8000", binja.RegisterValueType.ConstantPointerValue)
rhs = binja.PossibleValueSet.constant_ptr(0x8000)
assert lhs == rhs
# StackFrameOffset
lhs = bv.parse_possiblevalueset("16", binja.RegisterValueType.StackFrameOffset)
rhs = binja.PossibleValueSet.stack_frame_offset(0x16)
assert lhs == rhs
# SignedRangeValue
lhs = bv.parse_possiblevalueset("-10:0:2", binja.RegisterValueType.SignedRangeValue)
rhs = binja.PossibleValueSet.signed_range_value([binja.ValueRange(-0x10, 0, 2)])
assert lhs == rhs
lhs = bv.parse_possiblevalueset("-10:0:2,2:5:1", binja.RegisterValueType.SignedRangeValue)
rhs = binja.PossibleValueSet.signed_range_value([binja.ValueRange(-0x10, 0, 2), binja.ValueRange(2, 5, 1)])
assert lhs == rhs
# UnsignedRangeValue
lhs = bv.parse_possiblevalueset("1:10:1", binja.RegisterValueType.UnsignedRangeValue)
rhs = binja.PossibleValueSet.unsigned_range_value([binja.ValueRange(1, 0x10, 1)])
assert lhs == rhs
lhs = bv.parse_possiblevalueset("1:10:1, 2:20:2", binja.RegisterValueType.UnsignedRangeValue)
rhs = binja.PossibleValueSet.unsigned_range_value([binja.ValueRange(1, 0x10, 1), binja.ValueRange(2, 0x20, 2)])
assert lhs == rhs
# InSetOfValues
lhs = bv.parse_possiblevalueset("1,2,3,3,4", binja.RegisterValueType.InSetOfValues)
rhs = binja.PossibleValueSet.in_set_of_values([1,2,3,4])
assert lhs == rhs
# NotInSetOfValues
lhs = bv.parse_possiblevalueset("1,2,3,4,4", binja.RegisterValueType.NotInSetOfValues)
rhs = binja.PossibleValueSet.not_in_set_of_values([1,2,3,4])
assert lhs == rhs
# UndeterminedValue
lhs = bv.parse_possiblevalueset("", binja.RegisterValueType.UndeterminedValue)
rhs = binja.PossibleValueSet.undetermined()
assert lhs == rhs
return True
finally:
self.delete_package("helloworld")
def test_expression_parse(self):
file_name = self.unpackage_file("helloworld")
try:
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
assert bv.parse_expression("1 + 1") == 2
assert bv.parse_expression("-1 + 1") == 0
assert bv.parse_expression("1 - 1") == 0
assert bv.parse_expression("1 + -1") == 0
assert bv.parse_expression("[0x8000]") == 0x464c457f
assert bv.parse_expression("[0x8000]b") == 0
assert bv.parse_expression("[0x8000].b") == 0x7f
assert bv.parse_expression("[0x8000].w") == 0x457f
assert bv.parse_expression("[0x8000].d") == 0x464c457f
assert bv.parse_expression("[0x8000].q") == 0x10101464c457f
assert bv.parse_expression("$here + 1", 12345) == 12345 + 1
assert bv.parse_expression("_start") == 0x830c
assert bv.parse_expression("_start + 4") == 0x8310
return True
finally:
self.delete_package("helloworld")
def test_verify_BNDB_round_trip(self):
"""Binary Ninja Database output doesn't match its input"""
# This will test Binja's ability to save and restore databases
# By:
# - Creating a binary view
# - Make modification that impact the database
# - Record those modification
# - Save the database
# - Restore the datbase
# - Validate that the modifications are present
file_name = self.unpackage_file("helloworld")
try:
with binja.BinaryViewType['ELF'].get_view_of_file(file_name) as bv:
bv.update_analysis_and_wait()
# Make some modifications to the binary view
# Add a comment
bv.functions[0].set_comment(bv.functions[0].start, "Function start")
# Add a new function
bv.add_function(bv.functions[0].start + 4)
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
comments = self.get_comments(bv)
functions = self.get_functions(bv)
bv.create_database(temp_name)
bv.file.close()
del bv
bv = binja.FileMetadata(temp_name).open_existing_database(temp_name).get_view_of_type('ELF')
bv.update_analysis_and_wait()
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
# force windows to close the handle to the bndb that we want to delete
bv.file.close()
del bv
os.unlink(temp_name)
return [str(functions == bndb_functions and comments == bndb_comments)]
finally:
self.delete_package("helloworld")
def test_verify_persistent_undo(self):
file_name = self.unpackage_file("helloworld")
try:
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
with binja.BinaryViewType['ELF'].get_view_of_file(file_name) as bv:
bv.update_analysis_and_wait()
bv.begin_undo_actions()
bv.functions[0].set_comment(bv.functions[0].start, "Function start")
bv.commit_undo_actions()
bv.update_analysis_and_wait()
comments = self.get_comments(bv)
functions = self.get_functions(bv)
bv.begin_undo_actions()
bv.functions[0].set_comment(bv.functions[0].start, "Function start!")
bv.commit_undo_actions()
bv.begin_undo_actions()
bv.create_user_function(bv.start)
bv.commit_undo_actions()
bv.update_analysis_and_wait()
bv.create_database(temp_name)
with binja.FileMetadata(temp_name).open_existing_database(temp_name).get_view_of_type('ELF') as bv:
bv.update_analysis_and_wait()
bv.undo()
bv.undo()
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
os.unlink(temp_name)
return functions == bndb_functions and comments == bndb_comments
finally:
self.delete_package("helloworld")
def test_memory_leaks(self):
"""Detected memory leaks during analysis"""
# This test will attempt to detect object leaks during headless analysis
file_name = self.unpackage_file("helloworld")
try:
# Open the binary once and let any persistent structures be created (typically types)
bv = binja.BinaryViewType['ELF'].open(file_name)
bv.update_analysis_and_wait()
# Hold on to a graph reference while tearing down the binary view. This will keep a reference
# in the core. If we directly free the view, the teardown will happen in a worker thread and
# we will not be able to get a reliable object count. By keeping a reference in a different
# object in the core, the teardown will occur immediately upon freeing the other object.
graph = bv.functions[0].create_graph()
bv.file.close()
del bv
import gc
gc.collect()
del graph
gc.collect()
initial_object_counts = binja.get_memory_usage_info()
# Analyze the binary again
bv = binja.BinaryViewType['ELF'].open(file_name)
bv.update_analysis_and_wait()
graph = bv.functions[0].create_graph()
bv.file.close()
del bv
gc.collect()
del graph
gc.collect()
# Capture final object count
final_object_counts = binja.get_memory_usage_info()
# Check for leaks
ok = True
for i in initial_object_counts.keys():
if final_object_counts[i] > initial_object_counts[i]:
ok = False
return ok
finally:
self.delete_package("helloworld")
def test_univeral_loader(self):
"""Universal Mach-O Loader Tests"""
file_name = self.unpackage_file("fat_macho_9arch")
save_setting_value = binja.Settings().get_string_list("files.universal.architecturePreference")
binja.Settings().reset("files.universal.architecturePreference")
try:
# test with default arch preference
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86")
assert(bv.start == 0x1000)
load_setting_keys = bv.get_load_settings("Mach-O")
assert(load_setting_keys is not None)
assert(len(bv.get_load_settings("Mach-O").keys()) == 1)
assert(bv.get_load_settings("Mach-O").get_integer("loader.macho.universalImageOffset") == 0x1000)
# save temp bndb for round trip testing
bv.functions[0].set_comment(bv.functions[0].start, "Function start")
comments = self.get_comments(bv)
functions = self.get_functions(bv)
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
bv.create_database(temp_name)
# test get_view_of_file open path
binja.Settings().reset("files.universal.architecturePreference")
with BinaryViewType.get_view_of_file(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86")
assert(bv.start == 0x1000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file_with_options open path
binja.Settings().reset("files.universal.architecturePreference")
with BinaryViewType.get_view_of_file_with_options(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86")
assert(bv.start == 0x1000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file open path (modified architecture preference)
binja.Settings().set_string_list("files.universal.architecturePreference", ["arm64"])
with BinaryViewType.get_view_of_file(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86")
assert(bv.start == 0x1000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file_with_options open path (modified architecture preference)
binja.Settings().set_string_list("files.universal.architecturePreference", ["x86_64", "arm64"])
with BinaryViewType.get_view_of_file_with_options(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86")
assert(bv.start == 0x1000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
os.unlink(temp_name)
# test with overridden arch preference
binja.Settings().set_string_list("files.universal.architecturePreference", ["arm64"])
with binja.BinaryViewType.get_view_of_file(file_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "aarch64")
assert(bv.start == 0x100000000)
load_setting_keys = bv.get_load_settings("Mach-O")
assert(load_setting_keys is not None)
assert(len(bv.get_load_settings("Mach-O").keys()) == 1)
assert(bv.get_load_settings("Mach-O").get_integer("loader.macho.universalImageOffset") == 0x4c000)
# save temp bndb for round trip testing
bv.functions[0].set_comment(bv.functions[0].start, "Function start")
comments = self.get_comments(bv)
functions = self.get_functions(bv)
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
bv.create_database(temp_name)
# test get_view_of_file open path
binja.Settings().reset("files.universal.architecturePreference")
with BinaryViewType.get_view_of_file(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "aarch64")
assert(bv.start == 0x100000000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file_with_options open path
binja.Settings().reset("files.universal.architecturePreference")
with BinaryViewType.get_view_of_file_with_options(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "aarch64")
assert(bv.start == 0x100000000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file open path (modified architecture preference)
binja.Settings().set_string_list("files.universal.architecturePreference", ["x86"])
with BinaryViewType.get_view_of_file(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "aarch64")
assert(bv.start == 0x100000000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
# test get_view_of_file_with_options open path (modified architecture preference)
binja.Settings().set_string_list("files.universal.architecturePreference", ["x86_64", "arm64"])
with BinaryViewType.get_view_of_file_with_options(temp_name) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "aarch64")
assert(bv.start == 0x100000000)
bndb_functions = self.get_functions(bv)
bndb_comments = self.get_comments(bv)
assert([str(functions == bndb_functions and comments == bndb_comments)])
bv.file.close()
os.unlink(temp_name)
binja.Settings().set_string_list("files.universal.architecturePreference", ["x86_64", "arm64"])
with binja.BinaryViewType.get_view_of_file_with_options(file_name, options={'loader.imageBase': 0xfffffff0000}) as bv:
assert(bv.view_type == "Mach-O")
assert(bv.arch.name == "x86_64")
assert(bv.start == 0xfffffff0000)
load_setting_keys = bv.get_load_settings("Mach-O")
assert(load_setting_keys is not None)
assert(len(bv.get_load_settings("Mach-O").keys()) == 8)
assert(bv.get_load_settings("Mach-O").get_integer("loader.macho.universalImageOffset") == 0x8000)
binja.Settings().set_string_list("files.universal.architecturePreference", save_setting_value)
return True
finally:
binja.Settings().set_string_list("files.universal.architecturePreference", save_setting_value)
self.delete_package("fat_macho_9arch")
def test_user_informed_dataflow(self):
"""User-informed dataflow tests"""
file_name = self.unpackage_file("helloworld")
try:
with binja.open_view(file_name) as bv:
func = bv.get_function_at(0x00008440)
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
assert(len(ins.vars_read) == 1)
var = ins.vars_read[0]
defs = func.mlil.get_var_definitions(var)
assert(len(defs) == 1)
def_site = defs[0].address
# Set variable value to 0
bv.begin_undo_actions()
func.set_user_var_value(var, def_site, binja.PossibleValueSet.constant(0))
bv.commit_undo_actions()
bv.update_analysis_and_wait()
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
# test if condition value is updated to true
assert(ins.condition.value == True)
# test if register value is updated to 0
assert(ins.get_reg_value_after('r3') == 0)
# test if branch is eliminated in hlil
for hlil_ins in func.hlil.instructions:
assert(hlil_ins.operation != binja.HighLevelILOperation.HLIL_IF)
# test undo action
bv.undo()
bv.update_analysis_and_wait()
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
# test if condition value is updated to undetermined
assert(ins.condition.value.type == binja.RegisterValueType.UndeterminedValue)
# test if register value is updated to undetermined
assert(ins.get_reg_value_after('r3').type == binja.RegisterValueType.EntryValue)
# test if branch is restored in hlil
found = False
for hlil_ins in func.hlil.instructions:
if hlil_ins.operation == binja.HighLevelILOperation.HLIL_IF:
found = True
assert(found)
# test redo action
bv.redo()
bv.update_analysis_and_wait()
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
# test if condition value is updated to true
assert(ins.condition.value == True)
# test if register value is updated to 0
assert(ins.get_reg_value_after('r3') == 0)
# test if branch is eliminated in hlil
for hlil_ins in func.hlil.instructions:
assert(hlil_ins.operation != binja.HighLevelILOperation.HLIL_IF)
# test bndb round trip
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
bv.create_database(temp_name)
with binja.open_view(temp_name) as bv:
func = bv.get_function_at(0x00008440)
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
# test if condition value is updated to true
assert(ins.condition.value == True)
# test if register value is updated to 0
assert(ins.get_reg_value_after('r3') == 0)
# test if branch is eliminated in hlil
for hlil_ins in func.hlil.instructions:
assert(hlil_ins.operation != binja.HighLevelILOperation.HLIL_IF)
# test undo after round trip
bv.undo()
bv.update_analysis_and_wait()
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
assert(ins.operation == binja.MediumLevelILOperation.MLIL_IF)
# test if condition value is updated to undetermined
assert(ins.condition.value.type == binja.RegisterValueType.UndeterminedValue)
# test if register value is updated to undetermined
assert(ins.get_reg_value_after('r3').type == binja.RegisterValueType.EntryValue)
# test if branch is restored in hlil
found = False
for hlil_ins in func.hlil.instructions:
if hlil_ins.operation == binja.HighLevelILOperation.HLIL_IF:
found = True
assert(found)
os.unlink(temp_name)
return True
finally:
self.delete_package("helloworld")
def test_possiblevalueset_ser_and_deser(self):
"""PossibleValueSet serialization and deserialization"""
def test_helper(value):
file_name = self.unpackage_file("helloworld")
try:
with binja.open_view(file_name) as bv:
func = bv.get_function_at(0x00008440)
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
var = ins.vars_read[0]
defs = func.mlil.get_var_definitions(var)
def_site = defs[0].address
func.set_user_var_value(var, def_site, value)
bv.update_analysis_and_wait()
def_ins_idx = func.mlil.get_instruction_start(def_site)
def_ins = func.mlil[def_ins_idx]
assert(def_ins.get_possible_reg_values_after('r3') == value)
temp_name = next(tempfile._get_candidate_names()) + ".bndb"
bv.create_database(temp_name)
with binja.open_view(temp_name) as bv:
func = bv.get_function_at(0x00008440)
ins_idx = func.mlil.get_instruction_start(0x845c)
ins = func.mlil[ins_idx]
def_ins_idx = func.mlil.get_instruction_start(def_site)
def_ins = func.mlil[def_ins_idx]
assert(def_ins.get_possible_reg_values_after('r3') == value)
os.unlink(temp_name)
return True
finally:
self.delete_package("helloworld")
assert(test_helper(binja.PossibleValueSet.constant(0)))
assert(test_helper(binja.PossibleValueSet.constant_ptr(0x8000)))
assert(test_helper(binja.PossibleValueSet.unsigned_range_value([binja.ValueRange(1, 10, 2)])))
# assert(test_helper(binja.PossibleValueSet.signed_range_value([binja.ValueRange(-10, 0, 2)])))
assert(test_helper(binja.PossibleValueSet.in_set_of_values([1,2,3,4])))
assert(test_helper(binja.PossibleValueSet.not_in_set_of_values([1,2,3,4])))
return True
def test_binaryview_callbacks(self):
"""BinaryView finalized callback and analysis completion callback"""
file_name = self.unpackage_file("helloworld")
# Currently, there is no way to unregister a BinaryView event callback.
# This boolean tells the callback function whether it should run or just return
callback_should_run = True
def bv_finalized_callback(bv):
if callback_should_run:
bv.store_metadata('finalized', 'yes')
def bv_finalized_callback_2(bv):
if callback_should_run:
bv.store_metadata('finalized_2', 'yes')
def bv_analysis_completion_callback(bv):
if callback_should_run:
bv.store_metadata('analysis_completion', 'yes')
BinaryViewType.add_binaryview_finalized_event(bv_finalized_callback)
BinaryViewType.add_binaryview_finalized_event(bv_finalized_callback_2)
BinaryViewType.add_binaryview_initial_analysis_completion_event(bv_analysis_completion_callback)
try:
with binja.open_view(file_name) as bv:
finalized = bv.query_metadata('finalized') == 'yes'
finalized_2 = bv.query_metadata('finalized_2') == 'yes'
analysis_completion = bv.query_metadata('analysis_completion') == 'yes'
return finalized and finalized_2 and analysis_completion
finally:
self.delete_package("helloworld")
callback_should_run = False
def test_load_old_database(self):
"""Load a database produced by Binary Ninja v1.2.1921"""
file_name = self.unpackage_file("binja_v1.2.1921_bin_ls.bndb")
if not os.path.exists(file_name):
return False
binja.Settings().set_bool("analysis.database.suppressReanalysis", True)
ret = None
with BinaryViewType.get_view_of_file_with_options(file_name) as bv:
if bv is None:
ret = False
if bv.file.snapshot_data_applied_without_error:
ret = True
binja.Settings().reset("analysis.database.suppressReanalysis")
self.delete_package("binja_v1.2.1921_bin_ls.bndb")
return ret
|
python
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
d=[0]*(n+1)
max_val=0
for query in queries:
d[query[0]-1]+=query[2]
d[query[1]]+=query[2]*(-1)
max_dif=0
for i in d:
max_dif+=i
if max_val<max_dif:
max_val=max_dif
return max_val
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
fptr.write(str(result) + '\n')
fptr.close()
|
python
|
from model.model.space.space import Space
from model.model.space.space import Space
from watchmen.auth.storage.user_group import get_user_group_list_by_ids, update_user_group_storage, USER_GROUPS
from watchmen.auth.user_group import UserGroup
from watchmen_boot.guid.snowflake import get_surrogate_key
from watchmen.common.utils.data_utils import check_fake_id
from watchmen.database.find_storage_template import find_storage_template
from watchmen.space.storage.space_storage import insert_space_to_storage, update_space_to_storage
storage_template = find_storage_template()
def create_space(space: Space) -> Space:
if space.spaceId is None or check_fake_id(space.spaceId):
space.spaceId = get_surrogate_key()
if type(space) is not dict:
space = space.dict()
return insert_space_to_storage(space)
def update_space_by_id(space_id: str, space: Space) -> Space:
if type(space) is not dict:
space = space.dict()
return update_space_to_storage(space_id, space)
# def load_space(name: str) -> List[Space]:
# return load_space_by_name(name)
def sync_space_to_user_group(space: Space, current_user):
storage_template.pull_update({"spaceIds": {"in": [space.spaceId]}}, {"spaceIds": {"in": [space.spaceId]}},
UserGroup, USER_GROUPS)
user_group_list = get_user_group_list_by_ids(space.groupIds, current_user)
for user_group in user_group_list:
if user_group.spaceIds is None:
user_group.spaceIds = []
if space.spaceId not in user_group.spaceIds:
user_group.spaceIds.append(space.spaceId)
update_user_group_storage(user_group)
|
python
|
from scipy.spatial.distance import pdist, squareform
from causality.greedyBuilder.scores import mutual_info_pairwise
import networkx as nx
class TreeBuilder:
def __init__(self, score=None):
if score is None:
self.score = mutual_info_pairwise
else:
self.score = score
def build_graph(self, data):
return squareform(pdist(data.T, metric=self.score), force='tomatrix', checks=False)
def build_tree(self, data):
graph = self.build_graph(data)
return nx.maximum_spanning_arborescence(nx.from_numpy_matrix(graph).to_directed())
|
python
|
"""Interval set abstract type"""
import datetime
import collections
__version__ = "0.1.5"
_InternalInterval = collections.namedtuple("Interval", ["begin", "end"])
class Interval(_InternalInterval):
"""Represent an immutable interval, with beginning and ending value.
To create a new interval:
Interval(0, 10)
Begin and end values must be immutable ordered types.
Especially useful with datetime instances:
begin = datetime.datetime(...)
end = datetime.datetime(...)
Interval(begin, end)
These are closed intervals, and the beginning value must be smaller than the ending value.
Intervals with the same starting and ending value are considered empty, and are represented with
EMPTY_INTERVAL. The EMPTY_INTERVAL constant is a singleton, and its boolean value is False.
All other intervals are True. The EMPTY_INTERVAL is smaller than any other non-empty interval.
Operators for intervals:
"&" - intersection
"|" - unification, but it can only be applied to overlapping or touching non-empty intervals.
"in" - if an interval contains another interval completely.
"""
def __new__(cls, begin, end):
"""Create a new instance of Interval(begin, end)"""
global EMPTY_INTERVAL
if EMPTY_INTERVAL is not None and begin is None or end is None or end < begin:
return EMPTY_INTERVAL
else:
return _InternalInterval.__new__(cls, begin, end)
def __bool__(self):
return self is not EMPTY_INTERVAL
def __and__(self, other):
"""Return the intersection of this interval and another.
A zero-length intersection
When there is no intersection, it returns EMPTY_INTERVAl."""
global EMPTY_INTERVAL
if not self or not other or self.end < other.begin or other.end < self.begin:
return EMPTY_INTERVAL
elif self.begin >= other.begin and self.end <= other.end:
# This interval is completely within the other.
return self
elif other.begin >= self.begin and other.end <= self.end:
# The other interval is completely within this
return other
else:
# They overlap proper.
if self.begin > other.begin:
begin = self.begin
else:
begin = other.begin
if self.end < other.end:
end = self.end
else:
end = other.end
return Interval(begin, end)
def __or__(self, other):
"""Unify two overlapping intervals. When called with non-overlapping intervals, raises ValueError."""
if not self or not other or self.end < other.begin or other.end < self.begin:
raise ValueError("Cannot unify non-overlapping intervals. (Use interval sets for that.)")
elif self.begin >= other.begin and self.end <= other.end:
# This interval is completely within the other.
return other
elif other.begin >= self.begin and other.end <= self.end:
# The other interval is completely within this
return self
else:
# They overlap proper.
if self.begin > other.begin:
begin = other.begin
else:
begin = self.begin
if self.end < other.end:
end = other.end
else:
end = self.end
return Interval(begin, end)
def __contains__(self, other):
if not self:
return False # An empty interval does not contain anything, even another empty interval.
elif not other:
return False # This is an interesting question... is an empty interval inside a non-empty one?
else:
return other.begin >= self.begin and other.end <= self.end
def is_before_than(self, other):
"""Tells if this interval is completely before the other. (Empty intervals are before everything.)"""
return (self is EMPTY_INTERVAL) or (other is EMPTY_INTERVAL) or self.end < other.begin
def is_after_than(self, other):
"""Tells if this interval is completely after the other. (Empty intervals are before everything.)"""
if self is EMPTY_INTERVAL or other is EMPTY_INTERVAL:
return False
else:
return other.end < self.begin
def __str__(self):
"""Human-readable representation."""
name = self.__class__.__name__
if self:
if isinstance(self.begin, datetime.datetime):
w = 8
res = str(self.begin.date()) + " " + str(self.begin.time())[:w] + "->"
if self.begin.date() != self.end.date():
res += str(self.end.date())
res += str(self.end.time())[:w]
else:
res = "%s, %s" % (self.begin, self.end)
return "%s(%s)" % (name, res)
else:
return "%s(<empty>)" % name
EMPTY_INTERVAL = None # Define it so that __new__ can check it.
EMPTY_INTERVAL = Interval(None, None)
class IntervalSet(object):
"""A set of intervals.
IntervalSet is also immutable. To create a new set, pass elements to the constructor:
IntervalSet( interval1, interval2, interval3... )
Arguments should be Interval objects. The order is insignificant - they will automatically be unified and ordered
by the constructor. Empty intervals will be simply ignored (and absent from the set). Sets can be iterated
over.
Operators on interval sets:
* | union
* & intersection
* - difference
* ^ symmetric difference
* "in" - containment for an element
* "in" - containment for a set
"""
def __init__(self, *items):
self._fill_items(items)
self._hash = None
def _fill_items(self, items):
_items = []
if items:
it = iter(sorted(items))
# Get first non-empty interval
i1 = None
for i1 in it:
if i1:
break
# Unify with other items
for i2 in it:
if i1.is_before_than(i2):
# Next item is completely before the current one. Store the current.
_items.append(i1)
i1 = i2
elif i1 & i2 or i1.end == i2.begin:
# Next item overlaps with the current item. Unify them.
i1 = i1 | i2
else:
raise Exception("Internal error") # This should never happen when items are sorted.
# Add last remaining item
if i1:
_items.append(i1)
# Make it immutable, hashable
self._items = tuple(_items)
def __hash__(self):
if self._hash is None:
self._hash = hash(self._items)
return self._hash
def __eq__(self, other):
return hash(self) == hash(other)
def __iter__(self):
return iter(self._items)
def __len__(self):
return len(self._items)
def __and__(self, other):
"""Make a intersections of this interval set and another."""
# Intersection with an empty set is empty.
if not self:
return self
if not other:
return other
# We know that items are sorted, so we can do this incrementally in O(N) time.
new_items = []
it1 = iter(self)
it2 = iter(other)
i1 = next(it1)
i2 = next(it2)
try:
while True:
if i1.is_before_than(i2):
i1 = next(it1)
elif i2.is_before_than(i1):
i2 = next(it2)
else:
i3 = i1 & i2
if i3:
new_items.append(i3)
if i1.end < i2.end:
i1 = next(it1)
else:
i2 = next(it2)
except StopIteration:
pass
return IntervalSet(*new_items)
def __or__(self, other):
"""Make a union of two interval sets."""
# Union with an empty set...
if not self:
return other
if not other:
return self
# We know that items are sorted, so we can do this incrementally in O(N) time.
new_items = []
it1 = iter(self)
it2 = iter(other)
i1 = next(it1)
i2 = next(it2)
remaining = None
while True:
if i1.is_before_than(i2):
new_items.append(i1)
try:
i1 = next(it1)
except StopIteration:
new_items.append(i2)
remaining = it2
break
elif i2.is_before_than(i1):
new_items.append(i2)
try:
i2 = next(it2)
except StopIteration:
new_items.append(i1)
remaining = it1
break
else:
# They overlap, create a new unified item.
new_items.append(i1 | i2)
try:
i1 = next(it1)
except StopIteration:
remaining = it2
break
try:
i2 = next(it2)
except StopIteration:
new_items.append(i1)
break
if remaining:
new_items += list(remaining)
return IntervalSet(*new_items)
def __sub__(self, other):
"""Substract other set from this set."""
if not self:
return self
if not other:
return self
# We know that items are sorted, so we can do this incrementally in O(N) time.
new_items = []
it1 = iter(self)
it2 = iter(other)
b1, e1 = next(it1)
b2, e2 = next(it2)
try:
while True:
# If i1 became empty, advance to next item.
if b1 >= e1:
b1, e1 = None, None
b1, e1 = next(it1)
continue
if e1 <= b2: # i1 is completely before i2
new_items.append(Interval(b1, e1))
b1, e1 = None, None
b1, e1 = next(it1)
continue
if e2 <= b1: # i2 is completely before i1
b2, e2 = next(it2)
continue
if b1 < b2 <= e1 <= e2: # overlap, i1 starts sooner
new_items.append(Interval(b1, b2))
b1, e1 = None, None
b1, e1 = next(it1)
continue
if b2 <= b1 <= e2 < e1: # overlap, i2 starts sooner
# You might think that (e2, e1) can be added, but it cannot yet.
# There can be other items in it2 that needs to be substracted from (e2, e1)
b1 = e2
b2, e2 = next(it2)
continue
if b2 <= b1 <= e1 <= e2: # i2 contains i1
b1, e1 = None, None
b1, e1 = next(it1)
continue
if b1 < b2 <= e2 <= e1: # i1 contains i2
new_items.append(Interval(b1, b2))
b1 = e2
except StopIteration:
pass
# Add the last item, if available.
if b1 and e1 and b1 < e1:
new_items.append(Interval(b1, e1))
new_items += list(it1)
return IntervalSet(*new_items)
def __xor__(self, other):
"""Simmetric difference."""
return (self | other) - (self & other)
def __contains__(self, other):
"""Containment relation.
Tell if `other` is contained *completely* in this set. The argument can either be an Interval or an
IntervalSet.
"""
if isinstance(other, Interval):
# TODO: use binary search instead of linear search.
for item in self:
if other in item:
return True
return False
else:
# Contains the other set completely.
return (self & other) == other
def __getitem__(self, index):
"""Get element by its index. (IntervalSet stores elements in an increasing order!)"""
return self._items[index]
def min(self):
"""Return the smallest element in the set.
For empty sets, returns None."""
if self._items:
return self._items[0]
def max(self):
"""Return the biggest element in the set.
For empty sets, returns None."""
if self._items:
return self._items[-1]
def __str__(self):
"""Human-readable representation."""
name = self.__class__.__name__
if self:
if len(self) < 10:
parts = []
if isinstance(self._items[0].begin, datetime.datetime):
w = 8
last_date = None
for item in self:
sitem = "["
if not last_date or last_date!= item.begin.date():
last_date = item.begin.date()
sitem += str(last_date) + " "
sitem += str(item.begin.time())[:w] + " -> "
if last_date != item.end.date():
last_date = item.end.date()
sitem += str(last_date) + " "
sitem += str(item.end.time())[:w] + "]"
parts.append(sitem)
else:
parts = ["[%s -> %s]" % (item.begin, item.end) for item in self]
return "%s(%s)" % (name, ",".join(parts))
else:
return "%s(%d items between %s and %s)" % (name, len(self), self._items[0], self._items[-1] )
else:
return "%s(<empty>)" % name
|
python
|
#!/usr/bin/env python3
from ctypes import cdll, c_char_p, c_int, create_string_buffer, c_long
SO_PATH="/home/***************/libAdAuth/libAdAuth.so"
username = create_string_buffer(b"********")
password = create_string_buffer(b"********")
host = create_string_buffer(b"*********.uk")
domain = create_string_buffer(b"*******.uk")
port = 0
lib = cdll.LoadLibrary(SO_PATH)
lib.auth.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_long]
lib.auth.restype = c_int
auth = lib.auth(username, password, host, domain, port)
|
python
|
# rearrange name of data in anat directories,
# delete repeated task-name pattern, add missing pattern
import os
# change to main directory
main_directory = '/mindhive/saxelab3/anzellotti/forrest/forrest_bids/'
#main_directory = '/Users/chloe/Documents/test10/'
os.chdir(main_directory)
# get all subject folders in main directory
all_folder_names = os.listdir(main_directory)
# iterate through all subjects to arrange files
for sub in all_folder_names:
if sub == '.DS_Store' or sub == 'dataset_description.json' or sub == '.bidsignore' :
continue
# rename files in ses-localizer/anat
os.chdir(main_directory+sub+'/ses-localizer/anat')
list_of_anat = os.listdir('.')
for anat_file in list_of_anat:
if 'defacemask' in anat_file:
os.rename(anat_file, main_directory+sub+'/ses-localizer/anat/'+sub+'_ses-localizer_mod-T1w_defacemask.nii.gz')
print('RENAME SUCCESS: '+ anat_file)
# rename files in ses-movie/anat
os.chdir(main_directory+sub+'/ses-movie/anat')
list_of_anat2 = os.listdir('.')
for anat_file2 in list_of_anat2:
if 'defacemask' in anat_file2:
print(anat_file2+' FOUND')
os.rename(anat_file2, main_directory+sub+'/ses-movie/anat/'+sub+'_ses-movie_mod-T1w_defacemask.nii.gz')
print('RENAME SUCCESS: ' + anat_file2)
|
python
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.ohio import ohio
def test_ohio():
"""Test module ohio.py by downloading
ohio.csv and testing shape of
extracted data has 2148 rows and 4 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = ohio(test_path)
try:
assert x_train.shape == (2148, 4)
except:
shutil.rmtree(test_path)
raise()
|
python
|
class User:
"""
This class will contain all the details of the user
"""
def __init__(self,login,password):
"""
This will create the information of (Levert) the user
"""
self.login = login
self.password = password
# Levert
def user_exists(self,password):
"""Levert Co
This enables you to enter the password you created this account with and if it exits it will show you your stored password.Levert\
Args:
Password Lockers user's signup password
Return:
boolean-the data type that has one of two possible values
"""
if self.password == password:
return True
return False
|
python
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .cqlhandling import CqlParsingRuleSet, Hint
from cassandra.metadata import maybe_escape_name
from cassandra.metadata import escape_name
simple_cql_types = set(('ascii', 'bigint', 'blob', 'boolean', 'counter', 'date', 'decimal', 'double', 'float', 'inet', 'int',
'smallint', 'text', 'time', 'timestamp', 'timeuuid', 'tinyint', 'uuid', 'varchar', 'varint'))
simple_cql_types.difference_update(('set', 'map', 'list'))
from . import helptopics
cqldocs = helptopics.CQL3HelpTopics()
class UnexpectedTableStructure(UserWarning):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return 'Unexpected table structure; may not translate correctly to CQL. ' + self.msg
SYSTEM_KEYSPACES = ('system', 'system_traces', 'system_auth', 'system_distributed')
NONALTERBALE_KEYSPACES = ('system')
class Cql3ParsingRuleSet(CqlParsingRuleSet):
columnfamily_layout_options = (
('bloom_filter_fp_chance', None),
('comment', None),
('dclocal_read_repair_chance', 'local_read_repair_chance'),
('gc_grace_seconds', None),
('min_index_interval', None),
('max_index_interval', None),
('read_repair_chance', None),
('default_time_to_live', None),
('speculative_retry', None),
('memtable_flush_period_in_ms', None),
)
columnfamily_layout_map_options = (
# (CQL3 option name, schema_columnfamilies column name (or None if same),
# list of known map keys)
('compaction', 'compaction_strategy_options',
('class', 'max_threshold', 'tombstone_compaction_interval', 'tombstone_threshold', 'enabled', 'unchecked_tombstone_compaction')),
('compression', 'compression_parameters',
('sstable_compression', 'chunk_length_kb', 'crc_check_chance')),
('caching', None,
('rows_per_partition', 'keys')),
)
obsolete_cf_options = ()
consistency_levels = (
'ANY',
'ONE',
'TWO',
'THREE',
'QUORUM',
'ALL',
'LOCAL_QUORUM',
'EACH_QUORUM',
'SERIAL'
)
@classmethod
def escape_value(cls, value):
if value is None:
return 'NULL' # this totally won't work
if isinstance(value, bool):
value = str(value).lower()
elif isinstance(value, float):
return '%f' % value
elif isinstance(value, int):
return str(value)
return "'%s'" % value.replace("'", "''")
@staticmethod
def dequote_name(name):
name = name.strip()
if name == '':
return name
if name[0] == '"' and name[-1] == '"':
return name[1:-1].replace('""', '"')
else:
return name.lower()
@staticmethod
def dequote_value(cqlword):
cqlword = cqlword.strip()
if cqlword == '':
return cqlword
if cqlword[0] == "'" and cqlword[-1] == "'":
cqlword = cqlword[1:-1].replace("''", "'")
return cqlword
CqlRuleSet = Cql3ParsingRuleSet()
# convenience for remainder of module
completer_for = CqlRuleSet.completer_for
explain_completion = CqlRuleSet.explain_completion
dequote_value = CqlRuleSet.dequote_value
dequote_name = CqlRuleSet.dequote_name
escape_value = CqlRuleSet.escape_value
# BEGIN SYNTAX/COMPLETION RULE DEFINITIONS
syntax_rules = r'''
<Start> ::= <CQL_Statement>*
;
<CQL_Statement> ::= [statements]=<statementBody> ";"
;
# the order of these terminal productions is significant:
<endline> ::= /\n/ ;
JUNK ::= /([ \t\r\f\v]+|(--|[/][/])[^\n\r]*([\n\r]|$)|[/][*].*?[*][/])/ ;
<stringLiteral> ::= <quotedStringLiteral>
| <pgStringLiteral> ;
<quotedStringLiteral> ::= /'([^']|'')*'/ ;
<pgStringLiteral> ::= /\$\$.*\$\$/;
<quotedName> ::= /"([^"]|"")*"/ ;
<float> ::= /-?[0-9]+\.[0-9]+/ ;
<uuid> ::= /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ ;
<blobLiteral> ::= /0x[0-9a-f]+/ ;
<wholenumber> ::= /[0-9]+/ ;
<identifier> ::= /[a-z][a-z0-9_]*/ ;
<colon> ::= ":" ;
<star> ::= "*" ;
<endtoken> ::= ";" ;
<op> ::= /[-+=,().]/ ;
<cmp> ::= /[<>]=?/ ;
<brackets> ::= /[][{}]/ ;
<integer> ::= "-"? <wholenumber> ;
<boolean> ::= "true"
| "false"
;
<unclosedString> ::= /'([^']|'')*/ ;
<unclosedName> ::= /"([^"]|"")*/ ;
<unclosedComment> ::= /[/][*].*$/ ;
<term> ::= <stringLiteral>
| <integer>
| <float>
| <uuid>
| <boolean>
| <blobLiteral>
| <collectionLiteral>
| <functionName> <functionArguments>
| "NULL"
;
<functionArguments> ::= "(" ( <term> ( "," <term> )* )? ")"
;
<tokenDefinition> ::= token="TOKEN" "(" <term> ( "," <term> )* ")"
| <term>
;
<cident> ::= <quotedName>
| <identifier>
| <unreservedKeyword>
;
<colname> ::= <cident> ; # just an alias
<collectionLiteral> ::= <listLiteral>
| <setLiteral>
| <mapLiteral>
;
<listLiteral> ::= "[" ( <term> ( "," <term> )* )? "]"
;
<setLiteral> ::= "{" ( <term> ( "," <term> )* )? "}"
;
<mapLiteral> ::= "{" <term> ":" <term> ( "," <term> ":" <term> )* "}"
;
<anyFunctionName> ::= ( ksname=<cfOrKsName> dot="." )? udfname=<cfOrKsName> ;
<userFunctionName> ::= ( ksname=<nonSystemKeyspaceName> dot="." )? udfname=<cfOrKsName> ;
<refUserFunctionName> ::= udfname=<cfOrKsName> ;
<userAggregateName> ::= ( ksname=<nonSystemKeyspaceName> dot="." )? udaname=<cfOrKsName> ;
<functionAggregateName> ::= ( ksname=<nonSystemKeyspaceName> dot="." )? functionname=<cfOrKsName> ;
<aggregateName> ::= <userAggregateName>
;
<functionName> ::= <functionAggregateName>
| "TOKEN"
;
<statementBody> ::= <useStatement>
| <selectStatement>
| <dataChangeStatement>
| <schemaChangeStatement>
| <authenticationStatement>
| <authorizationStatement>
;
<dataChangeStatement> ::= <insertStatement>
| <updateStatement>
| <deleteStatement>
| <truncateStatement>
| <batchStatement>
;
<schemaChangeStatement> ::= <createKeyspaceStatement>
| <createColumnFamilyStatement>
| <createIndexStatement>
| <createUserTypeStatement>
| <createFunctionStatement>
| <createAggregateStatement>
| <createTriggerStatement>
| <dropKeyspaceStatement>
| <dropColumnFamilyStatement>
| <dropIndexStatement>
| <dropUserTypeStatement>
| <dropFunctionStatement>
| <dropAggregateStatement>
| <dropTriggerStatement>
| <alterTableStatement>
| <alterKeyspaceStatement>
| <alterUserTypeStatement>
;
<authenticationStatement> ::= <createUserStatement>
| <alterUserStatement>
| <dropUserStatement>
| <listUsersStatement>
| <createRoleStatement>
| <alterRoleStatement>
| <dropRoleStatement>
| <listRolesStatement>
;
<authorizationStatement> ::= <grantStatement>
| <grantRoleStatement>
| <revokeStatement>
| <revokeRoleStatement>
| <listPermissionsStatement>
;
# timestamp is included here, since it's also a keyword
<simpleStorageType> ::= typename=( <identifier> | <stringLiteral> | "timestamp" ) ;
<userType> ::= utname=<cfOrKsName> ;
<storageType> ::= <simpleStorageType> | <collectionType> | <frozenCollectionType> | <userType> ;
# Note: autocomplete for frozen collection types does not handle nesting past depth 1 properly,
# but that's a lot of work to fix for little benefit.
<collectionType> ::= "map" "<" <simpleStorageType> "," ( <simpleStorageType> | <userType> ) ">"
| "list" "<" ( <simpleStorageType> | <userType> ) ">"
| "set" "<" ( <simpleStorageType> | <userType> ) ">"
;
<frozenCollectionType> ::= "frozen" "<" "map" "<" <storageType> "," <storageType> ">" ">"
| "frozen" "<" "list" "<" <storageType> ">" ">"
| "frozen" "<" "set" "<" <storageType> ">" ">"
;
<columnFamilyName> ::= ( ksname=<cfOrKsName> dot="." )? cfname=<cfOrKsName> ;
<userTypeName> ::= ( ksname=<cfOrKsName> dot="." )? utname=<cfOrKsName> ;
<keyspaceName> ::= ksname=<cfOrKsName> ;
<nonSystemKeyspaceName> ::= ksname=<cfOrKsName> ;
<alterableKeyspaceName> ::= ksname=<cfOrKsName> ;
<cfOrKsName> ::= <identifier>
| <quotedName>
| <unreservedKeyword>;
<unreservedKeyword> ::= nocomplete=
( "key"
| "clustering"
# | "count" -- to get count(*) completion, treat count as reserved
| "ttl"
| "compact"
| "storage"
| "type"
| "values" )
;
<property> ::= [propname]=<cident> propeq="=" [propval]=<propertyValue>
;
<propertyValue> ::= propsimpleval=( <stringLiteral>
| <identifier>
| <integer>
| <float>
| <unreservedKeyword> )
# we don't use <mapLiteral> here so we can get more targeted
# completions:
| propsimpleval="{" [propmapkey]=<term> ":" [propmapval]=<term>
( ender="," [propmapkey]=<term> ":" [propmapval]=<term> )*
ender="}"
;
'''
def prop_equals_completer(ctxt, cass):
if not working_on_keyspace(ctxt):
# we know if the thing in the property name position is "compact" or
# "clustering" that there won't actually be an equals sign, because
# there are no properties by those names. there are, on the other hand,
# table properties that start with those keywords which don't have
# equals signs at all.
curprop = ctxt.get_binding('propname')[-1].upper()
if curprop in ('COMPACT', 'CLUSTERING'):
return ()
return ['=']
completer_for('property', 'propeq')(prop_equals_completer)
@completer_for('property', 'propname')
def prop_name_completer(ctxt, cass):
if working_on_keyspace(ctxt):
return ks_prop_name_completer(ctxt, cass)
else:
return cf_prop_name_completer(ctxt, cass)
@completer_for('propertyValue', 'propsimpleval')
def prop_val_completer(ctxt, cass):
if working_on_keyspace(ctxt):
return ks_prop_val_completer(ctxt, cass)
else:
return cf_prop_val_completer(ctxt, cass)
@completer_for('propertyValue', 'propmapkey')
def prop_val_mapkey_completer(ctxt, cass):
if working_on_keyspace(ctxt):
return ks_prop_val_mapkey_completer(ctxt, cass)
else:
return cf_prop_val_mapkey_completer(ctxt, cass)
@completer_for('propertyValue', 'propmapval')
def prop_val_mapval_completer(ctxt, cass):
if working_on_keyspace(ctxt):
return ks_prop_val_mapval_completer(ctxt, cass)
else:
return cf_prop_val_mapval_completer(ctxt, cass)
@completer_for('propertyValue', 'ender')
def prop_val_mapender_completer(ctxt, cass):
if working_on_keyspace(ctxt):
return ks_prop_val_mapender_completer(ctxt, cass)
else:
return cf_prop_val_mapender_completer(ctxt, cass)
def ks_prop_name_completer(ctxt, cass):
optsseen = ctxt.get_binding('propname', ())
if 'replication' not in optsseen:
return ['replication']
return ["durable_writes"]
def ks_prop_val_completer(ctxt, cass):
optname = ctxt.get_binding('propname')[-1]
if optname == 'durable_writes':
return ["'true'", "'false'"]
if optname == 'replication':
return ["{'class': '"]
return ()
def ks_prop_val_mapkey_completer(ctxt, cass):
optname = ctxt.get_binding('propname')[-1]
if optname != 'replication':
return ()
keysseen = map(dequote_value, ctxt.get_binding('propmapkey', ()))
valsseen = map(dequote_value, ctxt.get_binding('propmapval', ()))
for k, v in zip(keysseen, valsseen):
if k == 'class':
repclass = v
break
else:
return ["'class'"]
if repclass in CqlRuleSet.replication_factor_strategies:
opts = set(('replication_factor',))
elif repclass == 'NetworkTopologyStrategy':
return [Hint('<dc_name>')]
return map(escape_value, opts.difference(keysseen))
def ks_prop_val_mapval_completer(ctxt, cass):
optname = ctxt.get_binding('propname')[-1]
if optname != 'replication':
return ()
currentkey = dequote_value(ctxt.get_binding('propmapkey')[-1])
if currentkey == 'class':
return map(escape_value, CqlRuleSet.replication_strategies)
return [Hint('<term>')]
def ks_prop_val_mapender_completer(ctxt, cass):
optname = ctxt.get_binding('propname')[-1]
if optname != 'replication':
return [',']
keysseen = map(dequote_value, ctxt.get_binding('propmapkey', ()))
valsseen = map(dequote_value, ctxt.get_binding('propmapval', ()))
for k, v in zip(keysseen, valsseen):
if k == 'class':
repclass = v
break
else:
return [',']
if repclass in CqlRuleSet.replication_factor_strategies:
if 'replication_factor' not in keysseen:
return [',']
if repclass == 'NetworkTopologyStrategy' and len(keysseen) == 1:
return [',']
return ['}']
def cf_prop_name_completer(ctxt, cass):
return [c[0] for c in (CqlRuleSet.columnfamily_layout_options +
CqlRuleSet.columnfamily_layout_map_options)]
def cf_prop_val_completer(ctxt, cass):
exist_opts = ctxt.get_binding('propname')
this_opt = exist_opts[-1]
if this_opt == 'compression':
return ["{'sstable_compression': '"]
if this_opt == 'compaction':
return ["{'class': '"]
if this_opt == 'caching':
return ["{'keys': '"]
if any(this_opt == opt[0] for opt in CqlRuleSet.obsolete_cf_options):
return ["'<obsolete_option>'"]
if this_opt in ('read_repair_chance', 'bloom_filter_fp_chance',
'dclocal_read_repair_chance'):
return [Hint('<float_between_0_and_1>')]
if this_opt in ('min_compaction_threshold', 'max_compaction_threshold',
'gc_grace_seconds', 'min_index_interval', 'max_index_interval'):
return [Hint('<integer>')]
return [Hint('<option_value>')]
def cf_prop_val_mapkey_completer(ctxt, cass):
optname = ctxt.get_binding('propname')[-1]
for cql3option, _, subopts in CqlRuleSet.columnfamily_layout_map_options:
if optname == cql3option:
break
else:
return ()
keysseen = map(dequote_value, ctxt.get_binding('propmapkey', ()))
valsseen = map(dequote_value, ctxt.get_binding('propmapval', ()))
pairsseen = dict(zip(keysseen, valsseen))
if optname == 'compression':
return map(escape_value, set(subopts).difference(keysseen))
if optname == 'caching':
return map(escape_value, set(subopts).difference(keysseen))
if optname == 'compaction':
opts = set(subopts)
try:
csc = pairsseen['class']
except KeyError:
return ["'class'"]
csc = csc.split('.')[-1]
if csc == 'SizeTieredCompactionStrategy':
opts.add('min_sstable_size')
opts.add('min_threshold')
opts.add('bucket_high')
opts.add('bucket_low')
elif csc == 'LeveledCompactionStrategy':
opts.add('sstable_size_in_mb')
elif csc == 'DateTieredCompactionStrategy':
opts.add('base_time_seconds')
opts.add('max_sstable_age_days')
opts.add('timestamp_resolution')
opts.add('min_threshold')
return map(escape_value, opts)
return ()
def cf_prop_val_mapval_completer(ctxt, cass):
opt = ctxt.get_binding('propname')[-1]
key = dequote_value(ctxt.get_binding('propmapkey')[-1])
if opt == 'compaction':
if key == 'class':
return map(escape_value, CqlRuleSet.available_compaction_classes)
return [Hint('<option_value>')]
elif opt == 'compression':
if key == 'sstable_compression':
return map(escape_value, CqlRuleSet.available_compression_classes)
return [Hint('<option_value>')]
elif opt == 'caching':
if key == 'rows_per_partition':
return ["'ALL'", "'NONE'", Hint('#rows_per_partition')]
elif key == 'keys':
return ["'ALL'", "'NONE'"]
return ()
def cf_prop_val_mapender_completer(ctxt, cass):
return [',', '}']
@completer_for('tokenDefinition', 'token')
def token_word_completer(ctxt, cass):
return ['token(']
@completer_for('simpleStorageType', 'typename')
def storagetype_completer(ctxt, cass):
return simple_cql_types
@completer_for('keyspaceName', 'ksname')
def ks_name_completer(ctxt, cass):
return map(maybe_escape_name, cass.get_keyspace_names())
@completer_for('nonSystemKeyspaceName', 'ksname')
def ks_name_completer(ctxt, cass):
ksnames = [n for n in cass.get_keyspace_names() if n not in SYSTEM_KEYSPACES]
return map(maybe_escape_name, ksnames)
@completer_for('alterableKeyspaceName', 'ksname')
def ks_name_completer(ctxt, cass):
ksnames = [n for n in cass.get_keyspace_names() if n not in NONALTERBALE_KEYSPACES]
return map(maybe_escape_name, ksnames)
def cf_ks_name_completer(ctxt, cass):
return [maybe_escape_name(ks) + '.' for ks in cass.get_keyspace_names()]
completer_for('columnFamilyName', 'ksname')(cf_ks_name_completer)
def cf_ks_dot_completer(ctxt, cass):
name = dequote_name(ctxt.get_binding('ksname'))
if name in cass.get_keyspace_names():
return ['.']
return []
completer_for('columnFamilyName', 'dot')(cf_ks_dot_completer)
@completer_for('columnFamilyName', 'cfname')
def cf_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
cfnames = cass.get_columnfamily_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, cfnames)
completer_for('userTypeName', 'ksname')(cf_ks_name_completer)
completer_for('userTypeName', 'dot')(cf_ks_dot_completer)
def ut_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
utnames = cass.get_usertype_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, utnames)
completer_for('userTypeName', 'utname')(ut_name_completer)
completer_for('userType', 'utname')(ut_name_completer)
@completer_for('unreservedKeyword', 'nocomplete')
def unreserved_keyword_completer(ctxt, cass):
# we never want to provide completions through this production;
# this is always just to allow use of some keywords as column
# names, CF names, property values, etc.
return ()
def get_table_meta(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
cf = dequote_name(ctxt.get_binding('cfname'))
return cass.get_table_meta(ks, cf)
def get_ut_layout(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
ut = dequote_name(ctxt.get_binding('utname'))
return cass.get_usertype_layout(ks, ut)
def working_on_keyspace(ctxt):
wat = ctxt.get_binding('wat').upper()
if wat in ('KEYSPACE', 'SCHEMA'):
return True
return False
syntax_rules += r'''
<useStatement> ::= "USE" <keyspaceName>
;
<selectStatement> ::= "SELECT" ( "JSON" )? <selectClause>
"FROM" cf=<columnFamilyName>
( "WHERE" <whereClause> )?
( "ORDER" "BY" <orderByClause> ( "," <orderByClause> )* )?
( "LIMIT" limit=<wholenumber> )?
( "ALLOW" "FILTERING" )?
;
<whereClause> ::= <relation> ( "AND" <relation> )*
;
<relation> ::= [rel_lhs]=<cident> ( "[" <term> "]" )? ( "=" | "<" | ">" | "<=" | ">=" | "CONTAINS" ( "KEY" )? ) <term>
| token="TOKEN" "(" [rel_tokname]=<cident>
( "," [rel_tokname]=<cident> )*
")" ("=" | "<" | ">" | "<=" | ">=") <tokenDefinition>
| [rel_lhs]=<cident> "IN" "(" <term> ( "," <term> )* ")"
;
<selectClause> ::= "DISTINCT"? <selector> ("AS" <cident>)? ("," <selector> ("AS" <cident>)?)*
| "*"
;
<udtSubfieldSelection> ::= <identifier> "." <identifier>
;
<selector> ::= [colname]=<cident>
| <udtSubfieldSelection>
| "WRITETIME" "(" [colname]=<cident> ")"
| "TTL" "(" [colname]=<cident> ")"
| "COUNT" "(" star=( "*" | "1" ) ")"
| <functionName> <selectionFunctionArguments>
;
<selectionFunctionArguments> ::= "(" ( <selector> ( "," <selector> )* )? ")"
;
<orderByClause> ::= [ordercol]=<cident> ( "ASC" | "DESC" )?
;
'''
def udf_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
udfnames = cass.get_userfunction_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, udfnames)
def uda_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
udanames = cass.get_useraggregate_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, udanames)
def udf_uda_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
functionnames = cass.get_userfunction_names(ks) + cass.get_useraggregate_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, functionnames)
def ref_udf_name_completer(ctxt, cass):
try:
udanames = cass.get_userfunction_names(None)
except Exception:
return ()
return map(maybe_escape_name, udanames)
completer_for('functionAggregateName', 'ksname')(cf_ks_name_completer)
completer_for('functionAggregateName', 'dot')(cf_ks_dot_completer)
completer_for('functionAggregateName', 'functionname')(udf_uda_name_completer)
completer_for('anyFunctionName', 'ksname')(cf_ks_name_completer)
completer_for('anyFunctionName', 'dot')(cf_ks_dot_completer)
completer_for('anyFunctionName', 'udfname')(udf_name_completer)
completer_for('userFunctionName', 'ksname')(cf_ks_name_completer)
completer_for('userFunctionName', 'dot')(cf_ks_dot_completer)
completer_for('userFunctionName', 'udfname')(udf_name_completer)
completer_for('refUserFunctionName', 'udfname')(ref_udf_name_completer)
completer_for('userAggregateName', 'ksname')(cf_ks_dot_completer)
completer_for('userAggregateName', 'dot')(cf_ks_dot_completer)
completer_for('userAggregateName', 'udaname')(uda_name_completer)
@completer_for('orderByClause', 'ordercol')
def select_order_column_completer(ctxt, cass):
prev_order_cols = ctxt.get_binding('ordercol', ())
keyname = ctxt.get_binding('keyname')
if keyname is None:
keyname = ctxt.get_binding('rel_lhs', ())
if not keyname:
return [Hint("Can't ORDER BY here: need to specify partition key in WHERE clause")]
layout = get_table_meta(ctxt, cass)
order_by_candidates = [col.name for col in layout.clustering_key]
if len(order_by_candidates) > len(prev_order_cols):
return [maybe_escape_name(order_by_candidates[len(prev_order_cols)])]
return [Hint('No more orderable columns here.')]
@completer_for('relation', 'token')
def relation_token_word_completer(ctxt, cass):
return ['TOKEN(']
@completer_for('relation', 'rel_tokname')
def relation_token_subject_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
return [key.name for key in layout.partition_key]
@completer_for('relation', 'rel_lhs')
def select_relation_lhs_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
filterable = set((layout.partition_key[0].name, layout.clustering_key[0].name))
already_filtered_on = map(dequote_name, ctxt.get_binding('rel_lhs', ()))
for num in range(1, len(layout.partition_key)):
if layout.partition_key[num - 1].name in already_filtered_on:
filterable.add(layout.partition_key[num].name)
else:
break
for num in range(1, len(layout.clustering_key)):
if layout.clustering_key[num - 1].name in already_filtered_on:
filterable.add(layout.clustering_key[num].name)
else:
break
for cd in layout.columns.values():
if cd.index:
filterable.add(cd.name)
return map(maybe_escape_name, filterable)
explain_completion('selector', 'colname')
syntax_rules += r'''
<insertStatement> ::= "INSERT" "INTO" cf=<columnFamilyName>
( ( "(" [colname]=<cident> ( "," [colname]=<cident> )* ")"
"VALUES" "(" [newval]=<term> ( valcomma="," [newval]=<term> )* valcomma=")")
| ("JSON" <stringLiteral>))
( "IF" "NOT" "EXISTS")?
( "USING" [insertopt]=<usingOption>
( "AND" [insertopt]=<usingOption> )* )?
;
<usingOption> ::= "TIMESTAMP" <wholenumber>
| "TTL" <wholenumber>
;
'''
def regular_column_names(table_meta):
if not table_meta or not table_meta.columns:
return []
regular_coulmns = list(set(table_meta.columns.keys())
- set([key.name for key in table_meta.partition_key])
- set([key.name for key in table_meta.clustering_key]))
return regular_coulmns
@completer_for('insertStatement', 'colname')
def insert_colname_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
colnames = set(map(dequote_name, ctxt.get_binding('colname', ())))
keycols = layout.primary_key
for k in keycols:
if k.name not in colnames:
return [maybe_escape_name(k.name)]
normalcols = set(regular_column_names(layout)) - colnames
return map(maybe_escape_name, normalcols)
@completer_for('insertStatement', 'newval')
def insert_newval_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
insertcols = map(dequote_name, ctxt.get_binding('colname'))
valuesdone = ctxt.get_binding('newval', ())
if len(valuesdone) >= len(insertcols):
return []
curcol = insertcols[len(valuesdone)]
cqltype = layout.columns[curcol].data_type
coltype = cqltype.typename
if coltype in ('map', 'set'):
return ['{']
if coltype == 'list':
return ['[']
if coltype == 'boolean':
return ['true', 'false']
return [Hint('<value for %s (%s)>' % (maybe_escape_name(curcol),
cqltype.cql_parameterized_type()))]
@completer_for('insertStatement', 'valcomma')
def insert_valcomma_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
numcols = len(ctxt.get_binding('colname', ()))
numvals = len(ctxt.get_binding('newval', ()))
if numcols > numvals:
return [',']
return [')']
@completer_for('insertStatement', 'insertopt')
def insert_option_completer(ctxt, cass):
opts = set('TIMESTAMP TTL'.split())
for opt in ctxt.get_binding('insertopt', ()):
opts.discard(opt.split()[0])
return opts
syntax_rules += r'''
<updateStatement> ::= "UPDATE" cf=<columnFamilyName>
( "USING" [updateopt]=<usingOption>
( "AND" [updateopt]=<usingOption> )* )?
"SET" <assignment> ( "," <assignment> )*
"WHERE" <whereClause>
( "IF" ( "EXISTS" | <conditions> ))?
;
<assignment> ::= updatecol=<cident>
( "=" update_rhs=( <term> | <cident> )
( counterop=( "+" | "-" ) inc=<wholenumber>
| listadder="+" listcol=<cident> )?
| indexbracket="[" <term> "]" "=" <term> )
;
<conditions> ::= <condition> ( "AND" <condition> )*
;
<condition> ::= <cident> ( "[" <term> "]" )? ( ( "=" | "<" | ">" | "<=" | ">=" | "!=" ) <term>
| "IN" "(" <term> ( "," <term> )* ")")
;
'''
@completer_for('updateStatement', 'updateopt')
def insert_option_completer(ctxt, cass):
opts = set('TIMESTAMP TTL'.split())
for opt in ctxt.get_binding('updateopt', ()):
opts.discard(opt.split()[0])
return opts
@completer_for('assignment', 'updatecol')
def update_col_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
return map(maybe_escape_name, regular_column_names(layout))
@completer_for('assignment', 'update_rhs')
def update_countername_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
curcol = dequote_name(ctxt.get_binding('updatecol', ''))
cqltype = layout.columns[curcol].data_type
coltype = cqltype.typename
if coltype == 'counter':
return [maybe_escape_name(curcol)]
if coltype in ('map', 'set'):
return ["{"]
if coltype == 'list':
return ["["]
return [Hint('<term (%s)>' % cqltype.cql_parameterized_type())]
@completer_for('assignment', 'counterop')
def update_counterop_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
curcol = dequote_name(ctxt.get_binding('updatecol', ''))
return ['+', '-'] if layout.columns[curcol].data_type.typename == 'counter' else []
@completer_for('assignment', 'inc')
def update_counter_inc_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
curcol = dequote_name(ctxt.get_binding('updatecol', ''))
if layout.columns[curcol].data_type.typename == 'counter':
return [Hint('<wholenumber>')]
return []
@completer_for('assignment', 'listadder')
def update_listadder_completer(ctxt, cass):
rhs = ctxt.get_binding('update_rhs')
if rhs.startswith('['):
return ['+']
return []
@completer_for('assignment', 'listcol')
def update_listcol_completer(ctxt, cass):
rhs = ctxt.get_binding('update_rhs')
if rhs.startswith('['):
colname = dequote_name(ctxt.get_binding('updatecol'))
return [maybe_escape_name(colname)]
return []
@completer_for('assignment', 'indexbracket')
def update_indexbracket_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
curcol = dequote_name(ctxt.get_binding('updatecol', ''))
coltype = layout.columns[curcol].data_type.typename
if coltype in ('map', 'list'):
return ['[']
return []
syntax_rules += r'''
<deleteStatement> ::= "DELETE" ( <deleteSelector> ( "," <deleteSelector> )* )?
"FROM" cf=<columnFamilyName>
( "USING" [delopt]=<deleteOption> )?
"WHERE" <whereClause>
( "IF" ( "EXISTS" | <conditions> ) )?
;
<deleteSelector> ::= delcol=<cident> ( memberbracket="[" memberselector=<term> "]" )?
;
<deleteOption> ::= "TIMESTAMP" <wholenumber>
;
'''
@completer_for('deleteStatement', 'delopt')
def delete_opt_completer(ctxt, cass):
opts = set('TIMESTAMP'.split())
for opt in ctxt.get_binding('delopt', ()):
opts.discard(opt.split()[0])
return opts
@completer_for('deleteSelector', 'delcol')
def delete_delcol_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
return map(maybe_escape_name, regular_column_names(layout))
syntax_rules += r'''
<batchStatement> ::= "BEGIN" ( "UNLOGGED" | "COUNTER" )? "BATCH"
( "USING" [batchopt]=<usingOption>
( "AND" [batchopt]=<usingOption> )* )?
[batchstmt]=<batchStatementMember> ";"?
( [batchstmt]=<batchStatementMember> ";"? )*
"APPLY" "BATCH"
;
<batchStatementMember> ::= <insertStatement>
| <updateStatement>
| <deleteStatement>
;
'''
@completer_for('batchStatement', 'batchopt')
def batch_opt_completer(ctxt, cass):
opts = set('TIMESTAMP'.split())
for opt in ctxt.get_binding('batchopt', ()):
opts.discard(opt.split()[0])
return opts
syntax_rules += r'''
<truncateStatement> ::= "TRUNCATE" cf=<columnFamilyName>
;
'''
syntax_rules += r'''
<createKeyspaceStatement> ::= "CREATE" wat=( "KEYSPACE" | "SCHEMA" ) ("IF" "NOT" "EXISTS")? ksname=<cfOrKsName>
"WITH" <property> ( "AND" <property> )*
;
'''
@completer_for('createKeyspaceStatement', 'wat')
def create_ks_wat_completer(ctxt, cass):
# would prefer to get rid of the "schema" nomenclature in cql3
if ctxt.get_binding('partial', '') == '':
return ['KEYSPACE']
return ['KEYSPACE', 'SCHEMA']
syntax_rules += r'''
<createColumnFamilyStatement> ::= "CREATE" wat=( "COLUMNFAMILY" | "TABLE" ) ("IF" "NOT" "EXISTS")?
( ks=<nonSystemKeyspaceName> dot="." )? cf=<cfOrKsName>
"(" ( <singleKeyCfSpec> | <compositeKeyCfSpec> ) ")"
( "WITH" <cfamProperty> ( "AND" <cfamProperty> )* )?
;
<cfamProperty> ::= <property>
| "COMPACT" "STORAGE"
| "CLUSTERING" "ORDER" "BY" "(" <cfamOrdering>
( "," <cfamOrdering> )* ")"
;
<cfamOrdering> ::= [ordercol]=<cident> ( "ASC" | "DESC" )
;
<singleKeyCfSpec> ::= [newcolname]=<cident> <storageType> "PRIMARY" "KEY"
( "," [newcolname]=<cident> <storageType> )*
;
<compositeKeyCfSpec> ::= [newcolname]=<cident> <storageType>
"," [newcolname]=<cident> <storageType> ( "static" )?
( "," [newcolname]=<cident> <storageType> ( "static" )? )*
"," "PRIMARY" k="KEY" p="(" ( partkey=<pkDef> | [pkey]=<cident> )
( c="," [pkey]=<cident> )* ")"
;
<pkDef> ::= "(" [ptkey]=<cident> "," [ptkey]=<cident>
( "," [ptkey]=<cident> )* ")"
;
'''
@completer_for('cfamOrdering', 'ordercol')
def create_cf_clustering_order_colname_completer(ctxt, cass):
colnames = map(dequote_name, ctxt.get_binding('newcolname', ()))
# Definitely some of these aren't valid for ordering, but I'm not sure
# precisely which are. This is good enough for now
return colnames
@completer_for('createColumnFamilyStatement', 'wat')
def create_cf_wat_completer(ctxt, cass):
# would prefer to get rid of the "columnfamily" nomenclature in cql3
if ctxt.get_binding('partial', '') == '':
return ['TABLE']
return ['TABLE', 'COLUMNFAMILY']
explain_completion('createColumnFamilyStatement', 'cf', '<new_table_name>')
explain_completion('compositeKeyCfSpec', 'newcolname', '<new_column_name>')
@completer_for('createColumnFamilyStatement', 'dot')
def create_cf_ks_dot_completer(ctxt, cass):
ks = dequote_name(ctxt.get_binding('ks'))
if ks in cass.get_keyspace_names():
return ['.']
return []
@completer_for('pkDef', 'ptkey')
def create_cf_pkdef_declaration_completer(ctxt, cass):
cols_declared = ctxt.get_binding('newcolname')
pieces_already = ctxt.get_binding('ptkey', ())
pieces_already = map(dequote_name, pieces_already)
while cols_declared[0] in pieces_already:
cols_declared = cols_declared[1:]
if len(cols_declared) < 2:
return ()
return [maybe_escape_name(cols_declared[0])]
@completer_for('compositeKeyCfSpec', 'pkey')
def create_cf_composite_key_declaration_completer(ctxt, cass):
cols_declared = ctxt.get_binding('newcolname')
pieces_already = ctxt.get_binding('ptkey', ()) + ctxt.get_binding('pkey', ())
pieces_already = map(dequote_name, pieces_already)
while cols_declared[0] in pieces_already:
cols_declared = cols_declared[1:]
if len(cols_declared) < 2:
return ()
return [maybe_escape_name(cols_declared[0])]
@completer_for('compositeKeyCfSpec', 'k')
def create_cf_composite_primary_key_keyword_completer(ctxt, cass):
return ['KEY (']
@completer_for('compositeKeyCfSpec', 'p')
def create_cf_composite_primary_key_paren_completer(ctxt, cass):
return ['(']
@completer_for('compositeKeyCfSpec', 'c')
def create_cf_composite_primary_key_comma_completer(ctxt, cass):
cols_declared = ctxt.get_binding('newcolname')
pieces_already = ctxt.get_binding('pkey', ())
if len(pieces_already) >= len(cols_declared) - 1:
return ()
return [',']
syntax_rules += r'''
<idxName> ::= <identifier>
| <quotedName>
| <unreservedKeyword>;
<createIndexStatement> ::= "CREATE" "CUSTOM"? "INDEX" ("IF" "NOT" "EXISTS")? indexname=<idxName>? "ON"
cf=<columnFamilyName> "(" (
col=<cident> |
"keys(" col=<cident> ")" |
"full(" col=<cident> ")"
) ")"
( "USING" <stringLiteral> ( "WITH" "OPTIONS" "=" <mapLiteral> )? )?
;
<createUserTypeStatement> ::= "CREATE" "TYPE" ( ks=<nonSystemKeyspaceName> dot="." )? typename=<cfOrKsName> "(" newcol=<cident> <storageType>
( "," [newcolname]=<cident> <storageType> )*
")"
;
<createFunctionStatement> ::= "CREATE" ("OR" "REPLACE")? "FUNCTION"
("IF" "NOT" "EXISTS")?
<userFunctionName>
( "(" ( newcol=<cident> <storageType>
( "," [newcolname]=<cident> <storageType> )* )?
")" )?
("RETURNS" "NULL" | "CALLED") "ON" "NULL" "INPUT"
"RETURNS" <storageType>
"LANGUAGE" <cident> "AS" <stringLiteral>
;
<createAggregateStatement> ::= "CREATE" ("OR" "REPLACE")? "AGGREGATE"
("IF" "NOT" "EXISTS")?
<userAggregateName>
( "("
( <storageType> ( "," <storageType> )* )?
")" )?
"SFUNC" <refUserFunctionName>
"STYPE" <storageType>
( "FINALFUNC" <refUserFunctionName> )?
( "INITCOND" <term> )?
;
'''
explain_completion('createIndexStatement', 'indexname', '<new_index_name>')
explain_completion('createUserTypeStatement', 'typename', '<new_type_name>')
explain_completion('createUserTypeStatement', 'newcol', '<new_field_name>')
@completer_for('createIndexStatement', 'col')
def create_index_col_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
colnames = [cd.name for cd in layout.columns.values() if not cd.index]
return map(maybe_escape_name, colnames)
syntax_rules += r'''
<dropKeyspaceStatement> ::= "DROP" "KEYSPACE" ("IF" "EXISTS")? ksname=<nonSystemKeyspaceName>
;
<dropColumnFamilyStatement> ::= "DROP" ( "COLUMNFAMILY" | "TABLE" ) ("IF" "EXISTS")? cf=<columnFamilyName>
;
<indexName> ::= ( ksname=<idxOrKsName> dot="." )? idxname=<idxOrKsName> ;
<idxOrKsName> ::= <identifier>
| <quotedName>
| <unreservedKeyword>;
<dropIndexStatement> ::= "DROP" "INDEX" ("IF" "EXISTS")? idx=<indexName>
;
<dropUserTypeStatement> ::= "DROP" "TYPE" ut=<userTypeName>
;
<dropFunctionStatement> ::= "DROP" "FUNCTION" ( "IF" "EXISTS" )? <userFunctionName>
;
<dropAggregateStatement> ::= "DROP" "AGGREGATE" ( "IF" "EXISTS" )? <userAggregateName>
;
'''
@completer_for('indexName', 'ksname')
def idx_ks_name_completer(ctxt, cass):
return [maybe_escape_name(ks) + '.' for ks in cass.get_keyspace_names()]
@completer_for('indexName', 'dot')
def idx_ks_dot_completer(ctxt, cass):
name = dequote_name(ctxt.get_binding('ksname'))
if name in cass.get_keyspace_names():
return ['.']
return []
@completer_for('indexName', 'idxname')
def idx_ks_idx_name_completer(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
try:
idxnames = cass.get_index_names(ks)
except Exception:
if ks is None:
return ()
raise
return map(maybe_escape_name, idxnames)
syntax_rules += r'''
<alterTableStatement> ::= "ALTER" wat=( "COLUMNFAMILY" | "TABLE" ) cf=<columnFamilyName>
<alterInstructions>
;
<alterInstructions> ::= "ALTER" existcol=<cident> "TYPE" <storageType>
| "ADD" newcol=<cident> <storageType> ("static")?
| "DROP" existcol=<cident>
| "WITH" <cfamProperty> ( "AND" <cfamProperty> )*
| "RENAME" existcol=<cident> "TO" newcol=<cident>
( "AND" existcol=<cident> "TO" newcol=<cident> )*
;
<alterUserTypeStatement> ::= "ALTER" "TYPE" ut=<userTypeName>
<alterTypeInstructions>
;
<alterTypeInstructions> ::= "ALTER" existcol=<cident> "TYPE" <storageType>
| "ADD" newcol=<cident> <storageType>
| "RENAME" existcol=<cident> "TO" newcol=<cident>
( "AND" existcol=<cident> "TO" newcol=<cident> )*
;
'''
@completer_for('alterInstructions', 'existcol')
def alter_table_col_completer(ctxt, cass):
layout = get_table_meta(ctxt, cass)
cols = [str(md) for md in layout.columns]
return map(maybe_escape_name, cols)
@completer_for('alterTypeInstructions', 'existcol')
def alter_type_field_completer(ctxt, cass):
layout = get_ut_layout(ctxt, cass)
fields = [tuple[0] for tuple in layout]
return map(maybe_escape_name, fields)
explain_completion('alterInstructions', 'newcol', '<new_column_name>')
explain_completion('alterTypeInstructions', 'newcol', '<new_field_name>')
syntax_rules += r'''
<alterKeyspaceStatement> ::= "ALTER" wat=( "KEYSPACE" | "SCHEMA" ) ks=<alterableKeyspaceName>
"WITH" <property> ( "AND" <property> )*
;
'''
syntax_rules += r'''
<username> ::= name=( <identifier> | <stringLiteral> )
;
<createUserStatement> ::= "CREATE" "USER" ( "IF" "NOT" "EXISTS" )? <username>
( "WITH" "PASSWORD" <stringLiteral> )?
( "SUPERUSER" | "NOSUPERUSER" )?
;
<alterUserStatement> ::= "ALTER" "USER" <username>
( "WITH" "PASSWORD" <stringLiteral> )?
( "SUPERUSER" | "NOSUPERUSER" )?
;
<dropUserStatement> ::= "DROP" "USER" ( "IF" "EXISTS" )? <username>
;
<listUsersStatement> ::= "LIST" "USERS"
;
'''
syntax_rules += r'''
<rolename> ::= <identifier>
| <quotedName>
| <unreservedKeyword>
;
<createRoleStatement> ::= "CREATE" "ROLE" <rolename>
( "WITH" <roleProperty> ("AND" <roleProperty>)*)?
;
<alterRoleStatement> ::= "ALTER" "ROLE" <rolename>
( "WITH" <roleProperty> ("AND" <roleProperty>)*)?
;
<roleProperty> ::= "PASSWORD" "=" <stringLiteral>
| "OPTIONS" "=" <mapLiteral>
| "SUPERUSER" "=" <boolean>
| "LOGIN" "=" <boolean>
;
<dropRoleStatement> ::= "DROP" "ROLE" <rolename>
;
<grantRoleStatement> ::= "GRANT" <rolename> "TO" <rolename>
;
<revokeRoleStatement> ::= "REVOKE" <rolename> "FROM" <rolename>
;
<listRolesStatement> ::= "LIST" "ROLES"
( "OF" <rolename> )? "NORECURSIVE"?
;
'''
syntax_rules += r'''
<grantStatement> ::= "GRANT" <permissionExpr> "ON" <resource> "TO" <rolename>
;
<revokeStatement> ::= "REVOKE" <permissionExpr> "ON" <resource> "FROM" <rolename>
;
<listPermissionsStatement> ::= "LIST" <permissionExpr>
( "ON" <resource> )? ( "OF" <rolename> )? "NORECURSIVE"?
;
<permission> ::= "AUTHORIZE"
| "CREATE"
| "ALTER"
| "DROP"
| "SELECT"
| "MODIFY"
| "DESCRIBE"
| "EXECUTE"
;
<permissionExpr> ::= ( <permission> "PERMISSION"? )
| ( "ALL" "PERMISSIONS"? )
;
<resource> ::= <dataResource>
| <roleResource>
| <functionResource>
;
<dataResource> ::= ( "ALL" "KEYSPACES" )
| ( "KEYSPACE" <keyspaceName> )
| ( "TABLE"? <columnFamilyName> )
;
<roleResource> ::= ("ALL" "ROLES")
| ("ROLE" <rolename>)
;
<functionResource> ::= ( "ALL" "FUNCTIONS" ("IN KEYSPACE" <keyspaceName>)? )
| ( "FUNCTION" <functionAggregateName>
( "(" ( newcol=<cident> <storageType>
( "," [newcolname]=<cident> <storageType> )* )?
")" )
)
;
'''
@completer_for('username', 'name')
def username_name_completer(ctxt, cass):
def maybe_quote(name):
if CqlRuleSet.is_valid_cql3_name(name):
return name
return "'%s'" % name
# disable completion for CREATE USER.
if ctxt.matched[0][0] == 'create':
return [Hint('<username>')]
session = cass.session
return [maybe_quote(row.values()[0].replace("'", "''")) for row in session.execute("LIST USERS")]
@completer_for('rolename', 'role')
def rolename_completer(ctxt, cass):
def maybe_quote(name):
if CqlRuleSet.is_valid_cql3_name(name):
return name
return "'%s'" % name
# disable completion for CREATE ROLE.
if ctxt.matched[0][0] == 'K_CREATE':
return [Hint('<rolename>')]
session = cass.session
return [maybe_quote(row[0].replace("'", "''")) for row in session.execute("LIST ROLES")]
syntax_rules += r'''
<createTriggerStatement> ::= "CREATE" "TRIGGER" ( "IF" "NOT" "EXISTS" )? <cident>
"ON" cf=<columnFamilyName> "USING" class=<stringLiteral>
;
<dropTriggerStatement> ::= "DROP" "TRIGGER" ( "IF" "EXISTS" )? triggername=<cident>
"ON" cf=<columnFamilyName>
;
'''
explain_completion('createTriggerStatement', 'class', '\'fully qualified class name\'')
def get_trigger_names(ctxt, cass):
ks = ctxt.get_binding('ksname', None)
if ks is not None:
ks = dequote_name(ks)
return cass.get_trigger_names(ks)
@completer_for('dropTriggerStatement', 'triggername')
def alter_type_field_completer(ctxt, cass):
names = get_trigger_names(ctxt, cass)
return map(maybe_escape_name, names)
# END SYNTAX/COMPLETION RULE DEFINITIONS
CqlRuleSet.append_rules(syntax_rules)
|
python
|
import pytest
import numpy as np
class DataGenerator:
def __init__(self, fs=100e3, n_iter=10, sample_duration=1):
self.fs = fs
self.n_iter = n_iter
self.sample_duration = sample_duration
self.n_samples = int(round(sample_duration * fs))
def _iter(self):
self.generated = []
for i in range(self.n_iter):
samples = np.random.uniform(size=self.n_samples)
self.generated.append(samples)
yield samples
def iter_continuous(self):
yield from self._iter()
def iter_epochs(self, isi):
for i, samples in enumerate(self._iter()):
signal = {
'signal': samples,
'info': {
't0': isi * i,
'duration': self.sample_duration,
'metadata': {'frequency': 1e3, 'stim': i},
}
}
yield [signal]
@pytest.fixture
def data_generator():
return DataGenerator()
|
python
|
#
# Copyright (c) Sinergise, 2019 -- 2021.
#
# This file belongs to subproject "field-delineation" of project NIVA (www.niva4cap.eu).
# All rights reserved.
#
# This source code is licensed under the MIT license found in the LICENSE
# file in the root directory of this source tree.
#
import os
import re
from setuptools import setup, find_packages
def parse_requirements(file):
with open(os.path.join(os.path.dirname(__file__), file)) as req_file:
return [line.strip() for line in req_file if '/' not in line]
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'fd', '__init__.py')) as file:
return re.findall("__version__ = \'(.*)\'", file.read())[0]
setup(
name='fd',
python_requires='>=3.6',
version=get_version(),
description='EO Research Field Delineation',
url='https://gitlab.com/nivaeu/uc2_fielddelineation',
author='Sinergise EO research team',
author_email='[email protected]',
packages=find_packages(),
package_data={'fd': ['evalscripts/dates_evalscript.js', 'evalscripts/data_evalscript.js']},
include_package_data=True,
install_requires=parse_requirements('requirements.txt'),
extras_require={
'DEV': parse_requirements('requirements-dev.txt')
},
zip_safe=False
)
|
python
|
import time
import base64
def normalize_scope(scope):
return ' '.join(sorted(scope.split()))
def is_token_expired(token, offset=60):
return token['expires_at'] - int(time.time()) < offset
def get_authorization_headers(client_id, client_secret):
auth_header = base64.b64encode(f'{client_id}:{client_secret}'.encode('ascii')).decode('ascii')
return {'Authorization': f'Basic {auth_header}'}
def add_custom_values_to_token(token, scope=None):
token['expires_at'] = token['expires_in'] + int(time.time())
if scope:
token['scope'] = scope
return token
def encode_image(image):
with open(image, "rb") as f:
enc_str = base64.b64encode(f.read())
return enc_str
|
python
|
"""
# 100daysCodingChallenge
Level: Medium
Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, S
.
Both players have to make substrings using the letters of the string S
.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.
Scoring
A player gets +1 point for each occurrence of the substring in the string S
Example:
String = BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.
"""
# This is my solution which is incomplete and timing out in hackerRank when given
# large numbers
# todo: Fix the timing out at Large numbers
import sys
def getSub_words(string, workDict, stringLen):
# {'b': [0], 'n': [3, 5], 's': [7]}
# {'a': [1, 2, 4, 6]}
subs = []
for key,sindex in workDict.items():
for s in sindex:
for i in range(s, stringLen+1):
if string[s:i] != "":
if not string[s:i] in subs:
subs.append(string[s:i])
print(subs)
score = 0
for word in subs:
l = [n for n in range(len(string)) if string.find(word, n) == n]
score += len(l)
return score
def minion_game(string):
# kevin = vowels
# stuart = consonants
if not string.isupper():
sys.exit(1)
if len(string) > 10**6 or len(string) < 0:
sys.exit(1)
string = string.lower()
vowels = ["a", "e", "i", "o", "u"]
mystring = [letter for i, letter in enumerate(string)]
kevin_words = {}
stuart_words = {}
for l in mystring:
if l in vowels:
# if l not in kevin_words.items():
kevin_words[l] = [n for n in range(len(string)+1) if string.find(l, n) == n]
if l not in vowels:
# if l not in stuart_words.items():
stuart_words[l] = [n for n in range(len(string)+1) if string.find(l, n) == n]
# print(kevin_words)
# print(stuart_words)
stuart_subs = []
stringLen = len(string)
# print(stuart_words)
# print(kevin_words)
stuart_score = getSub_words(string, stuart_words, stringLen)
kevin_score = getSub_words(string, kevin_words, stringLen)
#
# if stuart_score > kevin_score:
# print("Stuart {}".format(stuart_score))
# elif kevin_score > stuart_score:
# print("Kevin {}".format(kevin_score))
# else:
# print("Draw")
if __name__ == '__main__':
s = input()
minion_game(s)
"""
# working code
def minion_game1(s):
vowels = 'AEIOU'
kevsc = 0
stusc = 0
for i in range(len(s)):
if s[i] in vowels:
kevsc += (len(s)-i)
else:
stusc += (len(s)-i)
if kevsc > stusc:
print("Kevin {}".format(kevsc))
elif kevsc < stusc:
print("Stuart {} ".format(stusc))
else:
print("Draw")
"""
|
python
|
'''
Date: 2021-08-02 22:38:28
LastEditors: xgy
LastEditTime: 2021-08-15 16:12:14
FilePath: \code\ctpn\src\CTPN\BoundingBoxDecode.py
'''
import mindspore.nn as nn
from mindspore.ops import operations as P
class BoundingBoxDecode(nn.Cell):
"""
BoundintBox Decoder.
Returns:
pred_box(Tensor): decoder bounding boxes.
"""
def __init__(self):
super(BoundingBoxDecode, self).__init__()
self.split = P.Split(axis=1, output_num=4)
self.ones = 1.0
self.half = 0.5
self.log = P.Log()
self.exp = P.Exp()
self.concat = P.Concat(axis=1)
def construct(self, bboxes, deltas):
"""
boxes(Tensor): boundingbox.
deltas(Tensor): delta between boundingboxs and anchors.
"""
x1, y1, x2, y2 = self.split(bboxes)
width = x2 - x1 + self.ones
height = y2 - y1 + self.ones
ctr_x = x1 + self.half * width
ctr_y = y1 + self.half * height
_, dy, _, dh = self.split(deltas)
pred_ctr_x = ctr_x
pred_ctr_y = dy * height + ctr_y
pred_w = width
pred_h = self.exp(dh) * height
x1 = pred_ctr_x - self.half * pred_w
y1 = pred_ctr_y - self.half * pred_h
x2 = pred_ctr_x + self.half * pred_w
y2 = pred_ctr_y + self.half * pred_h
pred_box = self.concat((x1, y1, x2, y2))
return pred_box
|
python
|
'''In this exercise, the task is to write a function that picks a random word from a list of words from the
SOWPODS dictionary. Download this file and save it in the same directory as your Python code.
This file is Peter Norvig’s compilation of the dictionary of words used in professional Scrabble tournaments.
Each line in the file contains a single word.'''
import random
def random_sowpods(filename):
list = []
with open(filename) as file:
for line in file:
list.append(line.replace('\n',''))
file.close()
return list[random.randint(0,len(list)-1)]
print (random_sowpods('sowpods.txt'))
|
python
|
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField('Titulo', max_length=150)
description = models.TextField('Description')
# author = models.ForeignKey(User, verbose_name = 'Autor')
is_published = models.BooleanField('Publicado?', default = False)
created_at = models.DateTimeField('Criado em', auto_now_add = True)
updated_at = models.DateTimeField('Atualizado em', auto_now = True)
class Meta:
ordering = ['-created_at']
verbose_name = 'Publicação'
verbose_name_plural = 'Publicações'
def __str__(self):
return '{} - {}'.format(self.title, self.created_at)
|
python
|
# from os.path import dirname
import os,sys,pytest
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from Page.login_page import Login_Page
from Base.init_driver import get_driver
from Base.read_data import Op_Data
from time import sleep
from loguru import logger
# sys.path.append(os.getcwd())
def get_data():
# 读取返回数据
data_list = []
data = Op_Data("data.yml").read_yaml().get("Login_data")
for i in data:
for o in i.keys():
data_list.append((o, i.get(o).get("phone"), i.get(o).get("passwd"),
i.get(o).get("get_mess"), i.get(o).get("expect_message"),
i.get(o).get("tag")))
return data_list
class Test_Login:
def setup_class(self):
# 实例化登陆对象
logger.info("调起同桌100")
os.system('adb shell am broadcast -a com.baidu.duer.query -e q "打开同桌100"')
# os.system('adb shell am broadcast -a com.baidu.duer.query -e q "退出"')
os.system('adb shell am broadcast -a com.baidu.duer.query -e q "打开同桌100"')
os.system('adb shell am broadcast -a com.baidu.duer.query -e q "打开同桌100"')
self.LP_obj = Login_Page(get_driver())
# 点击个人中心
# sleep(5)
# self.LP_obj.click_sy_login_btn()
def teardown_class(self):
self.LP_obj.driver.quit()
@pytest.mark.parametrize("case_num, username, passwd,get_mess,expect_message, tag", get_data())
def test_login_page(self, case_num, username, passwd, get_mess, expect_message, tag):
"""
:param username: 用户名
:param passwd: 密码
:param get_mess: toast传参
:param expect_message: 预期toast消息
:param tag: 1 标记登陆成功用例 2 标记账号不存在 3标记登录失败
:return:
"""
# 点击登陆注册
# logger.info("点击登录/注册")
# self.LP_obj.click_sy_login_btn()
# 登陆操作
logger.info("登录相关操作")
self.LP_obj.click_sy_login_btn()
self.LP_obj.login_input_page(username, passwd)
if tag == 1:
try:
# 获取登陆成功toast
logger.info("正向登录用例")
suc_msg = self.LP_obj.get_toast(get_mess)
logger.debug("获取登录成功toast:{}".format(suc_msg))
# 退出登录
self.LP_obj.logout_page()
assert suc_msg == expect_message
logger.success("断言成功{}=={}".format(suc_msg, expect_message))
except Exception as e:
# 捕获异常信息+截图
self.LP_obj.error_dispose(e)
# 关闭登录信息输入页面
self.LP_obj.login_back_page()
assert False
elif tag == 2:
try:
logger.debug("登录不存在的账号用例")
# 获取登陆成功toast
suc_msg = self.LP_obj.get_toast(get_mess)
logger.debug("获取账号不存在toast:{}".format(suc_msg))
# 退出登录
self.LP_obj.login_close_page()
assert suc_msg == expect_message
logger.success("断言成功{}=={}".format(suc_msg, expect_message))
except Exception as e:
# 捕获异常信息+截图
self.LP_obj.error_dispose(e)
assert False
elif tag == 3:
logger.debug("账号或密码错误用例")
try:
# 获取登陆失败toast消息
fail_msg = self.LP_obj.get_toast(get_mess)
logger.debug("登录失败toast:{}".format(fail_msg))
if fail_msg:
assert fail_msg == expect_message
logger.success("断言成功:{}=={}".format(fail_msg, expect_message))
else:
assert False
self.LP_obj.login_back_page()
except Exception as e:
# 捕获异常信息+截图
self.LP_obj.error_dispose(e)
sleep(3)
assert False
'''
allure generate report/ -o report/html
'''
|
python
|
from unittest import TestCase
import pytest
import pandas as pd
import numpy as np
from pipelines.wine_quality_preparers import WinesPreparerETL, WhiteWinesPreparer
inputs = [7.0, 0.27, 0.36, 20.7, 0.045, 45.0, 170.0, 1.0010, 3.00, 0.45, 8.8, 6]
np_inputs = np.array(inputs)
class TestWinesPreparerETL(TestCase):
def setUp(self):
self.preparer = WinesPreparerETL()
def test_raw_features_inputs(self):
row = self.preparer.prepare(inputs).loc[0]
assert row['fixed_acidity'] == 7.0
assert row['citric_acid'] == 0.36
assert row['volatile_acidity'] == 0.27
assert row['residual_sugar'] == 20.7
assert row['chlorides'] == 0.045
assert row['free_sulfur_dioxide'] == 45.0
assert row['total_sulfur_dioxide'] == 170.0
assert row['density'] == 1.0010
assert row['pH'] == 3.00
assert row['sulphates'] == 0.45
assert row['alcohol'] == 8.8
assert row['quality'] == 6
def test_raw_features_type(self):
row = self.preparer.prepare(inputs).loc[0]
self.assertIsInstance(row['fixed_acidity'], float)
self.assertIsInstance(row['citric_acid'], float)
self.assertIsInstance(row['volatile_acidity'], float)
self.assertIsInstance(row['residual_sugar'], float)
self.assertIsInstance(row['chlorides'], float)
self.assertIsInstance(row['free_sulfur_dioxide'], float)
self.assertIsInstance(row['total_sulfur_dioxide'], float)
self.assertIsInstance(row['density'], float)
self.assertIsInstance(row['pH'], float)
self.assertIsInstance(row['sulphates'], float)
self.assertIsInstance(row['alcohol'], float)
self.assertIsInstance(row['quality'], float)
def test_prepare_quality_to_category_1(self):
transformed = self.preparer.prepare(inputs)
self.assertEqual(transformed.loc[0]['quality_cat'], 1)
def test_prepare_quality_to_category_0(self):
others = np_inputs.copy()
others[-1] = 1
transformed = self.preparer.prepare(others)
self.assertEqual(transformed.loc[0]['quality_cat'], 0)
def test_prepare_quality_to_category_2(self):
others = np_inputs.copy()
others[-1] = 8
transformed = self.preparer.prepare(others)
self.assertEqual(transformed.loc[0]['quality_cat'], 2)
def test_transform_free_sulfur_dioxide_to_log(self):
row = self.preparer.prepare(inputs).loc[0]
self.assertEqual(row['free_sulfur_dioxide_log'], np.log(45.0))
def test_transform_total_sulfur_dioxide_to_log(self):
row = self.preparer.prepare(inputs).loc[0]
self.assertEqual(row['total_sulfur_dioxide_log'], np.log(170.0))
def test_transform_residual_sugar(self):
row = self.preparer.prepare(inputs).loc[0]
self.assertEqual(row['residual_sugar_log'], np.log(20.7))
class TestWinesPreparerServing(TestCase):
def setUp(self):
self.preparer = WhiteWinesPreparer()
def test_selected_raw_feature_inputs(self):
row = self.preparer.prepare(inputs).loc[0]
assert row['fixed_acidity'] == 7.0
assert row['citric_acid'] == 0.36
assert row['volatile_acidity'] == 0.27
assert row['residual_sugar'] == 20.7
assert row['chlorides'] == 0.045
assert row['free_sulfur_dioxide'] == 45.0
assert row['total_sulfur_dioxide'] == 170.0
assert row['density'] == 1.0010
assert row['pH'] == 3.00
assert row['sulphates'] == 0.45
assert row['alcohol'] == 8.8
class TestWinesValidations(TestCase):
def setUp(self):
self.preparer = WinesPreparerETL()
def test_valid_quality_lower_bound(self):
invalid_inputs = np_inputs.copy()
invalid_inputs[-1] = 0
row = self.preparer.prepare(invalid_inputs).loc[0]
self.assertEqual(row['quality'], 0)
def test_valid_quality_upper_bound(self):
invalid_inputs = np_inputs.copy()
invalid_inputs[-1] = 10
row = self.preparer.prepare(invalid_inputs).loc[0]
self.assertEqual(row['quality'], 10)
def test_invalid_quality_lower_bound(self):
invalid_inputs = np_inputs.copy()
invalid_inputs[-1] = -1
with pytest.raises(ValueError, match="'quality' out of range"):
self.preparer.prepare(invalid_inputs).loc[0]
def test_invalid_quality_upper_bound(self):
invalid_inputs = np_inputs.copy()
invalid_inputs[-1] = 11
with pytest.raises(ValueError, match="'quality' out of range"):
self.preparer.prepare(invalid_inputs).loc[0]
|
python
|
from openfermion_dirac import MolecularData_Dirac, run_dirac
from openfermion.transforms import jordan_wigner
from openfermion.utils import eigenspectrum
import os
# Set molecule parameters.
basis = 'STO-3G'
bond_length = 0.5
charge = 1
data_directory=os.getcwd()
delete_input = True
delete_xyz = True
delete_output = False
delete_MRCONEE = True
delete_MDCINT = True
fcidump = True
geometry = [('He', (0., 0., 0.)), ('H', (0., 0., bond_length))]
print()
print('#'*40)
print('NONREL Dirac calculation, cc-pVDZ basis for H')
print('#'*40)
print()
run_ccsd = True
if run_ccsd:
description = 'R' + str(bond_length) + '_ccsd'
else:
description = 'R' + str(bond_length) + '_scf'
manual_option = "**RELCCSD\n*CCENER\n.NOSDT"
basis="special" # necessary keyword to specify that we are using a special basis
special_basis=["STO-3G","H BASIS cc-pVDZ"] # list of two string : [default basis, special basis for a given atomic species]
point_nucleus = True
molecule = MolecularData_Dirac(geometry=geometry,
basis=basis,
special_basis=special_basis,
charge=charge,
description=description,
data_directory=data_directory)
molecule = run_dirac(molecule,
fcidump=fcidump,
point_nucleus=point_nucleus,
delete_input=delete_input,
delete_xyz=delete_xyz,
delete_output=delete_output,
delete_MRCONEE=delete_MRCONEE,
delete_MDCINT=delete_MDCINT,
run_ccsd=run_ccsd,
manual_option=manual_option)
molecular_hamiltonian = molecule.get_molecular_hamiltonian()[0]
qubit_hamiltonian = jordan_wigner(molecular_hamiltonian)
evs = eigenspectrum(qubit_hamiltonian)
print('Hartree-Fock energy of {} Hartree.'.format(molecule.get_energies()[0]))
print('MP2 energy of {} Hartree.'.format(molecule.get_energies()[1]))
print('CCSD energy of {} Hartree.'.format(molecule.get_energies()[2]))
print('Solving the Qubit Hamiltonian (Jordan-Wigner): \n {}'.format(evs))
|
python
|
# Copyright (c) 2021-present, Ethan Henderson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
COUNTRIES = {
"AW",
"AF",
"AO",
"AI",
"AX",
"AL",
"AD",
"AE",
"AR",
"AM",
"AS",
"AQ",
"TF",
"AG",
"AU",
"AT",
"AZ",
"BI",
"BE",
"BJ",
"BQ",
"BF",
"BD",
"BG",
"BH",
"BS",
"BA",
"BL",
"BY",
"BZ",
"BM",
"BO",
"BR",
"BB",
"BN",
"BT",
"BV",
"BW",
"CF",
"CA",
"CC",
"CH",
"CL",
"CN",
"CI",
"CM",
"CD",
"CG",
"CK",
"CO",
"KM",
"CV",
"CR",
"CU",
"CW",
"CX",
"KY",
"CY",
"CZ",
"DE",
"DJ",
"DM",
"DK",
"DO",
"DZ",
"EC",
"EG",
"ER",
"EH",
"ES",
"EE",
"ET",
"FI",
"FJ",
"FK",
"FR",
"FO",
"FM",
"GA",
"GB",
"GE",
"GG",
"GH",
"GI",
"GN",
"GP",
"GM",
"GW",
"GQ",
"GR",
"GD",
"GL",
"GT",
"GF",
"GU",
"GY",
"HK",
"HM",
"HN",
"HR",
"HT",
"HU",
"ID",
"IM",
"IN",
"IO",
"IE",
"IR",
"IQ",
"IS",
"IL",
"IT",
"JM",
"JE",
"JO",
"JP",
"KZ",
"KE",
"KG",
"KH",
"KI",
"KN",
"KR",
"KW",
"LA",
"LB",
"LR",
"LY",
"LC",
"LI",
"LK",
"LS",
"LT",
"LU",
"LV",
"MO",
"MF",
"MA",
"MC",
"MD",
"MG",
"MV",
"MX",
"MH",
"MK",
"ML",
"MT",
"MM",
"ME",
"MN",
"MP",
"MZ",
"MR",
"MS",
"MQ",
"MU",
"MW",
"MY",
"YT",
"NA",
"NC",
"NE",
"NF",
"NG",
"NI",
"NU",
"NL",
"NO",
"NP",
"NR",
"NZ",
"OM",
"PK",
"PA",
"PN",
"PE",
"PH",
"PW",
"PG",
"PL",
"PR",
"KP",
"PT",
"PY",
"PS",
"PF",
"QA",
"RE",
"RO",
"RU",
"RW",
"SA",
"SD",
"SN",
"SG",
"GS",
"SH",
"SJ",
"SB",
"SL",
"SV",
"SM",
"SO",
"PM",
"RS",
"SS",
"ST",
"SR",
"SK",
"SI",
"SE",
"SZ",
"SX",
"SC",
"SY",
"TC",
"TD",
"TG",
"TH",
"TJ",
"TK",
"TM",
"TL",
"TO",
"TT",
"TN",
"TR",
"TV",
"TW",
"TZ",
"UG",
"UA",
"UM",
"UY",
"US",
"UZ",
"VA",
"VC",
"VE",
"VG",
"VI",
"VN",
"VU",
"WF",
"WS",
"YE",
"ZA",
"ZM",
"ZW",
}
SUBDIVISIONS = {
"US-OH",
"US-IN",
"US-OK",
"US-KS",
"US-OR",
"US-KY",
"US-PA",
"US-LA",
"US-AK",
"US-PR",
"US-MA",
"US-AL",
"US-RI",
"US-MD",
"US-AR",
"US-SC",
"US-ME",
"US-AS",
"US-SD",
"US-MI",
"US-AZ",
"US-TN",
"US-MN",
"US-CA",
"US-TX",
"US-MO",
"US-CO",
"US-UM",
"US-MP",
"US-CT",
"US-UT",
"US-MS",
"US-DC",
"US-VA",
"US-MT",
"US-DE",
"US-VI",
"US-NC",
"US-FL",
"US-VT",
"US-ND",
"US-GA",
"US-WA",
"US-NE",
"US-GU",
"US-WI",
"US-NH",
"US-HI",
"US-WV",
"US-NJ",
"US-IA",
"US-WY",
"US-NM",
"US-ID",
"US-NV",
"US-IL",
"US-NY",
}
CURRENCIES = {
"AED",
"AFN",
"ALL",
"AMD",
"ANG",
"AOA",
"ARS",
"AUD",
"AWG",
"AZN",
"BAM",
"BBD",
"BDT",
"BGN",
"BHD",
"BIF",
"BMD",
"BND",
"BOB",
"BRL",
"BSD",
"BTN",
"BWP",
"BYN",
"BZD",
"CAD",
"CDF",
"CHF",
"CLP",
"CNY",
"COP",
"CRC",
"CUC",
"CUP",
"CVE",
"CZK",
"DJF",
"DKK",
"DOP",
"DZD",
"EGP",
"ERN",
"ETB",
"EUR",
"FJD",
"FKP",
"GBP",
"GEL",
"GHS",
"GIP",
"GMD",
"GNF",
"GTQ",
"GYD",
"HKD",
"HNL",
"HRK",
"HTG",
"HUF",
"IDR",
"ILS",
"INR",
"IQD",
"IRR",
"ISK",
"JMD",
"JOD",
"JPY",
"KES",
"KGS",
"KHR",
"KMF",
"KPW",
"KRW",
"KWD",
"KYD",
"KZT",
"LAK",
"LBP",
"LKR",
"LRD",
"LSL",
"LYD",
"MAD",
"MDL",
"MGA",
"MKD",
"MMK",
"MNT",
"MOP",
"MRO",
"MUR",
"MVR",
"MWK",
"MXN",
"MYR",
"MZN",
"NAD",
"NGN",
"NIO",
"NOK",
"NPR",
"NZD",
"OMR",
"PAB",
"PEN",
"PGK",
"PHP",
"PKR",
"PLN",
"PYG",
"QAR",
"RON",
"RSD",
"RUB",
"RWF",
"SAR",
"SBD",
"SCR",
"SDG",
"SEK",
"SGD",
"SHP",
"SLL",
"SOS",
"SRD",
"SSP",
"STD",
"SVC",
"SYP",
"SZL",
"THB",
"TJS",
"TMT",
"TND",
"TOP",
"TRY",
"TTD",
"TWD",
"TZS",
"UAH",
"UGX",
"USD",
"UYU",
"UZS",
"VEF",
"VND",
"VUV",
"WST",
"XAF",
"XAG",
"XAU",
"XBA",
"XBB",
"XBC",
"XBD",
"XCD",
"XDR",
"XOF",
"XPD",
"XPF",
"XPT",
"XSU",
"XTS",
"XUA",
"XXX",
"YER",
"ZAR",
"ZMW",
"ZWL",
}
DEPRECATED_DIMENSIONS = {
"7DayTotals",
"30DayTotals",
}
CORE_DIMENSIONS = {
"ageGroup",
"channel",
"country",
"day",
"gender",
"month",
"sharingService",
"uploaderType",
"video",
}
CONTENT_OWNER_DIMENSIONS = {
"claimedStatus",
"uploaderType",
}
ALL_DIMENSIONS = {
"video",
"playlist",
"channel",
"country",
"province",
"day",
"month",
"insightPlaybackLocationType",
"insightPlaybackLocationDetail",
"liveOrOnDemand",
"subscribedStatus",
"youtubeProduct",
"insightTrafficSourceType",
"insightTrafficSourceDetail",
"deviceType",
"operatingSystem",
"ageGroup",
"gender",
"sharingService",
"elapsedVideoTimeRatio",
"audienceType",
"adType",
"claimedStatus",
"uploaderType",
}
VALID_FILTER_OPTIONS = {
"video": (),
"playlist": (),
"channel": (),
"group": (),
"country": COUNTRIES,
"province": SUBDIVISIONS,
"continent": (
"002",
"019",
"142",
"150",
"009",
),
"subContinent": (
"014",
"017",
"015",
"018",
"011",
"029",
"013",
"021",
"005",
"143",
"030",
"034",
"035",
"145",
"151",
"154",
"039",
"155",
"053",
"054",
"057",
"061",
),
"day": (),
"month": (),
"insightPlaybackLocationType": (
"BROWSE",
"CHANNEL",
"EMBEDDED",
"EXTERNAL_APP",
"MOBILE",
"SEARCH",
"WATCH",
"YT_OTHER",
),
"insightPlaybackLocationDetail": (),
"liveOrOnDemand": (
"LIVE",
"ON_DEMAND",
),
"subscribedStatus": (
"SUBSCRIBED",
"UNSUBSCRIBED",
),
"youtubeProduct": (
"CORE",
"GAMING",
"KIDS",
"UNKNOWN",
),
"insightTrafficSourceType": (
"ADVERTISING",
"ANNOTATION",
"CAMPAIGN_CARD",
"END_SCREEN",
"EXT_URL",
"NO_LINK_EMBEDDED",
"NO_LINK_OTHER",
"NOTIFICATION",
"PLAYLIST",
"PROMOTED",
"RELATED_VIDEO",
"SHORTS",
"SUBSCRIBER",
"YT_CHANNEL",
"YT_OTHER_PAGE",
"YT_PLAYLIST_PAGE",
"YT_SEARCH",
),
"insightTrafficSourceDetail": (
"ADVERTISING",
"CAMPAIGN_CARD",
"END_SCREEN",
"EXT_URL",
"NOTIFICATION",
"RELATED_VIDEO",
"SUBSCRIBER",
"YT_CHANNEL",
"YT_OTHER_PAGE",
"YT_SEARCH",
),
"deviceType": (
"DESKTOP",
"GAME_CONSOLE",
"MOBILE",
"TABLET",
"TV",
"UNKNOWN_PLATFORM",
),
"operatingSystem": (
"ANDROID",
"BADA",
"BLACKBERRY",
"CHROMECAST",
"DOCOMO",
"FIREFOX",
"HIPTOP",
"IOS",
"KAIOS",
"LINUX",
"MACINTOSH",
"MEEGO",
"NINTENDO_3DS",
"OTHER",
"PLAYSTATION",
"PLAYSTATION_VITA",
"REALMEDIA",
"SMART_TV",
"SYMBIAN",
"TIZEN",
"WEBOS",
"WII",
"WINDOWS",
"WINDOWS_MOBILE",
"XBOX",
),
"ageGroup": (
"age13-17",
"age18-24",
"age25-34",
"age35-44",
"age45-54",
"age55-64",
"age65-",
),
"gender": (
"female",
"male",
),
"sharingService": (
"AMEBA",
"ANDROID_EMAIL",
"ANDROID_MESSENGER",
"ANDROID_MMS",
"BBM",
"BLOGGER",
"COPY_PASTE",
"CYWORLD",
"DIGG",
"DROPBOX",
"EMBED",
"MAIL",
"FACEBOOK",
"FACEBOOK_MESSENGER",
"FACEBOOK_PAGES",
"FOTKA",
"GMAIL",
"GOO",
"GOOGLEPLUS",
"GO_SMS",
"GROUPME",
"HANGOUTS",
"HI5",
"HTC_MMS",
"INBOX",
"IOS_SYSTEM_ACTIVITY_DIALOG",
"KAKAO_STORY",
"KAKAO",
"KIK",
"LGE_EMAIL",
"LINE",
"LINKEDIN",
"LIVEJOURNAL",
"MENEAME",
"MIXI",
"MOTOROLA_MESSAGING",
"MYSPACE",
"NAVER",
"NEARBY_SHARE",
"NUJIJ",
"ODNOKLASSNIKI",
"OTHER",
"PINTEREST",
"RAKUTEN",
"REDDIT",
"SKYPE",
"SKYBLOG",
"SONY_CONVERSATIONS",
"STUMBLEUPON",
"TELEGRAM",
"TEXT_MESSAGE",
"TUENTI",
"TUMBLR",
"TWITTER",
"UNKNOWN",
"VERIZON_MMS",
"VIBER",
"VKONTATKE",
"WECHAT",
"WEIBO",
"WHATS_APP",
"WYKOP",
"YAHOO",
"YOUTUBE_GAMING",
"YOUTUBE_KIDS",
"YOUTUBE_MUSIC",
"YOUTUBE_TV",
),
"elapsedVideoTimeRatio": tuple(f"{n/100}" for n in range(1, 101)),
"audienceType": (
"ORGANIC",
"AD_INSTREAM",
"AD_INDISPLAY",
),
"adType": (
"auctionBumperInstream",
"auctionDisplay",
"auctionInstream",
"auctionTrueviewInslate",
"auctionTrueviewInstream",
"auctionUnknown",
"reservedBumperInstream",
"reservedClickToPlay",
"reservedDisplay",
"reservedInstream",
"reservedInstreamSelect",
"reservedMasthead",
"reservedUnknown",
"unknown",
),
"claimedStatus": ("claimed",),
"uploaderType": (
"self",
"thirdParty",
),
"isCurated": ("1",),
}
ALL_FILTERS = set(VALID_FILTER_OPTIONS.keys())
CORE_METRICS = {
"annotationClickThroughRate",
"annotationCloseRate",
"averageViewDuration",
"comments",
"dislikes",
"estimatedMinutesWatched",
"estimatedRevenue",
"likes",
"shares",
"subscribersGained",
"subscribersLost",
"viewerPercentage",
"views",
}
ALL_METRICS_ORDERED = (
"views",
"redViews",
"comments",
"likes",
"dislikes",
"videosAddedToPlaylists",
"videosRemovedFromPlaylists",
"shares",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
"annotationClickThroughRate",
"annotationCloseRate",
"annotationImpressions",
"annotationClickableImpressions",
"annotationClosableImpressions",
"annotationClicks",
"annotationCloses",
"cardClickRate",
"cardTeaserClickRate",
"cardImpressions",
"cardTeaserImpressions",
"cardClicks",
"cardTeaserClicks",
"subscribersGained",
"subscribersLost",
"estimatedRevenue",
"estimatedAdRevenue",
"grossRevenue",
"estimatedRedPartnerRevenue",
"monetizedPlaybacks",
"playbackBasedCpm",
"adImpressions",
"cpm",
"viewerPercentage",
"audienceWatchRatio",
"relativeRetentionPerformance",
"playlistStarts",
"viewsPerPlaylistStart",
"averageTimeInPlaylist",
)
ALL_METRICS = set(ALL_METRICS_ORDERED)
ALL_VIDEO_METRICS = {
"views",
"redViews",
"comments",
"likes",
"dislikes",
"videosAddedToPlaylists",
"videosRemovedFromPlaylists",
"shares",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
"annotationClickThroughRate",
"annotationCloseRate",
"annotationImpressions",
"annotationClickableImpressions",
"annotationClosableImpressions",
"annotationClicks",
"annotationCloses",
"cardClickRate",
"cardTeaserClickRate",
"cardImpressions",
"cardTeaserImpressions",
"cardClicks",
"cardTeaserClicks",
"subscribersGained",
"subscribersLost",
"estimatedRevenue",
"estimatedAdRevenue",
"grossRevenue",
"estimatedRedPartnerRevenue",
"monetizedPlaybacks",
"playbackBasedCpm",
"adImpressions",
"cpm",
}
ALL_PROVINCE_METRICS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
"annotationClickThroughRate",
"annotationCloseRate",
"annotationImpressions",
"annotationClickableImpressions",
"annotationClosableImpressions",
"annotationClicks",
"annotationCloses",
"cardClickRate",
"cardTeaserClickRate",
"cardImpressions",
"cardTeaserImpressions",
"cardClicks",
"cardTeaserClicks",
}
SUBSCRIPTION_METRICS = {
"views",
"redViews",
"likes",
"dislikes",
"videosAddedToPlaylists",
"videosRemovedFromPlaylists",
"shares",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
"annotationClickThroughRate",
"annotationCloseRate",
"annotationImpressions",
"annotationClickableImpressions",
"annotationClosableImpressions",
"annotationClicks",
"annotationCloses",
"cardClickRate",
"cardTeaserClickRate",
"cardImpressions",
"cardTeaserImpressions",
"cardClicks",
"cardTeaserClicks",
}
LESSER_SUBSCRIPTION_METRICS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
"annotationClickThroughRate",
"annotationCloseRate",
"annotationImpressions",
"annotationClickableImpressions",
"annotationClosableImpressions",
"annotationClicks",
"annotationCloses",
"cardClickRate",
"cardTeaserClickRate",
"cardImpressions",
"cardTeaserImpressions",
"cardClicks",
"cardTeaserClicks",
}
LIVE_PLAYBACK_DETAIL_METRICS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
}
VIEW_PERCENTAGE_PLAYBACK_DETAIL_METRICS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"averageViewPercentage",
}
LOCATION_AND_TRAFFIC_METRICS = {
"views",
"estimatedMinutesWatched",
}
ALL_PLAYLIST_METRICS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"averageViewDuration",
"playlistStarts",
"viewsPerPlaylistStart",
"averageTimeInPlaylist",
}
LOCATION_AND_TRAFFIC_PLAYLIST_METRICS = {
"views",
"estimatedMinutesWatched",
"playlistStarts",
"viewsPerPlaylistStart",
"averageTimeInPlaylist",
}
LOCATION_AND_TRAFFIC_SORT_OPTIONS = {
"views",
"estimatedMinutesWatched",
}
TOP_VIDEOS_SORT_OPTIONS = {
"views",
"redViews",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
}
TOP_VIDEOS_EXTRA_SORT_OPTIONS = {
"views",
"redViews",
"estimatedRevenue",
"estimatedRedPartnerRevenue",
"estimatedMinutesWatched",
"estimatedRedMinutesWatched",
"subscribersGained",
"subscribersLost",
}
LOCATION_AND_TRAFFIC_PLAYLIST_SORT_OPTIONS = {
"views",
"estimatedMinutesWatched",
"playlistStarts",
}
|
python
|
# -*- coding: utf-8 -*-
# :Project: pglast -- DO NOT EDIT: automatically extracted from struct_defs.json @ 13-2.1.0-0-gd1d0186
# :Author: Lele Gaifax <[email protected]>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2021 Lele Gaifax
#
from collections import namedtuple
from decimal import Decimal
from enum import Enum
SlotTypeInfo = namedtuple('SlotTypeInfo', ['c_type', 'py_type', 'adaptor'])
def _serialize_node(n, depth, ellipsis, skip_none):
d = {'@': n.__class__.__name__}
for a in n:
v = _serialize_value(getattr(n, a), depth, ellipsis, skip_none)
if not skip_none or v is not None:
d[a] = v
return d
def _serialize_value(v, depth, ellipsis, skip_none):
if isinstance(v, Node):
if depth is None or depth > 0:
v = _serialize_node(v, None if depth is None else depth - 1,
ellipsis, skip_none)
else:
v = ellipsis
elif isinstance(v, tuple):
if depth is None or depth > 0:
v = tuple(_serialize_value(i, None if depth is None else depth - 1,
ellipsis, skip_none)
for i in v)
else:
v = ellipsis
elif isinstance(v, Enum):
v = {'#': v.__class__.__name__, 'name': v.name, 'value': v.value}
return v
class Omissis:
def __eq__(self, other):
if other is ... or other is self:
return True
return False
def __repr__(self):
return '…'
Omissis = Omissis()
"Marker value used as default for the ellipsis argument"
class Node:
"Base class for all AST nodes."
__slots__ = ()
def __init__(self, data):
if not isinstance(data, dict): # pragma: no cover
raise ValueError(f'Bad argument, expected a dictionary, got {type(data)!r}')
if '@' not in data: # pragma: no cover
raise ValueError('Bad argument, expected a dictionary with a "@" key')
if data['@'] != self.__class__.__name__:
raise ValueError(f'Bad argument, wrong "@" value, expected'
f' {self.__class__.__name__!r}, got {data["@"]!r}')
G = globals()
for a in self:
v = data.get(a)
if v is not None:
if isinstance(v, dict) and '@' in v:
v = G[v['@']](v)
elif isinstance(v, (tuple, list)):
v = tuple(G[i['@']](i) if isinstance(i, dict) and '@' in i else i
for i in v)
setattr(self, a, v)
def __iter__(self):
"Iterate over all attribute names of this node."
return iter(self.__slots__)
def __repr__(self):
"Build a representation of the whole node and its subtree, for debug."
attrs = []
for a in self:
if a != 'location':
v = getattr(self, a)
if v is not None:
attrs.append(f'{a}={v!r}')
if attrs:
attrs = ' ' + ' '.join(attrs)
else:
attrs = ''
return '<' + self.__class__.__name__ + attrs + '>'
def __eq__(self, other):
'''
Compare two nodes, returning ``True`` if they are considered equivalent.
This is mainly an helper method used by tests: for this reason, two nodes are
considered equal when all their attributes match, ignoring *positional* ones such as
``location``, ``stmt_len`` and ``stmt_location``.
'''
if not isinstance(other, type(self)):
return False
for a in self:
if ((a not in ('location', 'stmt_len', 'stmt_location')
and getattr(self, a) != getattr(other, a))):
return False
return True
def __call__(self, depth=None, ellipsis=Omissis, skip_none=False):
'''Serialize the node as a structure made of simple Python data-types.
:type depth: ``None`` or ``int``
:param depth: if not ``None``, the maximum depth to reach
:param ellipsis: the marker value that will be used to replace cut-off branch
:param bool skip_none: whether ``None``-valued attributes should be elided
:param bool enum_name: whether Enums will be rendered as their name only
:return: a :class:`dict` instance
This performs a top-down recursive visit to the whole AST tree: each :class:`Node`
instance becomes a dictionary with a special ``@`` key carrying the node type, lists
becomes tuples and ``Enum`` instances become dictionaries with a special ``#`` key
carrying the enum name.'''
return _serialize_node(self, depth, ellipsis, skip_none)
def __setattr__(self, name, value):
'''Validate the given `value` and if acceptable assign it to the `name` attribute.
This tries to coerce the given `value` accordingly with the *ctype* of the
attribute, raising opportune exception when that is not possible.
'''
if value is not None:
ctype, ptype, adaptor = self.__slots__[name]
if not isinstance(ptype, tuple):
ptype = (ptype,)
if not isinstance(value, ptype):
raise ValueError(f'Bad value for attribute {self.__class__.__name__}'
f'.{name}, expected {ptype}, got {type(value)}:'
f' {value!r}')
if adaptor is not None:
value = adaptor(value)
elif ctype != 'char*':
from pglast import enums
if hasattr(enums, ctype):
enum = getattr(enums, ctype)
if not isinstance(value, enum):
if isinstance(value, dict) and '#' in value:
if value['#'] != ctype:
raise ValueError(f'Bad value for attribute'
f' {self.__class__.__name__}.{name},'
f' expected a {ptype}, got'
f' {value!r}') from None
if 'name' in value:
value = value['name']
elif 'value' in value:
value = value['value']
else:
raise ValueError(f'Bad value for attribute'
f' {self.__class__.__name__}.{name},'
f' expected a {ptype}, got'
f' {value!r}') from None
try:
if isinstance(value, str) and len(value) > 1:
value = enum[value]
else:
value = enum(value)
except (KeyError, ValueError):
raise ValueError(f'Bad value for attribute'
f' {self.__class__.__name__}.{name},'
f' expected a {ptype}, got'
f' {value!r}') from None
else:
if ctype.endswith('*'):
cls = globals().get(ctype[:-1])
if cls is None:
raise NotImplementedError(f'Unhandled {ctype!r} for attribute'
f' {self.__class__.__name__}.{name}')
if isinstance(value, dict) and '@' in value:
value = cls(value)
super().__setattr__(name, value)
class Expr(Node):
'''Abstract super class of several *expression* classes.'''
__slots__ = ()
class Value(Node):
'''Abstract super class, representing PG's `Value`__ union type.
__ https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/include/nodes/value.h
'''
__slots__ = ()
def __init__(self, value=None):
if ((value is not None
and isinstance(value, dict)
and '@' in value)):
super().__init__(value)
else:
self.val = value
class BitString(Value):
'''Implement the ``T_BitString`` variant of the :class:`Value` union.'''
__slots__ = {'val': SlotTypeInfo('char*', str, None)}
class Float(Value):
'''Implement the ``T_Float`` variant of the :class:`Value` union.'''
__slots__ = {'val': SlotTypeInfo('char*', (str, Decimal), Decimal)}
class Integer(Value):
'''Implement the ``T_Integer`` variant of the :class:`Value` union.'''
__slots__ = {'val': SlotTypeInfo('char*', int, None)}
class Null(Value):
'''Implement the ``T_Null`` variant of the :class:`Value` union.'''
__slots__ = {'val': SlotTypeInfo('char*', type(None), None)}
class String(Value):
'''Implement the ``T_String`` variant of the :class:`Value` union.'''
__slots__ = {'val': SlotTypeInfo('char*', str, None)}
class A_ArrayExpr(Node):
__slots__ = {'elements': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, elements=None, location=None): # pragma: no cover # noqa: E501
if ((elements is not None
and location is None # noqa: E501
and isinstance(elements, dict)
and '@' in elements)):
super().__init__(elements)
else:
self.elements = elements
self.location = location
class A_Const(Node):
__slots__ = {'val': 'Value', 'location': 'int'} # noqa: E501
def __init__(self, val=None, location=None): # pragma: no cover # noqa: E501
if ((val is not None
and location is None # noqa: E501
and isinstance(val, dict)
and '@' in val)):
super().__init__(val)
else:
self.val = val
self.location = location
class A_Expr(Node):
__slots__ = {'kind': 'A_Expr_Kind', 'name': 'List*', 'lexpr': 'Node*', 'rexpr': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, kind=None, name=None, lexpr=None, rexpr=None, location=None): # pragma: no cover # noqa: E501
if ((kind is not None
and name is lexpr is rexpr is location is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.name = name
self.lexpr = lexpr
self.rexpr = rexpr
self.location = location
class A_Indices(Node):
__slots__ = {'is_slice': 'bool', 'lidx': 'Node*', 'uidx': 'Node*'} # noqa: E501
def __init__(self, is_slice=None, lidx=None, uidx=None): # pragma: no cover # noqa: E501
if ((is_slice is not None
and lidx is uidx is None # noqa: E501
and isinstance(is_slice, dict)
and '@' in is_slice)):
super().__init__(is_slice)
else:
self.is_slice = is_slice
self.lidx = lidx
self.uidx = uidx
class A_Indirection(Node):
__slots__ = {'arg': 'Node*', 'indirection': 'List*'} # noqa: E501
def __init__(self, arg=None, indirection=None): # pragma: no cover # noqa: E501
if ((arg is not None
and indirection is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.indirection = indirection
class A_Star(Node):
__slots__ = {} # noqa: E501
def __init__(self): # pragma: no cover
pass
class AccessPriv(Node):
__slots__ = {'priv_name': 'char*', 'cols': 'List*'} # noqa: E501
def __init__(self, priv_name=None, cols=None): # pragma: no cover # noqa: E501
if ((priv_name is not None
and cols is None # noqa: E501
and isinstance(priv_name, dict)
and '@' in priv_name)):
super().__init__(priv_name)
else:
self.priv_name = priv_name
self.cols = cols
class Aggref(Expr):
__slots__ = {'aggargtypes': 'List*', 'aggdirectargs': 'List*', 'args': 'List*', 'aggorder': 'List*', 'aggdistinct': 'List*', 'aggfilter': 'Expr*', 'aggstar': 'bool', 'aggvariadic': 'bool', 'aggkind': 'char', 'agglevelsup': 'Index', 'aggsplit': 'AggSplit', 'location': 'int'} # noqa: E501
def __init__(self, aggargtypes=None, aggdirectargs=None, args=None, aggorder=None, aggdistinct=None, aggfilter=None, aggstar=None, aggvariadic=None, aggkind=None, agglevelsup=None, aggsplit=None, location=None): # pragma: no cover # noqa: E501
if ((aggargtypes is not None
and aggdirectargs is args is aggorder is aggdistinct is aggfilter is aggstar is aggvariadic is aggkind is agglevelsup is aggsplit is location is None # noqa: E501
and isinstance(aggargtypes, dict)
and '@' in aggargtypes)):
super().__init__(aggargtypes)
else:
self.aggargtypes = aggargtypes
self.aggdirectargs = aggdirectargs
self.args = args
self.aggorder = aggorder
self.aggdistinct = aggdistinct
self.aggfilter = aggfilter
self.aggstar = aggstar
self.aggvariadic = aggvariadic
self.aggkind = aggkind
self.agglevelsup = agglevelsup
self.aggsplit = aggsplit
self.location = location
class Alias(Node):
__slots__ = {'aliasname': 'char*', 'colnames': 'List*'} # noqa: E501
def __init__(self, aliasname=None, colnames=None): # pragma: no cover # noqa: E501
if ((aliasname is not None
and colnames is None # noqa: E501
and isinstance(aliasname, dict)
and '@' in aliasname)):
super().__init__(aliasname)
else:
self.aliasname = aliasname
self.colnames = colnames
class AlterCollationStmt(Node):
__slots__ = {'collname': 'List*'} # noqa: E501
def __init__(self, collname=None): # pragma: no cover # noqa: E501
if ((collname is not None
and isinstance(collname, dict)
and '@' in collname)):
super().__init__(collname)
else:
self.collname = collname
class AlterDatabaseSetStmt(Node):
__slots__ = {'dbname': 'char*', 'setstmt': 'VariableSetStmt*'} # noqa: E501
def __init__(self, dbname=None, setstmt=None): # pragma: no cover # noqa: E501
if ((dbname is not None
and setstmt is None # noqa: E501
and isinstance(dbname, dict)
and '@' in dbname)):
super().__init__(dbname)
else:
self.dbname = dbname
self.setstmt = setstmt
class AlterDatabaseStmt(Node):
__slots__ = {'dbname': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, dbname=None, options=None): # pragma: no cover # noqa: E501
if ((dbname is not None
and options is None # noqa: E501
and isinstance(dbname, dict)
and '@' in dbname)):
super().__init__(dbname)
else:
self.dbname = dbname
self.options = options
class AlterDefaultPrivilegesStmt(Node):
__slots__ = {'options': 'List*', 'action': 'GrantStmt*'} # noqa: E501
def __init__(self, options=None, action=None): # pragma: no cover # noqa: E501
if ((options is not None
and action is None # noqa: E501
and isinstance(options, dict)
and '@' in options)):
super().__init__(options)
else:
self.options = options
self.action = action
class AlterDomainStmt(Node):
__slots__ = {'subtype': 'char', 'typeName': 'List*', 'name': 'char*', 'def_': 'Node*', 'behavior': 'DropBehavior', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, subtype=None, typeName=None, name=None, def_=None, behavior=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((subtype is not None
and typeName is name is def_ is behavior is missing_ok is None # noqa: E501
and isinstance(subtype, dict)
and '@' in subtype)):
super().__init__(subtype)
else:
self.subtype = subtype
self.typeName = typeName
self.name = name
self.def_ = def_
self.behavior = behavior
self.missing_ok = missing_ok
class AlterEnumStmt(Node):
__slots__ = {'typeName': 'List*', 'oldVal': 'char*', 'newVal': 'char*', 'newValNeighbor': 'char*', 'newValIsAfter': 'bool', 'skipIfNewValExists': 'bool'} # noqa: E501
def __init__(self, typeName=None, oldVal=None, newVal=None, newValNeighbor=None, newValIsAfter=None, skipIfNewValExists=None): # pragma: no cover # noqa: E501
if ((typeName is not None
and oldVal is newVal is newValNeighbor is newValIsAfter is skipIfNewValExists is None # noqa: E501
and isinstance(typeName, dict)
and '@' in typeName)):
super().__init__(typeName)
else:
self.typeName = typeName
self.oldVal = oldVal
self.newVal = newVal
self.newValNeighbor = newValNeighbor
self.newValIsAfter = newValIsAfter
self.skipIfNewValExists = skipIfNewValExists
class AlterEventTrigStmt(Node):
__slots__ = {'trigname': 'char*', 'tgenabled': 'char'} # noqa: E501
def __init__(self, trigname=None, tgenabled=None): # pragma: no cover # noqa: E501
if ((trigname is not None
and tgenabled is None # noqa: E501
and isinstance(trigname, dict)
and '@' in trigname)):
super().__init__(trigname)
else:
self.trigname = trigname
self.tgenabled = tgenabled
class AlterExtensionContentsStmt(Node):
__slots__ = {'extname': 'char*', 'action': 'int', 'objtype': 'ObjectType', 'object': 'Node*'} # noqa: E501
def __init__(self, extname=None, action=None, objtype=None, object=None): # pragma: no cover # noqa: E501
if ((extname is not None
and action is objtype is object is None # noqa: E501
and isinstance(extname, dict)
and '@' in extname)):
super().__init__(extname)
else:
self.extname = extname
self.action = action
self.objtype = objtype
self.object = object
class AlterExtensionStmt(Node):
__slots__ = {'extname': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, extname=None, options=None): # pragma: no cover # noqa: E501
if ((extname is not None
and options is None # noqa: E501
and isinstance(extname, dict)
and '@' in extname)):
super().__init__(extname)
else:
self.extname = extname
self.options = options
class AlterFdwStmt(Node):
__slots__ = {'fdwname': 'char*', 'func_options': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, fdwname=None, func_options=None, options=None): # pragma: no cover # noqa: E501
if ((fdwname is not None
and func_options is options is None # noqa: E501
and isinstance(fdwname, dict)
and '@' in fdwname)):
super().__init__(fdwname)
else:
self.fdwname = fdwname
self.func_options = func_options
self.options = options
class AlterForeignServerStmt(Node):
__slots__ = {'servername': 'char*', 'version': 'char*', 'options': 'List*', 'has_version': 'bool'} # noqa: E501
def __init__(self, servername=None, version=None, options=None, has_version=None): # pragma: no cover # noqa: E501
if ((servername is not None
and version is options is has_version is None # noqa: E501
and isinstance(servername, dict)
and '@' in servername)):
super().__init__(servername)
else:
self.servername = servername
self.version = version
self.options = options
self.has_version = has_version
class AlterFunctionStmt(Node):
__slots__ = {'objtype': 'ObjectType', 'func': 'ObjectWithArgs*', 'actions': 'List*'} # noqa: E501
def __init__(self, objtype=None, func=None, actions=None): # pragma: no cover # noqa: E501
if ((objtype is not None
and func is actions is None # noqa: E501
and isinstance(objtype, dict)
and '@' in objtype)):
super().__init__(objtype)
else:
self.objtype = objtype
self.func = func
self.actions = actions
class AlterObjectDependsStmt(Node):
__slots__ = {'objectType': 'ObjectType', 'relation': 'RangeVar*', 'object': 'Node*', 'extname': 'Value*', 'remove': 'bool'} # noqa: E501
def __init__(self, objectType=None, relation=None, object=None, extname=None, remove=None): # pragma: no cover # noqa: E501
if ((objectType is not None
and relation is object is extname is remove is None # noqa: E501
and isinstance(objectType, dict)
and '@' in objectType)):
super().__init__(objectType)
else:
self.objectType = objectType
self.relation = relation
self.object = object
self.extname = extname
self.remove = remove
class AlterObjectSchemaStmt(Node):
__slots__ = {'objectType': 'ObjectType', 'relation': 'RangeVar*', 'object': 'Node*', 'newschema': 'char*', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, objectType=None, relation=None, object=None, newschema=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((objectType is not None
and relation is object is newschema is missing_ok is None # noqa: E501
and isinstance(objectType, dict)
and '@' in objectType)):
super().__init__(objectType)
else:
self.objectType = objectType
self.relation = relation
self.object = object
self.newschema = newschema
self.missing_ok = missing_ok
class AlterOpFamilyStmt(Node):
__slots__ = {'opfamilyname': 'List*', 'amname': 'char*', 'isDrop': 'bool', 'items': 'List*'} # noqa: E501
def __init__(self, opfamilyname=None, amname=None, isDrop=None, items=None): # pragma: no cover # noqa: E501
if ((opfamilyname is not None
and amname is isDrop is items is None # noqa: E501
and isinstance(opfamilyname, dict)
and '@' in opfamilyname)):
super().__init__(opfamilyname)
else:
self.opfamilyname = opfamilyname
self.amname = amname
self.isDrop = isDrop
self.items = items
class AlterOperatorStmt(Node):
__slots__ = {'opername': 'ObjectWithArgs*', 'options': 'List*'} # noqa: E501
def __init__(self, opername=None, options=None): # pragma: no cover # noqa: E501
if ((opername is not None
and options is None # noqa: E501
and isinstance(opername, dict)
and '@' in opername)):
super().__init__(opername)
else:
self.opername = opername
self.options = options
class AlterOwnerStmt(Node):
__slots__ = {'objectType': 'ObjectType', 'relation': 'RangeVar*', 'object': 'Node*', 'newowner': 'RoleSpec*'} # noqa: E501
def __init__(self, objectType=None, relation=None, object=None, newowner=None): # pragma: no cover # noqa: E501
if ((objectType is not None
and relation is object is newowner is None # noqa: E501
and isinstance(objectType, dict)
and '@' in objectType)):
super().__init__(objectType)
else:
self.objectType = objectType
self.relation = relation
self.object = object
self.newowner = newowner
class AlterPolicyStmt(Node):
__slots__ = {'policy_name': 'char*', 'table': 'RangeVar*', 'roles': 'List*', 'qual': 'Node*', 'with_check': 'Node*'} # noqa: E501
def __init__(self, policy_name=None, table=None, roles=None, qual=None, with_check=None): # pragma: no cover # noqa: E501
if ((policy_name is not None
and table is roles is qual is with_check is None # noqa: E501
and isinstance(policy_name, dict)
and '@' in policy_name)):
super().__init__(policy_name)
else:
self.policy_name = policy_name
self.table = table
self.roles = roles
self.qual = qual
self.with_check = with_check
class AlterPublicationStmt(Node):
__slots__ = {'pubname': 'char*', 'options': 'List*', 'tables': 'List*', 'for_all_tables': 'bool', 'tableAction': 'DefElemAction'} # noqa: E501
def __init__(self, pubname=None, options=None, tables=None, for_all_tables=None, tableAction=None): # pragma: no cover # noqa: E501
if ((pubname is not None
and options is tables is for_all_tables is tableAction is None # noqa: E501
and isinstance(pubname, dict)
and '@' in pubname)):
super().__init__(pubname)
else:
self.pubname = pubname
self.options = options
self.tables = tables
self.for_all_tables = for_all_tables
self.tableAction = tableAction
class AlterRoleSetStmt(Node):
__slots__ = {'role': 'RoleSpec*', 'database': 'char*', 'setstmt': 'VariableSetStmt*'} # noqa: E501
def __init__(self, role=None, database=None, setstmt=None): # pragma: no cover # noqa: E501
if ((role is not None
and database is setstmt is None # noqa: E501
and isinstance(role, dict)
and '@' in role)):
super().__init__(role)
else:
self.role = role
self.database = database
self.setstmt = setstmt
class AlterRoleStmt(Node):
__slots__ = {'role': 'RoleSpec*', 'options': 'List*', 'action': 'int'} # noqa: E501
def __init__(self, role=None, options=None, action=None): # pragma: no cover # noqa: E501
if ((role is not None
and options is action is None # noqa: E501
and isinstance(role, dict)
and '@' in role)):
super().__init__(role)
else:
self.role = role
self.options = options
self.action = action
class AlterSeqStmt(Node):
__slots__ = {'sequence': 'RangeVar*', 'options': 'List*', 'for_identity': 'bool', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, sequence=None, options=None, for_identity=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((sequence is not None
and options is for_identity is missing_ok is None # noqa: E501
and isinstance(sequence, dict)
and '@' in sequence)):
super().__init__(sequence)
else:
self.sequence = sequence
self.options = options
self.for_identity = for_identity
self.missing_ok = missing_ok
class AlterStatsStmt(Node):
__slots__ = {'defnames': 'List*', 'stxstattarget': 'int', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, defnames=None, stxstattarget=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((defnames is not None
and stxstattarget is missing_ok is None # noqa: E501
and isinstance(defnames, dict)
and '@' in defnames)):
super().__init__(defnames)
else:
self.defnames = defnames
self.stxstattarget = stxstattarget
self.missing_ok = missing_ok
class AlterSubscriptionStmt(Node):
__slots__ = {'kind': 'AlterSubscriptionType', 'subname': 'char*', 'conninfo': 'char*', 'publication': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, kind=None, subname=None, conninfo=None, publication=None, options=None): # pragma: no cover # noqa: E501
if ((kind is not None
and subname is conninfo is publication is options is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.subname = subname
self.conninfo = conninfo
self.publication = publication
self.options = options
class AlterSystemStmt(Node):
__slots__ = {'setstmt': 'VariableSetStmt*'} # noqa: E501
def __init__(self, setstmt=None): # pragma: no cover # noqa: E501
if ((setstmt is not None
and isinstance(setstmt, dict)
and '@' in setstmt)):
super().__init__(setstmt)
else:
self.setstmt = setstmt
class AlterTSConfigurationStmt(Node):
__slots__ = {'kind': 'AlterTSConfigType', 'cfgname': 'List*', 'tokentype': 'List*', 'dicts': 'List*', 'override': 'bool', 'replace': 'bool', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, kind=None, cfgname=None, tokentype=None, dicts=None, override=None, replace=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((kind is not None
and cfgname is tokentype is dicts is override is replace is missing_ok is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.cfgname = cfgname
self.tokentype = tokentype
self.dicts = dicts
self.override = override
self.replace = replace
self.missing_ok = missing_ok
class AlterTSDictionaryStmt(Node):
__slots__ = {'dictname': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, dictname=None, options=None): # pragma: no cover # noqa: E501
if ((dictname is not None
and options is None # noqa: E501
and isinstance(dictname, dict)
and '@' in dictname)):
super().__init__(dictname)
else:
self.dictname = dictname
self.options = options
class AlterTableCmd(Node):
__slots__ = {'subtype': 'AlterTableType', 'name': 'char*', 'num': 'int16', 'newowner': 'RoleSpec*', 'def_': 'Node*', 'behavior': 'DropBehavior', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, subtype=None, name=None, num=None, newowner=None, def_=None, behavior=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((subtype is not None
and name is num is newowner is def_ is behavior is missing_ok is None # noqa: E501
and isinstance(subtype, dict)
and '@' in subtype)):
super().__init__(subtype)
else:
self.subtype = subtype
self.name = name
self.num = num
self.newowner = newowner
self.def_ = def_
self.behavior = behavior
self.missing_ok = missing_ok
class AlterTableMoveAllStmt(Node):
__slots__ = {'orig_tablespacename': 'char*', 'objtype': 'ObjectType', 'roles': 'List*', 'new_tablespacename': 'char*', 'nowait': 'bool'} # noqa: E501
def __init__(self, orig_tablespacename=None, objtype=None, roles=None, new_tablespacename=None, nowait=None): # pragma: no cover # noqa: E501
if ((orig_tablespacename is not None
and objtype is roles is new_tablespacename is nowait is None # noqa: E501
and isinstance(orig_tablespacename, dict)
and '@' in orig_tablespacename)):
super().__init__(orig_tablespacename)
else:
self.orig_tablespacename = orig_tablespacename
self.objtype = objtype
self.roles = roles
self.new_tablespacename = new_tablespacename
self.nowait = nowait
class AlterTableSpaceOptionsStmt(Node):
__slots__ = {'tablespacename': 'char*', 'options': 'List*', 'isReset': 'bool'} # noqa: E501
def __init__(self, tablespacename=None, options=None, isReset=None): # pragma: no cover # noqa: E501
if ((tablespacename is not None
and options is isReset is None # noqa: E501
and isinstance(tablespacename, dict)
and '@' in tablespacename)):
super().__init__(tablespacename)
else:
self.tablespacename = tablespacename
self.options = options
self.isReset = isReset
class AlterTableStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'cmds': 'List*', 'relkind': 'ObjectType', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, relation=None, cmds=None, relkind=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((relation is not None
and cmds is relkind is missing_ok is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.cmds = cmds
self.relkind = relkind
self.missing_ok = missing_ok
class AlterTypeStmt(Node):
__slots__ = {'typeName': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, typeName=None, options=None): # pragma: no cover # noqa: E501
if ((typeName is not None
and options is None # noqa: E501
and isinstance(typeName, dict)
and '@' in typeName)):
super().__init__(typeName)
else:
self.typeName = typeName
self.options = options
class AlterUserMappingStmt(Node):
__slots__ = {'user': 'RoleSpec*', 'servername': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, user=None, servername=None, options=None): # pragma: no cover # noqa: E501
if ((user is not None
and servername is options is None # noqa: E501
and isinstance(user, dict)
and '@' in user)):
super().__init__(user)
else:
self.user = user
self.servername = servername
self.options = options
class AlternativeSubPlan(Expr):
__slots__ = {'subplans': 'List*'} # noqa: E501
def __init__(self, subplans=None): # pragma: no cover # noqa: E501
if ((subplans is not None
and isinstance(subplans, dict)
and '@' in subplans)):
super().__init__(subplans)
else:
self.subplans = subplans
class ArrayCoerceExpr(Expr):
__slots__ = {'arg': 'Expr*', 'elemexpr': 'Expr*', 'resulttypmod': 'int32', 'coerceformat': 'CoercionForm', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, elemexpr=None, resulttypmod=None, coerceformat=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and elemexpr is resulttypmod is coerceformat is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.elemexpr = elemexpr
self.resulttypmod = resulttypmod
self.coerceformat = coerceformat
self.location = location
class ArrayExpr(Expr):
__slots__ = {'elements': 'List*', 'multidims': 'bool', 'location': 'int'} # noqa: E501
def __init__(self, elements=None, multidims=None, location=None): # pragma: no cover # noqa: E501
if ((elements is not None
and multidims is location is None # noqa: E501
and isinstance(elements, dict)
and '@' in elements)):
super().__init__(elements)
else:
self.elements = elements
self.multidims = multidims
self.location = location
class BoolExpr(Expr):
__slots__ = {'boolop': 'BoolExprType', 'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, boolop=None, args=None, location=None): # pragma: no cover # noqa: E501
if ((boolop is not None
and args is location is None # noqa: E501
and isinstance(boolop, dict)
and '@' in boolop)):
super().__init__(boolop)
else:
self.boolop = boolop
self.args = args
self.location = location
class BooleanTest(Expr):
__slots__ = {'arg': 'Expr*', 'booltesttype': 'BoolTestType', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, booltesttype=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and booltesttype is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.booltesttype = booltesttype
self.location = location
class CallContext(Node):
__slots__ = {'atomic': 'bool'} # noqa: E501
def __init__(self, atomic=None): # pragma: no cover # noqa: E501
if ((atomic is not None
and isinstance(atomic, dict)
and '@' in atomic)):
super().__init__(atomic)
else:
self.atomic = atomic
class CallStmt(Node):
__slots__ = {'funccall': 'FuncCall*', 'funcexpr': 'FuncExpr*'} # noqa: E501
def __init__(self, funccall=None, funcexpr=None): # pragma: no cover # noqa: E501
if ((funccall is not None
and funcexpr is None # noqa: E501
and isinstance(funccall, dict)
and '@' in funccall)):
super().__init__(funccall)
else:
self.funccall = funccall
self.funcexpr = funcexpr
class CaseExpr(Expr):
__slots__ = {'arg': 'Expr*', 'args': 'List*', 'defresult': 'Expr*', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, args=None, defresult=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and args is defresult is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.args = args
self.defresult = defresult
self.location = location
class CaseTestExpr(Expr):
__slots__ = {'typeMod': 'int32'} # noqa: E501
def __init__(self, typeMod=None): # pragma: no cover # noqa: E501
if ((typeMod is not None
and isinstance(typeMod, dict)
and '@' in typeMod)):
super().__init__(typeMod)
else:
self.typeMod = typeMod
class CaseWhen(Expr):
__slots__ = {'expr': 'Expr*', 'result': 'Expr*', 'location': 'int'} # noqa: E501
def __init__(self, expr=None, result=None, location=None): # pragma: no cover # noqa: E501
if ((expr is not None
and result is location is None # noqa: E501
and isinstance(expr, dict)
and '@' in expr)):
super().__init__(expr)
else:
self.expr = expr
self.result = result
self.location = location
class CheckPointStmt(Node):
__slots__ = {} # noqa: E501
def __init__(self): # pragma: no cover
pass
class ClosePortalStmt(Node):
__slots__ = {'portalname': 'char*'} # noqa: E501
def __init__(self, portalname=None): # pragma: no cover # noqa: E501
if ((portalname is not None
and isinstance(portalname, dict)
and '@' in portalname)):
super().__init__(portalname)
else:
self.portalname = portalname
class ClusterStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'indexname': 'char*', 'options': 'int'} # noqa: E501
def __init__(self, relation=None, indexname=None, options=None): # pragma: no cover # noqa: E501
if ((relation is not None
and indexname is options is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.indexname = indexname
self.options = options
class CoalesceExpr(Expr):
__slots__ = {'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, args=None, location=None): # pragma: no cover # noqa: E501
if ((args is not None
and location is None # noqa: E501
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
self.location = location
class CoerceToDomain(Expr):
__slots__ = {'arg': 'Expr*', 'resulttypmod': 'int32', 'coercionformat': 'CoercionForm', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, resulttypmod=None, coercionformat=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and resulttypmod is coercionformat is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.resulttypmod = resulttypmod
self.coercionformat = coercionformat
self.location = location
class CoerceToDomainValue(Expr):
__slots__ = {'typeMod': 'int32', 'location': 'int'} # noqa: E501
def __init__(self, typeMod=None, location=None): # pragma: no cover # noqa: E501
if ((typeMod is not None
and location is None # noqa: E501
and isinstance(typeMod, dict)
and '@' in typeMod)):
super().__init__(typeMod)
else:
self.typeMod = typeMod
self.location = location
class CoerceViaIO(Expr):
__slots__ = {'arg': 'Expr*', 'coerceformat': 'CoercionForm', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, coerceformat=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and coerceformat is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.coerceformat = coerceformat
self.location = location
class CollateClause(Node):
__slots__ = {'arg': 'Node*', 'collname': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, collname=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and collname is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.collname = collname
self.location = location
class CollateExpr(Expr):
__slots__ = {'arg': 'Expr*', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.location = location
class ColumnDef(Node):
__slots__ = {'colname': 'char*', 'typeName': 'TypeName*', 'inhcount': 'int', 'is_local': 'bool', 'is_not_null': 'bool', 'is_from_type': 'bool', 'storage': 'char', 'raw_default': 'Node*', 'cooked_default': 'Node*', 'identity': 'char', 'identitySequence': 'RangeVar*', 'generated': 'char', 'collClause': 'CollateClause*', 'constraints': 'List*', 'fdwoptions': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, colname=None, typeName=None, inhcount=None, is_local=None, is_not_null=None, is_from_type=None, storage=None, raw_default=None, cooked_default=None, identity=None, identitySequence=None, generated=None, collClause=None, constraints=None, fdwoptions=None, location=None): # pragma: no cover # noqa: E501
if ((colname is not None
and typeName is inhcount is is_local is is_not_null is is_from_type is storage is raw_default is cooked_default is identity is identitySequence is generated is collClause is constraints is fdwoptions is location is None # noqa: E501
and isinstance(colname, dict)
and '@' in colname)):
super().__init__(colname)
else:
self.colname = colname
self.typeName = typeName
self.inhcount = inhcount
self.is_local = is_local
self.is_not_null = is_not_null
self.is_from_type = is_from_type
self.storage = storage
self.raw_default = raw_default
self.cooked_default = cooked_default
self.identity = identity
self.identitySequence = identitySequence
self.generated = generated
self.collClause = collClause
self.constraints = constraints
self.fdwoptions = fdwoptions
self.location = location
class ColumnRef(Node):
__slots__ = {'fields': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, fields=None, location=None): # pragma: no cover # noqa: E501
if ((fields is not None
and location is None # noqa: E501
and isinstance(fields, dict)
and '@' in fields)):
super().__init__(fields)
else:
self.fields = fields
self.location = location
class CommentStmt(Node):
__slots__ = {'objtype': 'ObjectType', 'object': 'Node*', 'comment': 'char*'} # noqa: E501
def __init__(self, objtype=None, object=None, comment=None): # pragma: no cover # noqa: E501
if ((objtype is not None
and object is comment is None # noqa: E501
and isinstance(objtype, dict)
and '@' in objtype)):
super().__init__(objtype)
else:
self.objtype = objtype
self.object = object
self.comment = comment
class CommonTableExpr(Node):
__slots__ = {'ctename': 'char*', 'aliascolnames': 'List*', 'ctematerialized': 'CTEMaterialize', 'ctequery': 'Node*', 'location': 'int', 'cterecursive': 'bool', 'cterefcount': 'int', 'ctecolnames': 'List*', 'ctecoltypes': 'List*', 'ctecoltypmods': 'List*', 'ctecolcollations': 'List*'} # noqa: E501
def __init__(self, ctename=None, aliascolnames=None, ctematerialized=None, ctequery=None, location=None, cterecursive=None, cterefcount=None, ctecolnames=None, ctecoltypes=None, ctecoltypmods=None, ctecolcollations=None): # pragma: no cover # noqa: E501
if ((ctename is not None
and aliascolnames is ctematerialized is ctequery is location is cterecursive is cterefcount is ctecolnames is ctecoltypes is ctecoltypmods is ctecolcollations is None # noqa: E501
and isinstance(ctename, dict)
and '@' in ctename)):
super().__init__(ctename)
else:
self.ctename = ctename
self.aliascolnames = aliascolnames
self.ctematerialized = ctematerialized
self.ctequery = ctequery
self.location = location
self.cterecursive = cterecursive
self.cterefcount = cterefcount
self.ctecolnames = ctecolnames
self.ctecoltypes = ctecoltypes
self.ctecoltypmods = ctecoltypmods
self.ctecolcollations = ctecolcollations
class CompositeTypeStmt(Node):
__slots__ = {'typevar': 'RangeVar*', 'coldeflist': 'List*'} # noqa: E501
def __init__(self, typevar=None, coldeflist=None): # pragma: no cover # noqa: E501
if ((typevar is not None
and coldeflist is None # noqa: E501
and isinstance(typevar, dict)
and '@' in typevar)):
super().__init__(typevar)
else:
self.typevar = typevar
self.coldeflist = coldeflist
class Constraint(Node):
__slots__ = {'contype': 'ConstrType', 'conname': 'char*', 'deferrable': 'bool', 'initdeferred': 'bool', 'location': 'int', 'is_no_inherit': 'bool', 'raw_expr': 'Node*', 'cooked_expr': 'char*', 'generated_when': 'char', 'keys': 'List*', 'including': 'List*', 'exclusions': 'List*', 'options': 'List*', 'indexname': 'char*', 'indexspace': 'char*', 'reset_default_tblspc': 'bool', 'access_method': 'char*', 'where_clause': 'Node*', 'pktable': 'RangeVar*', 'fk_attrs': 'List*', 'pk_attrs': 'List*', 'fk_matchtype': 'char', 'fk_upd_action': 'char', 'fk_del_action': 'char', 'old_conpfeqop': 'List*', 'skip_validation': 'bool', 'initially_valid': 'bool'} # noqa: E501
def __init__(self, contype=None, conname=None, deferrable=None, initdeferred=None, location=None, is_no_inherit=None, raw_expr=None, cooked_expr=None, generated_when=None, keys=None, including=None, exclusions=None, options=None, indexname=None, indexspace=None, reset_default_tblspc=None, access_method=None, where_clause=None, pktable=None, fk_attrs=None, pk_attrs=None, fk_matchtype=None, fk_upd_action=None, fk_del_action=None, old_conpfeqop=None, skip_validation=None, initially_valid=None): # pragma: no cover # noqa: E501
if ((contype is not None
and conname is deferrable is initdeferred is location is is_no_inherit is raw_expr is cooked_expr is generated_when is keys is including is exclusions is options is indexname is indexspace is reset_default_tblspc is access_method is where_clause is pktable is fk_attrs is pk_attrs is fk_matchtype is fk_upd_action is fk_del_action is old_conpfeqop is skip_validation is initially_valid is None # noqa: E501
and isinstance(contype, dict)
and '@' in contype)):
super().__init__(contype)
else:
self.contype = contype
self.conname = conname
self.deferrable = deferrable
self.initdeferred = initdeferred
self.location = location
self.is_no_inherit = is_no_inherit
self.raw_expr = raw_expr
self.cooked_expr = cooked_expr
self.generated_when = generated_when
self.keys = keys
self.including = including
self.exclusions = exclusions
self.options = options
self.indexname = indexname
self.indexspace = indexspace
self.reset_default_tblspc = reset_default_tblspc
self.access_method = access_method
self.where_clause = where_clause
self.pktable = pktable
self.fk_attrs = fk_attrs
self.pk_attrs = pk_attrs
self.fk_matchtype = fk_matchtype
self.fk_upd_action = fk_upd_action
self.fk_del_action = fk_del_action
self.old_conpfeqop = old_conpfeqop
self.skip_validation = skip_validation
self.initially_valid = initially_valid
class ConstraintsSetStmt(Node):
__slots__ = {'constraints': 'List*', 'deferred': 'bool'} # noqa: E501
def __init__(self, constraints=None, deferred=None): # pragma: no cover # noqa: E501
if ((constraints is not None
and deferred is None # noqa: E501
and isinstance(constraints, dict)
and '@' in constraints)):
super().__init__(constraints)
else:
self.constraints = constraints
self.deferred = deferred
class ConvertRowtypeExpr(Expr):
__slots__ = {'arg': 'Expr*', 'convertformat': 'CoercionForm', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, convertformat=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and convertformat is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.convertformat = convertformat
self.location = location
class CopyStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'query': 'Node*', 'attlist': 'List*', 'is_from': 'bool', 'is_program': 'bool', 'filename': 'char*', 'options': 'List*', 'whereClause': 'Node*'} # noqa: E501
def __init__(self, relation=None, query=None, attlist=None, is_from=None, is_program=None, filename=None, options=None, whereClause=None): # pragma: no cover # noqa: E501
if ((relation is not None
and query is attlist is is_from is is_program is filename is options is whereClause is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.query = query
self.attlist = attlist
self.is_from = is_from
self.is_program = is_program
self.filename = filename
self.options = options
self.whereClause = whereClause
class CreateAmStmt(Node):
__slots__ = {'amname': 'char*', 'handler_name': 'List*', 'amtype': 'char'} # noqa: E501
def __init__(self, amname=None, handler_name=None, amtype=None): # pragma: no cover # noqa: E501
if ((amname is not None
and handler_name is amtype is None # noqa: E501
and isinstance(amname, dict)
and '@' in amname)):
super().__init__(amname)
else:
self.amname = amname
self.handler_name = handler_name
self.amtype = amtype
class CreateCastStmt(Node):
__slots__ = {'sourcetype': 'TypeName*', 'targettype': 'TypeName*', 'func': 'ObjectWithArgs*', 'context': 'CoercionContext', 'inout': 'bool'} # noqa: E501
def __init__(self, sourcetype=None, targettype=None, func=None, context=None, inout=None): # pragma: no cover # noqa: E501
if ((sourcetype is not None
and targettype is func is context is inout is None # noqa: E501
and isinstance(sourcetype, dict)
and '@' in sourcetype)):
super().__init__(sourcetype)
else:
self.sourcetype = sourcetype
self.targettype = targettype
self.func = func
self.context = context
self.inout = inout
class CreateConversionStmt(Node):
__slots__ = {'conversion_name': 'List*', 'for_encoding_name': 'char*', 'to_encoding_name': 'char*', 'func_name': 'List*', 'def_': 'bool'} # noqa: E501
def __init__(self, conversion_name=None, for_encoding_name=None, to_encoding_name=None, func_name=None, def_=None): # pragma: no cover # noqa: E501
if ((conversion_name is not None
and for_encoding_name is to_encoding_name is func_name is def_ is None # noqa: E501
and isinstance(conversion_name, dict)
and '@' in conversion_name)):
super().__init__(conversion_name)
else:
self.conversion_name = conversion_name
self.for_encoding_name = for_encoding_name
self.to_encoding_name = to_encoding_name
self.func_name = func_name
self.def_ = def_
class CreateDomainStmt(Node):
__slots__ = {'domainname': 'List*', 'typeName': 'TypeName*', 'collClause': 'CollateClause*', 'constraints': 'List*'} # noqa: E501
def __init__(self, domainname=None, typeName=None, collClause=None, constraints=None): # pragma: no cover # noqa: E501
if ((domainname is not None
and typeName is collClause is constraints is None # noqa: E501
and isinstance(domainname, dict)
and '@' in domainname)):
super().__init__(domainname)
else:
self.domainname = domainname
self.typeName = typeName
self.collClause = collClause
self.constraints = constraints
class CreateEnumStmt(Node):
__slots__ = {'typeName': 'List*', 'vals': 'List*'} # noqa: E501
def __init__(self, typeName=None, vals=None): # pragma: no cover # noqa: E501
if ((typeName is not None
and vals is None # noqa: E501
and isinstance(typeName, dict)
and '@' in typeName)):
super().__init__(typeName)
else:
self.typeName = typeName
self.vals = vals
class CreateEventTrigStmt(Node):
__slots__ = {'trigname': 'char*', 'eventname': 'char*', 'whenclause': 'List*', 'funcname': 'List*'} # noqa: E501
def __init__(self, trigname=None, eventname=None, whenclause=None, funcname=None): # pragma: no cover # noqa: E501
if ((trigname is not None
and eventname is whenclause is funcname is None # noqa: E501
and isinstance(trigname, dict)
and '@' in trigname)):
super().__init__(trigname)
else:
self.trigname = trigname
self.eventname = eventname
self.whenclause = whenclause
self.funcname = funcname
class CreateExtensionStmt(Node):
__slots__ = {'extname': 'char*', 'if_not_exists': 'bool', 'options': 'List*'} # noqa: E501
def __init__(self, extname=None, if_not_exists=None, options=None): # pragma: no cover # noqa: E501
if ((extname is not None
and if_not_exists is options is None # noqa: E501
and isinstance(extname, dict)
and '@' in extname)):
super().__init__(extname)
else:
self.extname = extname
self.if_not_exists = if_not_exists
self.options = options
class CreateFdwStmt(Node):
__slots__ = {'fdwname': 'char*', 'func_options': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, fdwname=None, func_options=None, options=None): # pragma: no cover # noqa: E501
if ((fdwname is not None
and func_options is options is None # noqa: E501
and isinstance(fdwname, dict)
and '@' in fdwname)):
super().__init__(fdwname)
else:
self.fdwname = fdwname
self.func_options = func_options
self.options = options
class CreateForeignServerStmt(Node):
__slots__ = {'servername': 'char*', 'servertype': 'char*', 'version': 'char*', 'fdwname': 'char*', 'if_not_exists': 'bool', 'options': 'List*'} # noqa: E501
def __init__(self, servername=None, servertype=None, version=None, fdwname=None, if_not_exists=None, options=None): # pragma: no cover # noqa: E501
if ((servername is not None
and servertype is version is fdwname is if_not_exists is options is None # noqa: E501
and isinstance(servername, dict)
and '@' in servername)):
super().__init__(servername)
else:
self.servername = servername
self.servertype = servertype
self.version = version
self.fdwname = fdwname
self.if_not_exists = if_not_exists
self.options = options
class CreateForeignTableStmt(Node):
__slots__ = {'base': 'CreateStmt', 'servername': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, base=None, servername=None, options=None): # pragma: no cover # noqa: E501
if ((base is not None
and servername is options is None # noqa: E501
and isinstance(base, dict)
and '@' in base)):
super().__init__(base)
else:
self.base = base
self.servername = servername
self.options = options
class CreateFunctionStmt(Node):
__slots__ = {'is_procedure': 'bool', 'replace': 'bool', 'funcname': 'List*', 'parameters': 'List*', 'returnType': 'TypeName*', 'options': 'List*'} # noqa: E501
def __init__(self, is_procedure=None, replace=None, funcname=None, parameters=None, returnType=None, options=None): # pragma: no cover # noqa: E501
if ((is_procedure is not None
and replace is funcname is parameters is returnType is options is None # noqa: E501
and isinstance(is_procedure, dict)
and '@' in is_procedure)):
super().__init__(is_procedure)
else:
self.is_procedure = is_procedure
self.replace = replace
self.funcname = funcname
self.parameters = parameters
self.returnType = returnType
self.options = options
class CreateOpClassItem(Node):
__slots__ = {'itemtype': 'int', 'name': 'ObjectWithArgs*', 'number': 'int', 'order_family': 'List*', 'class_args': 'List*', 'storedtype': 'TypeName*'} # noqa: E501
def __init__(self, itemtype=None, name=None, number=None, order_family=None, class_args=None, storedtype=None): # pragma: no cover # noqa: E501
if ((itemtype is not None
and name is number is order_family is class_args is storedtype is None # noqa: E501
and isinstance(itemtype, dict)
and '@' in itemtype)):
super().__init__(itemtype)
else:
self.itemtype = itemtype
self.name = name
self.number = number
self.order_family = order_family
self.class_args = class_args
self.storedtype = storedtype
class CreateOpClassStmt(Node):
__slots__ = {'opclassname': 'List*', 'opfamilyname': 'List*', 'amname': 'char*', 'datatype': 'TypeName*', 'items': 'List*', 'isDefault': 'bool'} # noqa: E501
def __init__(self, opclassname=None, opfamilyname=None, amname=None, datatype=None, items=None, isDefault=None): # pragma: no cover # noqa: E501
if ((opclassname is not None
and opfamilyname is amname is datatype is items is isDefault is None # noqa: E501
and isinstance(opclassname, dict)
and '@' in opclassname)):
super().__init__(opclassname)
else:
self.opclassname = opclassname
self.opfamilyname = opfamilyname
self.amname = amname
self.datatype = datatype
self.items = items
self.isDefault = isDefault
class CreateOpFamilyStmt(Node):
__slots__ = {'opfamilyname': 'List*', 'amname': 'char*'} # noqa: E501
def __init__(self, opfamilyname=None, amname=None): # pragma: no cover # noqa: E501
if ((opfamilyname is not None
and amname is None # noqa: E501
and isinstance(opfamilyname, dict)
and '@' in opfamilyname)):
super().__init__(opfamilyname)
else:
self.opfamilyname = opfamilyname
self.amname = amname
class CreatePLangStmt(Node):
__slots__ = {'replace': 'bool', 'plname': 'char*', 'plhandler': 'List*', 'plinline': 'List*', 'plvalidator': 'List*', 'pltrusted': 'bool'} # noqa: E501
def __init__(self, replace=None, plname=None, plhandler=None, plinline=None, plvalidator=None, pltrusted=None): # pragma: no cover # noqa: E501
if ((replace is not None
and plname is plhandler is plinline is plvalidator is pltrusted is None # noqa: E501
and isinstance(replace, dict)
and '@' in replace)):
super().__init__(replace)
else:
self.replace = replace
self.plname = plname
self.plhandler = plhandler
self.plinline = plinline
self.plvalidator = plvalidator
self.pltrusted = pltrusted
class CreatePolicyStmt(Node):
__slots__ = {'policy_name': 'char*', 'table': 'RangeVar*', 'cmd_name': 'char*', 'permissive': 'bool', 'roles': 'List*', 'qual': 'Node*', 'with_check': 'Node*'} # noqa: E501
def __init__(self, policy_name=None, table=None, cmd_name=None, permissive=None, roles=None, qual=None, with_check=None): # pragma: no cover # noqa: E501
if ((policy_name is not None
and table is cmd_name is permissive is roles is qual is with_check is None # noqa: E501
and isinstance(policy_name, dict)
and '@' in policy_name)):
super().__init__(policy_name)
else:
self.policy_name = policy_name
self.table = table
self.cmd_name = cmd_name
self.permissive = permissive
self.roles = roles
self.qual = qual
self.with_check = with_check
class CreatePublicationStmt(Node):
__slots__ = {'pubname': 'char*', 'options': 'List*', 'tables': 'List*', 'for_all_tables': 'bool'} # noqa: E501
def __init__(self, pubname=None, options=None, tables=None, for_all_tables=None): # pragma: no cover # noqa: E501
if ((pubname is not None
and options is tables is for_all_tables is None # noqa: E501
and isinstance(pubname, dict)
and '@' in pubname)):
super().__init__(pubname)
else:
self.pubname = pubname
self.options = options
self.tables = tables
self.for_all_tables = for_all_tables
class CreateRangeStmt(Node):
__slots__ = {'typeName': 'List*', 'params': 'List*'} # noqa: E501
def __init__(self, typeName=None, params=None): # pragma: no cover # noqa: E501
if ((typeName is not None
and params is None # noqa: E501
and isinstance(typeName, dict)
and '@' in typeName)):
super().__init__(typeName)
else:
self.typeName = typeName
self.params = params
class CreateRoleStmt(Node):
__slots__ = {'stmt_type': 'RoleStmtType', 'role': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, stmt_type=None, role=None, options=None): # pragma: no cover # noqa: E501
if ((stmt_type is not None
and role is options is None # noqa: E501
and isinstance(stmt_type, dict)
and '@' in stmt_type)):
super().__init__(stmt_type)
else:
self.stmt_type = stmt_type
self.role = role
self.options = options
class CreateSchemaStmt(Node):
__slots__ = {'schemaname': 'char*', 'authrole': 'RoleSpec*', 'schemaElts': 'List*', 'if_not_exists': 'bool'} # noqa: E501
def __init__(self, schemaname=None, authrole=None, schemaElts=None, if_not_exists=None): # pragma: no cover # noqa: E501
if ((schemaname is not None
and authrole is schemaElts is if_not_exists is None # noqa: E501
and isinstance(schemaname, dict)
and '@' in schemaname)):
super().__init__(schemaname)
else:
self.schemaname = schemaname
self.authrole = authrole
self.schemaElts = schemaElts
self.if_not_exists = if_not_exists
class CreateSeqStmt(Node):
__slots__ = {'sequence': 'RangeVar*', 'options': 'List*', 'for_identity': 'bool', 'if_not_exists': 'bool'} # noqa: E501
def __init__(self, sequence=None, options=None, for_identity=None, if_not_exists=None): # pragma: no cover # noqa: E501
if ((sequence is not None
and options is for_identity is if_not_exists is None # noqa: E501
and isinstance(sequence, dict)
and '@' in sequence)):
super().__init__(sequence)
else:
self.sequence = sequence
self.options = options
self.for_identity = for_identity
self.if_not_exists = if_not_exists
class CreateStatsStmt(Node):
__slots__ = {'defnames': 'List*', 'stat_types': 'List*', 'exprs': 'List*', 'relations': 'List*', 'stxcomment': 'char*', 'if_not_exists': 'bool'} # noqa: E501
def __init__(self, defnames=None, stat_types=None, exprs=None, relations=None, stxcomment=None, if_not_exists=None): # pragma: no cover # noqa: E501
if ((defnames is not None
and stat_types is exprs is relations is stxcomment is if_not_exists is None # noqa: E501
and isinstance(defnames, dict)
and '@' in defnames)):
super().__init__(defnames)
else:
self.defnames = defnames
self.stat_types = stat_types
self.exprs = exprs
self.relations = relations
self.stxcomment = stxcomment
self.if_not_exists = if_not_exists
class CreateStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'tableElts': 'List*', 'inhRelations': 'List*', 'partbound': 'PartitionBoundSpec*', 'partspec': 'PartitionSpec*', 'ofTypename': 'TypeName*', 'constraints': 'List*', 'options': 'List*', 'oncommit': 'OnCommitAction', 'tablespacename': 'char*', 'accessMethod': 'char*', 'if_not_exists': 'bool'} # noqa: E501
def __init__(self, relation=None, tableElts=None, inhRelations=None, partbound=None, partspec=None, ofTypename=None, constraints=None, options=None, oncommit=None, tablespacename=None, accessMethod=None, if_not_exists=None): # pragma: no cover # noqa: E501
if ((relation is not None
and tableElts is inhRelations is partbound is partspec is ofTypename is constraints is options is oncommit is tablespacename is accessMethod is if_not_exists is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.tableElts = tableElts
self.inhRelations = inhRelations
self.partbound = partbound
self.partspec = partspec
self.ofTypename = ofTypename
self.constraints = constraints
self.options = options
self.oncommit = oncommit
self.tablespacename = tablespacename
self.accessMethod = accessMethod
self.if_not_exists = if_not_exists
class CreateSubscriptionStmt(Node):
__slots__ = {'subname': 'char*', 'conninfo': 'char*', 'publication': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, subname=None, conninfo=None, publication=None, options=None): # pragma: no cover # noqa: E501
if ((subname is not None
and conninfo is publication is options is None # noqa: E501
and isinstance(subname, dict)
and '@' in subname)):
super().__init__(subname)
else:
self.subname = subname
self.conninfo = conninfo
self.publication = publication
self.options = options
class CreateTableAsStmt(Node):
__slots__ = {'query': 'Node*', 'into': 'IntoClause*', 'relkind': 'ObjectType', 'is_select_into': 'bool', 'if_not_exists': 'bool'} # noqa: E501
def __init__(self, query=None, into=None, relkind=None, is_select_into=None, if_not_exists=None): # pragma: no cover # noqa: E501
if ((query is not None
and into is relkind is is_select_into is if_not_exists is None # noqa: E501
and isinstance(query, dict)
and '@' in query)):
super().__init__(query)
else:
self.query = query
self.into = into
self.relkind = relkind
self.is_select_into = is_select_into
self.if_not_exists = if_not_exists
class CreateTableSpaceStmt(Node):
__slots__ = {'tablespacename': 'char*', 'owner': 'RoleSpec*', 'location': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, tablespacename=None, owner=None, location=None, options=None): # pragma: no cover # noqa: E501
if ((tablespacename is not None
and owner is location is options is None # noqa: E501
and isinstance(tablespacename, dict)
and '@' in tablespacename)):
super().__init__(tablespacename)
else:
self.tablespacename = tablespacename
self.owner = owner
self.location = location
self.options = options
class CreateTransformStmt(Node):
__slots__ = {'replace': 'bool', 'type_name': 'TypeName*', 'lang': 'char*', 'fromsql': 'ObjectWithArgs*', 'tosql': 'ObjectWithArgs*'} # noqa: E501
def __init__(self, replace=None, type_name=None, lang=None, fromsql=None, tosql=None): # pragma: no cover # noqa: E501
if ((replace is not None
and type_name is lang is fromsql is tosql is None # noqa: E501
and isinstance(replace, dict)
and '@' in replace)):
super().__init__(replace)
else:
self.replace = replace
self.type_name = type_name
self.lang = lang
self.fromsql = fromsql
self.tosql = tosql
class CreateTrigStmt(Node):
__slots__ = {'trigname': 'char*', 'relation': 'RangeVar*', 'funcname': 'List*', 'args': 'List*', 'row': 'bool', 'timing': 'int16', 'events': 'int16', 'columns': 'List*', 'whenClause': 'Node*', 'isconstraint': 'bool', 'transitionRels': 'List*', 'deferrable': 'bool', 'initdeferred': 'bool', 'constrrel': 'RangeVar*'} # noqa: E501
def __init__(self, trigname=None, relation=None, funcname=None, args=None, row=None, timing=None, events=None, columns=None, whenClause=None, isconstraint=None, transitionRels=None, deferrable=None, initdeferred=None, constrrel=None): # pragma: no cover # noqa: E501
if ((trigname is not None
and relation is funcname is args is row is timing is events is columns is whenClause is isconstraint is transitionRels is deferrable is initdeferred is constrrel is None # noqa: E501
and isinstance(trigname, dict)
and '@' in trigname)):
super().__init__(trigname)
else:
self.trigname = trigname
self.relation = relation
self.funcname = funcname
self.args = args
self.row = row
self.timing = timing
self.events = events
self.columns = columns
self.whenClause = whenClause
self.isconstraint = isconstraint
self.transitionRels = transitionRels
self.deferrable = deferrable
self.initdeferred = initdeferred
self.constrrel = constrrel
class CreateUserMappingStmt(Node):
__slots__ = {'user': 'RoleSpec*', 'servername': 'char*', 'if_not_exists': 'bool', 'options': 'List*'} # noqa: E501
def __init__(self, user=None, servername=None, if_not_exists=None, options=None): # pragma: no cover # noqa: E501
if ((user is not None
and servername is if_not_exists is options is None # noqa: E501
and isinstance(user, dict)
and '@' in user)):
super().__init__(user)
else:
self.user = user
self.servername = servername
self.if_not_exists = if_not_exists
self.options = options
class CreatedbStmt(Node):
__slots__ = {'dbname': 'char*', 'options': 'List*'} # noqa: E501
def __init__(self, dbname=None, options=None): # pragma: no cover # noqa: E501
if ((dbname is not None
and options is None # noqa: E501
and isinstance(dbname, dict)
and '@' in dbname)):
super().__init__(dbname)
else:
self.dbname = dbname
self.options = options
class CurrentOfExpr(Expr):
__slots__ = {'cvarno': 'Index', 'cursor_name': 'char*', 'cursor_param': 'int'} # noqa: E501
def __init__(self, cvarno=None, cursor_name=None, cursor_param=None): # pragma: no cover # noqa: E501
if ((cvarno is not None
and cursor_name is cursor_param is None # noqa: E501
and isinstance(cvarno, dict)
and '@' in cvarno)):
super().__init__(cvarno)
else:
self.cvarno = cvarno
self.cursor_name = cursor_name
self.cursor_param = cursor_param
class DeallocateStmt(Node):
__slots__ = {'name': 'char*'} # noqa: E501
def __init__(self, name=None): # pragma: no cover # noqa: E501
if ((name is not None
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
class DeclareCursorStmt(Node):
__slots__ = {'portalname': 'char*', 'options': 'int', 'query': 'Node*'} # noqa: E501
def __init__(self, portalname=None, options=None, query=None): # pragma: no cover # noqa: E501
if ((portalname is not None
and options is query is None # noqa: E501
and isinstance(portalname, dict)
and '@' in portalname)):
super().__init__(portalname)
else:
self.portalname = portalname
self.options = options
self.query = query
class DefElem(Node):
__slots__ = {'defnamespace': 'char*', 'defname': 'char*', 'arg': 'Node*', 'defaction': 'DefElemAction', 'location': 'int'} # noqa: E501
def __init__(self, defnamespace=None, defname=None, arg=None, defaction=None, location=None): # pragma: no cover # noqa: E501
if ((defnamespace is not None
and defname is arg is defaction is location is None # noqa: E501
and isinstance(defnamespace, dict)
and '@' in defnamespace)):
super().__init__(defnamespace)
else:
self.defnamespace = defnamespace
self.defname = defname
self.arg = arg
self.defaction = defaction
self.location = location
class DefineStmt(Node):
__slots__ = {'kind': 'ObjectType', 'oldstyle': 'bool', 'defnames': 'List*', 'args': 'List*', 'definition': 'List*', 'if_not_exists': 'bool', 'replace': 'bool'} # noqa: E501
def __init__(self, kind=None, oldstyle=None, defnames=None, args=None, definition=None, if_not_exists=None, replace=None): # pragma: no cover # noqa: E501
if ((kind is not None
and oldstyle is defnames is args is definition is if_not_exists is replace is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.oldstyle = oldstyle
self.defnames = defnames
self.args = args
self.definition = definition
self.if_not_exists = if_not_exists
self.replace = replace
class DeleteStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'usingClause': 'List*', 'whereClause': 'Node*', 'returningList': 'List*', 'withClause': 'WithClause*'} # noqa: E501
def __init__(self, relation=None, usingClause=None, whereClause=None, returningList=None, withClause=None): # pragma: no cover # noqa: E501
if ((relation is not None
and usingClause is whereClause is returningList is withClause is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.usingClause = usingClause
self.whereClause = whereClause
self.returningList = returningList
self.withClause = withClause
class DiscardStmt(Node):
__slots__ = {'target': 'DiscardMode'} # noqa: E501
def __init__(self, target=None): # pragma: no cover # noqa: E501
if ((target is not None
and isinstance(target, dict)
and '@' in target)):
super().__init__(target)
else:
self.target = target
class DoStmt(Node):
__slots__ = {'args': 'List*'} # noqa: E501
def __init__(self, args=None): # pragma: no cover # noqa: E501
if ((args is not None
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
class DropOwnedStmt(Node):
__slots__ = {'roles': 'List*', 'behavior': 'DropBehavior'} # noqa: E501
def __init__(self, roles=None, behavior=None): # pragma: no cover # noqa: E501
if ((roles is not None
and behavior is None # noqa: E501
and isinstance(roles, dict)
and '@' in roles)):
super().__init__(roles)
else:
self.roles = roles
self.behavior = behavior
class DropRoleStmt(Node):
__slots__ = {'roles': 'List*', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, roles=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((roles is not None
and missing_ok is None # noqa: E501
and isinstance(roles, dict)
and '@' in roles)):
super().__init__(roles)
else:
self.roles = roles
self.missing_ok = missing_ok
class DropStmt(Node):
__slots__ = {'objects': 'List*', 'removeType': 'ObjectType', 'behavior': 'DropBehavior', 'missing_ok': 'bool', 'concurrent': 'bool'} # noqa: E501
def __init__(self, objects=None, removeType=None, behavior=None, missing_ok=None, concurrent=None): # pragma: no cover # noqa: E501
if ((objects is not None
and removeType is behavior is missing_ok is concurrent is None # noqa: E501
and isinstance(objects, dict)
and '@' in objects)):
super().__init__(objects)
else:
self.objects = objects
self.removeType = removeType
self.behavior = behavior
self.missing_ok = missing_ok
self.concurrent = concurrent
class DropSubscriptionStmt(Node):
__slots__ = {'subname': 'char*', 'missing_ok': 'bool', 'behavior': 'DropBehavior'} # noqa: E501
def __init__(self, subname=None, missing_ok=None, behavior=None): # pragma: no cover # noqa: E501
if ((subname is not None
and missing_ok is behavior is None # noqa: E501
and isinstance(subname, dict)
and '@' in subname)):
super().__init__(subname)
else:
self.subname = subname
self.missing_ok = missing_ok
self.behavior = behavior
class DropTableSpaceStmt(Node):
__slots__ = {'tablespacename': 'char*', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, tablespacename=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((tablespacename is not None
and missing_ok is None # noqa: E501
and isinstance(tablespacename, dict)
and '@' in tablespacename)):
super().__init__(tablespacename)
else:
self.tablespacename = tablespacename
self.missing_ok = missing_ok
class DropUserMappingStmt(Node):
__slots__ = {'user': 'RoleSpec*', 'servername': 'char*', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, user=None, servername=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((user is not None
and servername is missing_ok is None # noqa: E501
and isinstance(user, dict)
and '@' in user)):
super().__init__(user)
else:
self.user = user
self.servername = servername
self.missing_ok = missing_ok
class DropdbStmt(Node):
__slots__ = {'dbname': 'char*', 'missing_ok': 'bool', 'options': 'List*'} # noqa: E501
def __init__(self, dbname=None, missing_ok=None, options=None): # pragma: no cover # noqa: E501
if ((dbname is not None
and missing_ok is options is None # noqa: E501
and isinstance(dbname, dict)
and '@' in dbname)):
super().__init__(dbname)
else:
self.dbname = dbname
self.missing_ok = missing_ok
self.options = options
class ExecuteStmt(Node):
__slots__ = {'name': 'char*', 'params': 'List*'} # noqa: E501
def __init__(self, name=None, params=None): # pragma: no cover # noqa: E501
if ((name is not None
and params is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.params = params
class ExplainStmt(Node):
__slots__ = {'query': 'Node*', 'options': 'List*'} # noqa: E501
def __init__(self, query=None, options=None): # pragma: no cover # noqa: E501
if ((query is not None
and options is None # noqa: E501
and isinstance(query, dict)
and '@' in query)):
super().__init__(query)
else:
self.query = query
self.options = options
class FetchStmt(Node):
__slots__ = {'direction': 'FetchDirection', 'howMany': 'long', 'portalname': 'char*', 'ismove': 'bool'} # noqa: E501
def __init__(self, direction=None, howMany=None, portalname=None, ismove=None): # pragma: no cover # noqa: E501
if ((direction is not None
and howMany is portalname is ismove is None # noqa: E501
and isinstance(direction, dict)
and '@' in direction)):
super().__init__(direction)
else:
self.direction = direction
self.howMany = howMany
self.portalname = portalname
self.ismove = ismove
class FieldSelect(Expr):
__slots__ = {'arg': 'Expr*', 'fieldnum': 'AttrNumber', 'resulttypmod': 'int32'} # noqa: E501
def __init__(self, arg=None, fieldnum=None, resulttypmod=None): # pragma: no cover # noqa: E501
if ((arg is not None
and fieldnum is resulttypmod is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.fieldnum = fieldnum
self.resulttypmod = resulttypmod
class FieldStore(Expr):
__slots__ = {'arg': 'Expr*', 'newvals': 'List*', 'fieldnums': 'List*'} # noqa: E501
def __init__(self, arg=None, newvals=None, fieldnums=None): # pragma: no cover # noqa: E501
if ((arg is not None
and newvals is fieldnums is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.newvals = newvals
self.fieldnums = fieldnums
class FromExpr(Node):
__slots__ = {'fromlist': 'List*', 'quals': 'Node*'} # noqa: E501
def __init__(self, fromlist=None, quals=None): # pragma: no cover # noqa: E501
if ((fromlist is not None
and quals is None # noqa: E501
and isinstance(fromlist, dict)
and '@' in fromlist)):
super().__init__(fromlist)
else:
self.fromlist = fromlist
self.quals = quals
class FuncCall(Node):
__slots__ = {'funcname': 'List*', 'args': 'List*', 'agg_order': 'List*', 'agg_filter': 'Node*', 'agg_within_group': 'bool', 'agg_star': 'bool', 'agg_distinct': 'bool', 'func_variadic': 'bool', 'over': 'WindowDef*', 'location': 'int'} # noqa: E501
def __init__(self, funcname=None, args=None, agg_order=None, agg_filter=None, agg_within_group=None, agg_star=None, agg_distinct=None, func_variadic=None, over=None, location=None): # pragma: no cover # noqa: E501
if ((funcname is not None
and args is agg_order is agg_filter is agg_within_group is agg_star is agg_distinct is func_variadic is over is location is None # noqa: E501
and isinstance(funcname, dict)
and '@' in funcname)):
super().__init__(funcname)
else:
self.funcname = funcname
self.args = args
self.agg_order = agg_order
self.agg_filter = agg_filter
self.agg_within_group = agg_within_group
self.agg_star = agg_star
self.agg_distinct = agg_distinct
self.func_variadic = func_variadic
self.over = over
self.location = location
class FuncExpr(Expr):
__slots__ = {'funcretset': 'bool', 'funcvariadic': 'bool', 'funcformat': 'CoercionForm', 'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, funcretset=None, funcvariadic=None, funcformat=None, args=None, location=None): # pragma: no cover # noqa: E501
if ((funcretset is not None
and funcvariadic is funcformat is args is location is None # noqa: E501
and isinstance(funcretset, dict)
and '@' in funcretset)):
super().__init__(funcretset)
else:
self.funcretset = funcretset
self.funcvariadic = funcvariadic
self.funcformat = funcformat
self.args = args
self.location = location
class FunctionParameter(Node):
__slots__ = {'name': 'char*', 'argType': 'TypeName*', 'mode': 'FunctionParameterMode', 'defexpr': 'Node*'} # noqa: E501
def __init__(self, name=None, argType=None, mode=None, defexpr=None): # pragma: no cover # noqa: E501
if ((name is not None
and argType is mode is defexpr is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.argType = argType
self.mode = mode
self.defexpr = defexpr
class GrantRoleStmt(Node):
__slots__ = {'granted_roles': 'List*', 'grantee_roles': 'List*', 'is_grant': 'bool', 'admin_opt': 'bool', 'grantor': 'RoleSpec*', 'behavior': 'DropBehavior'} # noqa: E501
def __init__(self, granted_roles=None, grantee_roles=None, is_grant=None, admin_opt=None, grantor=None, behavior=None): # pragma: no cover # noqa: E501
if ((granted_roles is not None
and grantee_roles is is_grant is admin_opt is grantor is behavior is None # noqa: E501
and isinstance(granted_roles, dict)
and '@' in granted_roles)):
super().__init__(granted_roles)
else:
self.granted_roles = granted_roles
self.grantee_roles = grantee_roles
self.is_grant = is_grant
self.admin_opt = admin_opt
self.grantor = grantor
self.behavior = behavior
class GrantStmt(Node):
__slots__ = {'is_grant': 'bool', 'targtype': 'GrantTargetType', 'objtype': 'ObjectType', 'objects': 'List*', 'privileges': 'List*', 'grantees': 'List*', 'grant_option': 'bool', 'behavior': 'DropBehavior'} # noqa: E501
def __init__(self, is_grant=None, targtype=None, objtype=None, objects=None, privileges=None, grantees=None, grant_option=None, behavior=None): # pragma: no cover # noqa: E501
if ((is_grant is not None
and targtype is objtype is objects is privileges is grantees is grant_option is behavior is None # noqa: E501
and isinstance(is_grant, dict)
and '@' in is_grant)):
super().__init__(is_grant)
else:
self.is_grant = is_grant
self.targtype = targtype
self.objtype = objtype
self.objects = objects
self.privileges = privileges
self.grantees = grantees
self.grant_option = grant_option
self.behavior = behavior
class GroupingFunc(Expr):
__slots__ = {'args': 'List*', 'refs': 'List*', 'cols': 'List*', 'agglevelsup': 'Index', 'location': 'int'} # noqa: E501
def __init__(self, args=None, refs=None, cols=None, agglevelsup=None, location=None): # pragma: no cover # noqa: E501
if ((args is not None
and refs is cols is agglevelsup is location is None # noqa: E501
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
self.refs = refs
self.cols = cols
self.agglevelsup = agglevelsup
self.location = location
class GroupingSet(Node):
__slots__ = {'kind': 'GroupingSetKind', 'content': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, kind=None, content=None, location=None): # pragma: no cover # noqa: E501
if ((kind is not None
and content is location is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.content = content
self.location = location
class ImportForeignSchemaStmt(Node):
__slots__ = {'server_name': 'char*', 'remote_schema': 'char*', 'local_schema': 'char*', 'list_type': 'ImportForeignSchemaType', 'table_list': 'List*', 'options': 'List*'} # noqa: E501
def __init__(self, server_name=None, remote_schema=None, local_schema=None, list_type=None, table_list=None, options=None): # pragma: no cover # noqa: E501
if ((server_name is not None
and remote_schema is local_schema is list_type is table_list is options is None # noqa: E501
and isinstance(server_name, dict)
and '@' in server_name)):
super().__init__(server_name)
else:
self.server_name = server_name
self.remote_schema = remote_schema
self.local_schema = local_schema
self.list_type = list_type
self.table_list = table_list
self.options = options
class IndexElem(Node):
__slots__ = {'name': 'char*', 'expr': 'Node*', 'indexcolname': 'char*', 'collation': 'List*', 'opclass': 'List*', 'opclassopts': 'List*', 'ordering': 'SortByDir', 'nulls_ordering': 'SortByNulls'} # noqa: E501
def __init__(self, name=None, expr=None, indexcolname=None, collation=None, opclass=None, opclassopts=None, ordering=None, nulls_ordering=None): # pragma: no cover # noqa: E501
if ((name is not None
and expr is indexcolname is collation is opclass is opclassopts is ordering is nulls_ordering is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.expr = expr
self.indexcolname = indexcolname
self.collation = collation
self.opclass = opclass
self.opclassopts = opclassopts
self.ordering = ordering
self.nulls_ordering = nulls_ordering
class IndexStmt(Node):
__slots__ = {'idxname': 'char*', 'relation': 'RangeVar*', 'accessMethod': 'char*', 'tableSpace': 'char*', 'indexParams': 'List*', 'indexIncludingParams': 'List*', 'options': 'List*', 'whereClause': 'Node*', 'excludeOpNames': 'List*', 'idxcomment': 'char*', 'oldCreateSubid': 'SubTransactionId', 'oldFirstRelfilenodeSubid': 'SubTransactionId', 'unique': 'bool', 'primary': 'bool', 'isconstraint': 'bool', 'deferrable': 'bool', 'initdeferred': 'bool', 'transformed': 'bool', 'concurrent': 'bool', 'if_not_exists': 'bool', 'reset_default_tblspc': 'bool'} # noqa: E501
def __init__(self, idxname=None, relation=None, accessMethod=None, tableSpace=None, indexParams=None, indexIncludingParams=None, options=None, whereClause=None, excludeOpNames=None, idxcomment=None, oldCreateSubid=None, oldFirstRelfilenodeSubid=None, unique=None, primary=None, isconstraint=None, deferrable=None, initdeferred=None, transformed=None, concurrent=None, if_not_exists=None, reset_default_tblspc=None): # pragma: no cover # noqa: E501
if ((idxname is not None
and relation is accessMethod is tableSpace is indexParams is indexIncludingParams is options is whereClause is excludeOpNames is idxcomment is oldCreateSubid is oldFirstRelfilenodeSubid is unique is primary is isconstraint is deferrable is initdeferred is transformed is concurrent is if_not_exists is reset_default_tblspc is None # noqa: E501
and isinstance(idxname, dict)
and '@' in idxname)):
super().__init__(idxname)
else:
self.idxname = idxname
self.relation = relation
self.accessMethod = accessMethod
self.tableSpace = tableSpace
self.indexParams = indexParams
self.indexIncludingParams = indexIncludingParams
self.options = options
self.whereClause = whereClause
self.excludeOpNames = excludeOpNames
self.idxcomment = idxcomment
self.oldCreateSubid = oldCreateSubid
self.oldFirstRelfilenodeSubid = oldFirstRelfilenodeSubid
self.unique = unique
self.primary = primary
self.isconstraint = isconstraint
self.deferrable = deferrable
self.initdeferred = initdeferred
self.transformed = transformed
self.concurrent = concurrent
self.if_not_exists = if_not_exists
self.reset_default_tblspc = reset_default_tblspc
class InferClause(Node):
__slots__ = {'indexElems': 'List*', 'whereClause': 'Node*', 'conname': 'char*', 'location': 'int'} # noqa: E501
def __init__(self, indexElems=None, whereClause=None, conname=None, location=None): # pragma: no cover # noqa: E501
if ((indexElems is not None
and whereClause is conname is location is None # noqa: E501
and isinstance(indexElems, dict)
and '@' in indexElems)):
super().__init__(indexElems)
else:
self.indexElems = indexElems
self.whereClause = whereClause
self.conname = conname
self.location = location
class InferenceElem(Expr):
__slots__ = {'expr': 'Node*'} # noqa: E501
def __init__(self, expr=None): # pragma: no cover # noqa: E501
if ((expr is not None
and isinstance(expr, dict)
and '@' in expr)):
super().__init__(expr)
else:
self.expr = expr
class InlineCodeBlock(Node):
__slots__ = {'source_text': 'char*', 'langIsTrusted': 'bool', 'atomic': 'bool'} # noqa: E501
def __init__(self, source_text=None, langIsTrusted=None, atomic=None): # pragma: no cover # noqa: E501
if ((source_text is not None
and langIsTrusted is atomic is None # noqa: E501
and isinstance(source_text, dict)
and '@' in source_text)):
super().__init__(source_text)
else:
self.source_text = source_text
self.langIsTrusted = langIsTrusted
self.atomic = atomic
class InsertStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'cols': 'List*', 'selectStmt': 'Node*', 'onConflictClause': 'OnConflictClause*', 'returningList': 'List*', 'withClause': 'WithClause*', 'override': 'OverridingKind'} # noqa: E501
def __init__(self, relation=None, cols=None, selectStmt=None, onConflictClause=None, returningList=None, withClause=None, override=None): # pragma: no cover # noqa: E501
if ((relation is not None
and cols is selectStmt is onConflictClause is returningList is withClause is override is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.cols = cols
self.selectStmt = selectStmt
self.onConflictClause = onConflictClause
self.returningList = returningList
self.withClause = withClause
self.override = override
class IntoClause(Node):
__slots__ = {'rel': 'RangeVar*', 'colNames': 'List*', 'accessMethod': 'char*', 'options': 'List*', 'onCommit': 'OnCommitAction', 'tableSpaceName': 'char*', 'viewQuery': 'Node*', 'skipData': 'bool'} # noqa: E501
def __init__(self, rel=None, colNames=None, accessMethod=None, options=None, onCommit=None, tableSpaceName=None, viewQuery=None, skipData=None): # pragma: no cover # noqa: E501
if ((rel is not None
and colNames is accessMethod is options is onCommit is tableSpaceName is viewQuery is skipData is None # noqa: E501
and isinstance(rel, dict)
and '@' in rel)):
super().__init__(rel)
else:
self.rel = rel
self.colNames = colNames
self.accessMethod = accessMethod
self.options = options
self.onCommit = onCommit
self.tableSpaceName = tableSpaceName
self.viewQuery = viewQuery
self.skipData = skipData
class JoinExpr(Node):
__slots__ = {'jointype': 'JoinType', 'isNatural': 'bool', 'larg': 'Node*', 'rarg': 'Node*', 'usingClause': 'List*', 'quals': 'Node*', 'alias': 'Alias*', 'rtindex': 'int'} # noqa: E501
def __init__(self, jointype=None, isNatural=None, larg=None, rarg=None, usingClause=None, quals=None, alias=None, rtindex=None): # pragma: no cover # noqa: E501
if ((jointype is not None
and isNatural is larg is rarg is usingClause is quals is alias is rtindex is None # noqa: E501
and isinstance(jointype, dict)
and '@' in jointype)):
super().__init__(jointype)
else:
self.jointype = jointype
self.isNatural = isNatural
self.larg = larg
self.rarg = rarg
self.usingClause = usingClause
self.quals = quals
self.alias = alias
self.rtindex = rtindex
class ListenStmt(Node):
__slots__ = {'conditionname': 'char*'} # noqa: E501
def __init__(self, conditionname=None): # pragma: no cover # noqa: E501
if ((conditionname is not None
and isinstance(conditionname, dict)
and '@' in conditionname)):
super().__init__(conditionname)
else:
self.conditionname = conditionname
class LoadStmt(Node):
__slots__ = {'filename': 'char*'} # noqa: E501
def __init__(self, filename=None): # pragma: no cover # noqa: E501
if ((filename is not None
and isinstance(filename, dict)
and '@' in filename)):
super().__init__(filename)
else:
self.filename = filename
class LockStmt(Node):
__slots__ = {'relations': 'List*', 'mode': 'int', 'nowait': 'bool'} # noqa: E501
def __init__(self, relations=None, mode=None, nowait=None): # pragma: no cover # noqa: E501
if ((relations is not None
and mode is nowait is None # noqa: E501
and isinstance(relations, dict)
and '@' in relations)):
super().__init__(relations)
else:
self.relations = relations
self.mode = mode
self.nowait = nowait
class LockingClause(Node):
__slots__ = {'lockedRels': 'List*', 'strength': 'LockClauseStrength', 'waitPolicy': 'LockWaitPolicy'} # noqa: E501
def __init__(self, lockedRels=None, strength=None, waitPolicy=None): # pragma: no cover # noqa: E501
if ((lockedRels is not None
and strength is waitPolicy is None # noqa: E501
and isinstance(lockedRels, dict)
and '@' in lockedRels)):
super().__init__(lockedRels)
else:
self.lockedRels = lockedRels
self.strength = strength
self.waitPolicy = waitPolicy
class MinMaxExpr(Expr):
__slots__ = {'op': 'MinMaxOp', 'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, op=None, args=None, location=None): # pragma: no cover # noqa: E501
if ((op is not None
and args is location is None # noqa: E501
and isinstance(op, dict)
and '@' in op)):
super().__init__(op)
else:
self.op = op
self.args = args
self.location = location
class MultiAssignRef(Node):
__slots__ = {'source': 'Node*', 'colno': 'int', 'ncolumns': 'int'} # noqa: E501
def __init__(self, source=None, colno=None, ncolumns=None): # pragma: no cover # noqa: E501
if ((source is not None
and colno is ncolumns is None # noqa: E501
and isinstance(source, dict)
and '@' in source)):
super().__init__(source)
else:
self.source = source
self.colno = colno
self.ncolumns = ncolumns
class NamedArgExpr(Expr):
__slots__ = {'arg': 'Expr*', 'name': 'char*', 'argnumber': 'int', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, name=None, argnumber=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and name is argnumber is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.name = name
self.argnumber = argnumber
self.location = location
class NotifyStmt(Node):
__slots__ = {'conditionname': 'char*', 'payload': 'char*'} # noqa: E501
def __init__(self, conditionname=None, payload=None): # pragma: no cover # noqa: E501
if ((conditionname is not None
and payload is None # noqa: E501
and isinstance(conditionname, dict)
and '@' in conditionname)):
super().__init__(conditionname)
else:
self.conditionname = conditionname
self.payload = payload
class NullTest(Expr):
__slots__ = {'arg': 'Expr*', 'nulltesttype': 'NullTestType', 'argisrow': 'bool', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, nulltesttype=None, argisrow=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and nulltesttype is argisrow is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.nulltesttype = nulltesttype
self.argisrow = argisrow
self.location = location
class ObjectWithArgs(Node):
__slots__ = {'objname': 'List*', 'objargs': 'List*', 'args_unspecified': 'bool'} # noqa: E501
def __init__(self, objname=None, objargs=None, args_unspecified=None): # pragma: no cover # noqa: E501
if ((objname is not None
and objargs is args_unspecified is None # noqa: E501
and isinstance(objname, dict)
and '@' in objname)):
super().__init__(objname)
else:
self.objname = objname
self.objargs = objargs
self.args_unspecified = args_unspecified
class OnConflictClause(Node):
__slots__ = {'action': 'OnConflictAction', 'infer': 'InferClause*', 'targetList': 'List*', 'whereClause': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, action=None, infer=None, targetList=None, whereClause=None, location=None): # pragma: no cover # noqa: E501
if ((action is not None
and infer is targetList is whereClause is location is None # noqa: E501
and isinstance(action, dict)
and '@' in action)):
super().__init__(action)
else:
self.action = action
self.infer = infer
self.targetList = targetList
self.whereClause = whereClause
self.location = location
class OnConflictExpr(Node):
__slots__ = {'action': 'OnConflictAction', 'arbiterElems': 'List*', 'arbiterWhere': 'Node*', 'onConflictSet': 'List*', 'onConflictWhere': 'Node*', 'exclRelIndex': 'int', 'exclRelTlist': 'List*'} # noqa: E501
def __init__(self, action=None, arbiterElems=None, arbiterWhere=None, onConflictSet=None, onConflictWhere=None, exclRelIndex=None, exclRelTlist=None): # pragma: no cover # noqa: E501
if ((action is not None
and arbiterElems is arbiterWhere is onConflictSet is onConflictWhere is exclRelIndex is exclRelTlist is None # noqa: E501
and isinstance(action, dict)
and '@' in action)):
super().__init__(action)
else:
self.action = action
self.arbiterElems = arbiterElems
self.arbiterWhere = arbiterWhere
self.onConflictSet = onConflictSet
self.onConflictWhere = onConflictWhere
self.exclRelIndex = exclRelIndex
self.exclRelTlist = exclRelTlist
class OpExpr(Expr):
__slots__ = {'opretset': 'bool', 'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, opretset=None, args=None, location=None): # pragma: no cover # noqa: E501
if ((opretset is not None
and args is location is None # noqa: E501
and isinstance(opretset, dict)
and '@' in opretset)):
super().__init__(opretset)
else:
self.opretset = opretset
self.args = args
self.location = location
class Param(Expr):
__slots__ = {'paramkind': 'ParamKind', 'paramid': 'int', 'paramtypmod': 'int32', 'location': 'int'} # noqa: E501
def __init__(self, paramkind=None, paramid=None, paramtypmod=None, location=None): # pragma: no cover # noqa: E501
if ((paramkind is not None
and paramid is paramtypmod is location is None # noqa: E501
and isinstance(paramkind, dict)
and '@' in paramkind)):
super().__init__(paramkind)
else:
self.paramkind = paramkind
self.paramid = paramid
self.paramtypmod = paramtypmod
self.location = location
class ParamRef(Node):
__slots__ = {'number': 'int', 'location': 'int'} # noqa: E501
def __init__(self, number=None, location=None): # pragma: no cover # noqa: E501
if ((number is not None
and location is None # noqa: E501
and isinstance(number, dict)
and '@' in number)):
super().__init__(number)
else:
self.number = number
self.location = location
class PartitionBoundSpec(Node):
__slots__ = {'strategy': 'char', 'is_default': 'bool', 'modulus': 'int', 'remainder': 'int', 'listdatums': 'List*', 'lowerdatums': 'List*', 'upperdatums': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, strategy=None, is_default=None, modulus=None, remainder=None, listdatums=None, lowerdatums=None, upperdatums=None, location=None): # pragma: no cover # noqa: E501
if ((strategy is not None
and is_default is modulus is remainder is listdatums is lowerdatums is upperdatums is location is None # noqa: E501
and isinstance(strategy, dict)
and '@' in strategy)):
super().__init__(strategy)
else:
self.strategy = strategy
self.is_default = is_default
self.modulus = modulus
self.remainder = remainder
self.listdatums = listdatums
self.lowerdatums = lowerdatums
self.upperdatums = upperdatums
self.location = location
class PartitionCmd(Node):
__slots__ = {'name': 'RangeVar*', 'bound': 'PartitionBoundSpec*'} # noqa: E501
def __init__(self, name=None, bound=None): # pragma: no cover # noqa: E501
if ((name is not None
and bound is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.bound = bound
class PartitionElem(Node):
__slots__ = {'name': 'char*', 'expr': 'Node*', 'collation': 'List*', 'opclass': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, name=None, expr=None, collation=None, opclass=None, location=None): # pragma: no cover # noqa: E501
if ((name is not None
and expr is collation is opclass is location is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.expr = expr
self.collation = collation
self.opclass = opclass
self.location = location
class PartitionRangeDatum(Node):
__slots__ = {'kind': 'PartitionRangeDatumKind', 'value': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, kind=None, value=None, location=None): # pragma: no cover # noqa: E501
if ((kind is not None
and value is location is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.value = value
self.location = location
class PartitionSpec(Node):
__slots__ = {'strategy': 'char*', 'partParams': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, strategy=None, partParams=None, location=None): # pragma: no cover # noqa: E501
if ((strategy is not None
and partParams is location is None # noqa: E501
and isinstance(strategy, dict)
and '@' in strategy)):
super().__init__(strategy)
else:
self.strategy = strategy
self.partParams = partParams
self.location = location
class PrepareStmt(Node):
__slots__ = {'name': 'char*', 'argtypes': 'List*', 'query': 'Node*'} # noqa: E501
def __init__(self, name=None, argtypes=None, query=None): # pragma: no cover # noqa: E501
if ((name is not None
and argtypes is query is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.argtypes = argtypes
self.query = query
class Query(Node):
__slots__ = {'commandType': 'CmdType', 'querySource': 'QuerySource', 'queryId': 'uint64', 'canSetTag': 'bool', 'utilityStmt': 'Node*', 'resultRelation': 'int', 'hasAggs': 'bool', 'hasWindowFuncs': 'bool', 'hasTargetSRFs': 'bool', 'hasSubLinks': 'bool', 'hasDistinctOn': 'bool', 'hasRecursive': 'bool', 'hasModifyingCTE': 'bool', 'hasForUpdate': 'bool', 'hasRowSecurity': 'bool', 'cteList': 'List*', 'rtable': 'List*', 'jointree': 'FromExpr*', 'targetList': 'List*', 'override': 'OverridingKind', 'onConflict': 'OnConflictExpr*', 'returningList': 'List*', 'groupClause': 'List*', 'groupingSets': 'List*', 'havingQual': 'Node*', 'windowClause': 'List*', 'distinctClause': 'List*', 'sortClause': 'List*', 'limitOffset': 'Node*', 'limitCount': 'Node*', 'limitOption': 'LimitOption', 'rowMarks': 'List*', 'setOperations': 'Node*', 'constraintDeps': 'List*', 'withCheckOptions': 'List*', 'stmt_location': 'int', 'stmt_len': 'int'} # noqa: E501
def __init__(self, commandType=None, querySource=None, queryId=None, canSetTag=None, utilityStmt=None, resultRelation=None, hasAggs=None, hasWindowFuncs=None, hasTargetSRFs=None, hasSubLinks=None, hasDistinctOn=None, hasRecursive=None, hasModifyingCTE=None, hasForUpdate=None, hasRowSecurity=None, cteList=None, rtable=None, jointree=None, targetList=None, override=None, onConflict=None, returningList=None, groupClause=None, groupingSets=None, havingQual=None, windowClause=None, distinctClause=None, sortClause=None, limitOffset=None, limitCount=None, limitOption=None, rowMarks=None, setOperations=None, constraintDeps=None, withCheckOptions=None, stmt_location=None, stmt_len=None): # pragma: no cover # noqa: E501
if ((commandType is not None
and querySource is queryId is canSetTag is utilityStmt is resultRelation is hasAggs is hasWindowFuncs is hasTargetSRFs is hasSubLinks is hasDistinctOn is hasRecursive is hasModifyingCTE is hasForUpdate is hasRowSecurity is cteList is rtable is jointree is targetList is override is onConflict is returningList is groupClause is groupingSets is havingQual is windowClause is distinctClause is sortClause is limitOffset is limitCount is limitOption is rowMarks is setOperations is constraintDeps is withCheckOptions is stmt_location is stmt_len is None # noqa: E501
and isinstance(commandType, dict)
and '@' in commandType)):
super().__init__(commandType)
else:
self.commandType = commandType
self.querySource = querySource
self.queryId = queryId
self.canSetTag = canSetTag
self.utilityStmt = utilityStmt
self.resultRelation = resultRelation
self.hasAggs = hasAggs
self.hasWindowFuncs = hasWindowFuncs
self.hasTargetSRFs = hasTargetSRFs
self.hasSubLinks = hasSubLinks
self.hasDistinctOn = hasDistinctOn
self.hasRecursive = hasRecursive
self.hasModifyingCTE = hasModifyingCTE
self.hasForUpdate = hasForUpdate
self.hasRowSecurity = hasRowSecurity
self.cteList = cteList
self.rtable = rtable
self.jointree = jointree
self.targetList = targetList
self.override = override
self.onConflict = onConflict
self.returningList = returningList
self.groupClause = groupClause
self.groupingSets = groupingSets
self.havingQual = havingQual
self.windowClause = windowClause
self.distinctClause = distinctClause
self.sortClause = sortClause
self.limitOffset = limitOffset
self.limitCount = limitCount
self.limitOption = limitOption
self.rowMarks = rowMarks
self.setOperations = setOperations
self.constraintDeps = constraintDeps
self.withCheckOptions = withCheckOptions
self.stmt_location = stmt_location
self.stmt_len = stmt_len
class RangeFunction(Node):
__slots__ = {'lateral': 'bool', 'ordinality': 'bool', 'is_rowsfrom': 'bool', 'functions': 'List*', 'alias': 'Alias*', 'coldeflist': 'List*'} # noqa: E501
def __init__(self, lateral=None, ordinality=None, is_rowsfrom=None, functions=None, alias=None, coldeflist=None): # pragma: no cover # noqa: E501
if ((lateral is not None
and ordinality is is_rowsfrom is functions is alias is coldeflist is None # noqa: E501
and isinstance(lateral, dict)
and '@' in lateral)):
super().__init__(lateral)
else:
self.lateral = lateral
self.ordinality = ordinality
self.is_rowsfrom = is_rowsfrom
self.functions = functions
self.alias = alias
self.coldeflist = coldeflist
class RangeSubselect(Node):
__slots__ = {'lateral': 'bool', 'subquery': 'Node*', 'alias': 'Alias*'} # noqa: E501
def __init__(self, lateral=None, subquery=None, alias=None): # pragma: no cover # noqa: E501
if ((lateral is not None
and subquery is alias is None # noqa: E501
and isinstance(lateral, dict)
and '@' in lateral)):
super().__init__(lateral)
else:
self.lateral = lateral
self.subquery = subquery
self.alias = alias
class RangeTableFunc(Node):
__slots__ = {'lateral': 'bool', 'docexpr': 'Node*', 'rowexpr': 'Node*', 'namespaces': 'List*', 'columns': 'List*', 'alias': 'Alias*', 'location': 'int'} # noqa: E501
def __init__(self, lateral=None, docexpr=None, rowexpr=None, namespaces=None, columns=None, alias=None, location=None): # pragma: no cover # noqa: E501
if ((lateral is not None
and docexpr is rowexpr is namespaces is columns is alias is location is None # noqa: E501
and isinstance(lateral, dict)
and '@' in lateral)):
super().__init__(lateral)
else:
self.lateral = lateral
self.docexpr = docexpr
self.rowexpr = rowexpr
self.namespaces = namespaces
self.columns = columns
self.alias = alias
self.location = location
class RangeTableFuncCol(Node):
__slots__ = {'colname': 'char*', 'typeName': 'TypeName*', 'for_ordinality': 'bool', 'is_not_null': 'bool', 'colexpr': 'Node*', 'coldefexpr': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, colname=None, typeName=None, for_ordinality=None, is_not_null=None, colexpr=None, coldefexpr=None, location=None): # pragma: no cover # noqa: E501
if ((colname is not None
and typeName is for_ordinality is is_not_null is colexpr is coldefexpr is location is None # noqa: E501
and isinstance(colname, dict)
and '@' in colname)):
super().__init__(colname)
else:
self.colname = colname
self.typeName = typeName
self.for_ordinality = for_ordinality
self.is_not_null = is_not_null
self.colexpr = colexpr
self.coldefexpr = coldefexpr
self.location = location
class RangeTableSample(Node):
__slots__ = {'relation': 'Node*', 'method': 'List*', 'args': 'List*', 'repeatable': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, relation=None, method=None, args=None, repeatable=None, location=None): # pragma: no cover # noqa: E501
if ((relation is not None
and method is args is repeatable is location is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.method = method
self.args = args
self.repeatable = repeatable
self.location = location
class RangeTblEntry(Node):
__slots__ = {'rtekind': 'RTEKind', 'relkind': 'char', 'rellockmode': 'int', 'tablesample': 'TableSampleClause*', 'subquery': 'Query*', 'security_barrier': 'bool', 'jointype': 'JoinType', 'joinmergedcols': 'int', 'joinaliasvars': 'List*', 'joinleftcols': 'List*', 'joinrightcols': 'List*', 'functions': 'List*', 'funcordinality': 'bool', 'tablefunc': 'TableFunc*', 'values_lists': 'List*', 'ctename': 'char*', 'ctelevelsup': 'Index', 'self_reference': 'bool', 'coltypes': 'List*', 'coltypmods': 'List*', 'colcollations': 'List*', 'enrname': 'char*', 'enrtuples': 'double', 'alias': 'Alias*', 'eref': 'Alias*', 'lateral': 'bool', 'inh': 'bool', 'inFromCl': 'bool', 'requiredPerms': 'AclMode', 'selectedCols': 'Bitmapset*', 'insertedCols': 'Bitmapset*', 'updatedCols': 'Bitmapset*', 'extraUpdatedCols': 'Bitmapset*', 'securityQuals': 'List*'} # noqa: E501
def __init__(self, rtekind=None, relkind=None, rellockmode=None, tablesample=None, subquery=None, security_barrier=None, jointype=None, joinmergedcols=None, joinaliasvars=None, joinleftcols=None, joinrightcols=None, functions=None, funcordinality=None, tablefunc=None, values_lists=None, ctename=None, ctelevelsup=None, self_reference=None, coltypes=None, coltypmods=None, colcollations=None, enrname=None, enrtuples=None, alias=None, eref=None, lateral=None, inh=None, inFromCl=None, requiredPerms=None, selectedCols=None, insertedCols=None, updatedCols=None, extraUpdatedCols=None, securityQuals=None): # pragma: no cover # noqa: E501
if ((rtekind is not None
and relkind is rellockmode is tablesample is subquery is security_barrier is jointype is joinmergedcols is joinaliasvars is joinleftcols is joinrightcols is functions is funcordinality is tablefunc is values_lists is ctename is ctelevelsup is self_reference is coltypes is coltypmods is colcollations is enrname is enrtuples is alias is eref is lateral is inh is inFromCl is requiredPerms is selectedCols is insertedCols is updatedCols is extraUpdatedCols is securityQuals is None # noqa: E501
and isinstance(rtekind, dict)
and '@' in rtekind)):
super().__init__(rtekind)
else:
self.rtekind = rtekind
self.relkind = relkind
self.rellockmode = rellockmode
self.tablesample = tablesample
self.subquery = subquery
self.security_barrier = security_barrier
self.jointype = jointype
self.joinmergedcols = joinmergedcols
self.joinaliasvars = joinaliasvars
self.joinleftcols = joinleftcols
self.joinrightcols = joinrightcols
self.functions = functions
self.funcordinality = funcordinality
self.tablefunc = tablefunc
self.values_lists = values_lists
self.ctename = ctename
self.ctelevelsup = ctelevelsup
self.self_reference = self_reference
self.coltypes = coltypes
self.coltypmods = coltypmods
self.colcollations = colcollations
self.enrname = enrname
self.enrtuples = enrtuples
self.alias = alias
self.eref = eref
self.lateral = lateral
self.inh = inh
self.inFromCl = inFromCl
self.requiredPerms = requiredPerms
self.selectedCols = selectedCols
self.insertedCols = insertedCols
self.updatedCols = updatedCols
self.extraUpdatedCols = extraUpdatedCols
self.securityQuals = securityQuals
class RangeTblFunction(Node):
__slots__ = {'funcexpr': 'Node*', 'funccolcount': 'int', 'funccolnames': 'List*', 'funccoltypes': 'List*', 'funccoltypmods': 'List*', 'funccolcollations': 'List*', 'funcparams': 'Bitmapset*'} # noqa: E501
def __init__(self, funcexpr=None, funccolcount=None, funccolnames=None, funccoltypes=None, funccoltypmods=None, funccolcollations=None, funcparams=None): # pragma: no cover # noqa: E501
if ((funcexpr is not None
and funccolcount is funccolnames is funccoltypes is funccoltypmods is funccolcollations is funcparams is None # noqa: E501
and isinstance(funcexpr, dict)
and '@' in funcexpr)):
super().__init__(funcexpr)
else:
self.funcexpr = funcexpr
self.funccolcount = funccolcount
self.funccolnames = funccolnames
self.funccoltypes = funccoltypes
self.funccoltypmods = funccoltypmods
self.funccolcollations = funccolcollations
self.funcparams = funcparams
class RangeTblRef(Node):
__slots__ = {'rtindex': 'int'} # noqa: E501
def __init__(self, rtindex=None): # pragma: no cover # noqa: E501
if ((rtindex is not None
and isinstance(rtindex, dict)
and '@' in rtindex)):
super().__init__(rtindex)
else:
self.rtindex = rtindex
class RangeVar(Node):
__slots__ = {'catalogname': 'char*', 'schemaname': 'char*', 'relname': 'char*', 'inh': 'bool', 'relpersistence': 'char', 'alias': 'Alias*', 'location': 'int'} # noqa: E501
def __init__(self, catalogname=None, schemaname=None, relname=None, inh=None, relpersistence=None, alias=None, location=None): # pragma: no cover # noqa: E501
if ((catalogname is not None
and schemaname is relname is inh is relpersistence is alias is location is None # noqa: E501
and isinstance(catalogname, dict)
and '@' in catalogname)):
super().__init__(catalogname)
else:
self.catalogname = catalogname
self.schemaname = schemaname
self.relname = relname
self.inh = inh
self.relpersistence = relpersistence
self.alias = alias
self.location = location
class RawStmt(Node):
__slots__ = {'stmt': 'Node*', 'stmt_location': 'int', 'stmt_len': 'int'} # noqa: E501
def __init__(self, stmt=None, stmt_location=None, stmt_len=None): # pragma: no cover # noqa: E501
if ((stmt is not None
and stmt_location is stmt_len is None # noqa: E501
and isinstance(stmt, dict)
and '@' in stmt)):
super().__init__(stmt)
else:
self.stmt = stmt
self.stmt_location = stmt_location
self.stmt_len = stmt_len
class ReassignOwnedStmt(Node):
__slots__ = {'roles': 'List*', 'newrole': 'RoleSpec*'} # noqa: E501
def __init__(self, roles=None, newrole=None): # pragma: no cover # noqa: E501
if ((roles is not None
and newrole is None # noqa: E501
and isinstance(roles, dict)
and '@' in roles)):
super().__init__(roles)
else:
self.roles = roles
self.newrole = newrole
class RefreshMatViewStmt(Node):
__slots__ = {'concurrent': 'bool', 'skipData': 'bool', 'relation': 'RangeVar*'} # noqa: E501
def __init__(self, concurrent=None, skipData=None, relation=None): # pragma: no cover # noqa: E501
if ((concurrent is not None
and skipData is relation is None # noqa: E501
and isinstance(concurrent, dict)
and '@' in concurrent)):
super().__init__(concurrent)
else:
self.concurrent = concurrent
self.skipData = skipData
self.relation = relation
class ReindexStmt(Node):
__slots__ = {'kind': 'ReindexObjectType', 'relation': 'RangeVar*', 'name': 'char*', 'options': 'int', 'concurrent': 'bool'} # noqa: E501
def __init__(self, kind=None, relation=None, name=None, options=None, concurrent=None): # pragma: no cover # noqa: E501
if ((kind is not None
and relation is name is options is concurrent is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.relation = relation
self.name = name
self.options = options
self.concurrent = concurrent
class RelabelType(Expr):
__slots__ = {'arg': 'Expr*', 'resulttypmod': 'int32', 'relabelformat': 'CoercionForm', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, resulttypmod=None, relabelformat=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and resulttypmod is relabelformat is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.resulttypmod = resulttypmod
self.relabelformat = relabelformat
self.location = location
class RenameStmt(Node):
__slots__ = {'renameType': 'ObjectType', 'relationType': 'ObjectType', 'relation': 'RangeVar*', 'object': 'Node*', 'subname': 'char*', 'newname': 'char*', 'behavior': 'DropBehavior', 'missing_ok': 'bool'} # noqa: E501
def __init__(self, renameType=None, relationType=None, relation=None, object=None, subname=None, newname=None, behavior=None, missing_ok=None): # pragma: no cover # noqa: E501
if ((renameType is not None
and relationType is relation is object is subname is newname is behavior is missing_ok is None # noqa: E501
and isinstance(renameType, dict)
and '@' in renameType)):
super().__init__(renameType)
else:
self.renameType = renameType
self.relationType = relationType
self.relation = relation
self.object = object
self.subname = subname
self.newname = newname
self.behavior = behavior
self.missing_ok = missing_ok
class ReplicaIdentityStmt(Node):
__slots__ = {'identity_type': 'char', 'name': 'char*'} # noqa: E501
def __init__(self, identity_type=None, name=None): # pragma: no cover # noqa: E501
if ((identity_type is not None
and name is None # noqa: E501
and isinstance(identity_type, dict)
and '@' in identity_type)):
super().__init__(identity_type)
else:
self.identity_type = identity_type
self.name = name
class ResTarget(Node):
__slots__ = {'name': 'char*', 'indirection': 'List*', 'val': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, name=None, indirection=None, val=None, location=None): # pragma: no cover # noqa: E501
if ((name is not None
and indirection is val is location is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.indirection = indirection
self.val = val
self.location = location
class RoleSpec(Node):
__slots__ = {'roletype': 'RoleSpecType', 'rolename': 'char*', 'location': 'int'} # noqa: E501
def __init__(self, roletype=None, rolename=None, location=None): # pragma: no cover # noqa: E501
if ((roletype is not None
and rolename is location is None # noqa: E501
and isinstance(roletype, dict)
and '@' in roletype)):
super().__init__(roletype)
else:
self.roletype = roletype
self.rolename = rolename
self.location = location
class RowCompareExpr(Expr):
__slots__ = {'rctype': 'RowCompareType', 'opnos': 'List*', 'opfamilies': 'List*', 'inputcollids': 'List*', 'largs': 'List*', 'rargs': 'List*'} # noqa: E501
def __init__(self, rctype=None, opnos=None, opfamilies=None, inputcollids=None, largs=None, rargs=None): # pragma: no cover # noqa: E501
if ((rctype is not None
and opnos is opfamilies is inputcollids is largs is rargs is None # noqa: E501
and isinstance(rctype, dict)
and '@' in rctype)):
super().__init__(rctype)
else:
self.rctype = rctype
self.opnos = opnos
self.opfamilies = opfamilies
self.inputcollids = inputcollids
self.largs = largs
self.rargs = rargs
class RowExpr(Expr):
__slots__ = {'args': 'List*', 'row_format': 'CoercionForm', 'colnames': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, args=None, row_format=None, colnames=None, location=None): # pragma: no cover # noqa: E501
if ((args is not None
and row_format is colnames is location is None # noqa: E501
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
self.row_format = row_format
self.colnames = colnames
self.location = location
class RowMarkClause(Node):
__slots__ = {'rti': 'Index', 'strength': 'LockClauseStrength', 'waitPolicy': 'LockWaitPolicy', 'pushedDown': 'bool'} # noqa: E501
def __init__(self, rti=None, strength=None, waitPolicy=None, pushedDown=None): # pragma: no cover # noqa: E501
if ((rti is not None
and strength is waitPolicy is pushedDown is None # noqa: E501
and isinstance(rti, dict)
and '@' in rti)):
super().__init__(rti)
else:
self.rti = rti
self.strength = strength
self.waitPolicy = waitPolicy
self.pushedDown = pushedDown
class RuleStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'rulename': 'char*', 'whereClause': 'Node*', 'event': 'CmdType', 'instead': 'bool', 'actions': 'List*', 'replace': 'bool'} # noqa: E501
def __init__(self, relation=None, rulename=None, whereClause=None, event=None, instead=None, actions=None, replace=None): # pragma: no cover # noqa: E501
if ((relation is not None
and rulename is whereClause is event is instead is actions is replace is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.rulename = rulename
self.whereClause = whereClause
self.event = event
self.instead = instead
self.actions = actions
self.replace = replace
class SQLValueFunction(Expr):
__slots__ = {'op': 'SQLValueFunctionOp', 'typmod': 'int32', 'location': 'int'} # noqa: E501
def __init__(self, op=None, typmod=None, location=None): # pragma: no cover # noqa: E501
if ((op is not None
and typmod is location is None # noqa: E501
and isinstance(op, dict)
and '@' in op)):
super().__init__(op)
else:
self.op = op
self.typmod = typmod
self.location = location
class ScalarArrayOpExpr(Expr):
__slots__ = {'useOr': 'bool', 'args': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, useOr=None, args=None, location=None): # pragma: no cover # noqa: E501
if ((useOr is not None
and args is location is None # noqa: E501
and isinstance(useOr, dict)
and '@' in useOr)):
super().__init__(useOr)
else:
self.useOr = useOr
self.args = args
self.location = location
class SecLabelStmt(Node):
__slots__ = {'objtype': 'ObjectType', 'object': 'Node*', 'provider': 'char*', 'label': 'char*'} # noqa: E501
def __init__(self, objtype=None, object=None, provider=None, label=None): # pragma: no cover # noqa: E501
if ((objtype is not None
and object is provider is label is None # noqa: E501
and isinstance(objtype, dict)
and '@' in objtype)):
super().__init__(objtype)
else:
self.objtype = objtype
self.object = object
self.provider = provider
self.label = label
class SelectStmt(Node):
__slots__ = {'distinctClause': 'List*', 'intoClause': 'IntoClause*', 'targetList': 'List*', 'fromClause': 'List*', 'whereClause': 'Node*', 'groupClause': 'List*', 'havingClause': 'Node*', 'windowClause': 'List*', 'valuesLists': 'List*', 'sortClause': 'List*', 'limitOffset': 'Node*', 'limitCount': 'Node*', 'limitOption': 'LimitOption', 'lockingClause': 'List*', 'withClause': 'WithClause*', 'op': 'SetOperation', 'all': 'bool', 'larg': 'SelectStmt*', 'rarg': 'SelectStmt*'} # noqa: E501
def __init__(self, distinctClause=None, intoClause=None, targetList=None, fromClause=None, whereClause=None, groupClause=None, havingClause=None, windowClause=None, valuesLists=None, sortClause=None, limitOffset=None, limitCount=None, limitOption=None, lockingClause=None, withClause=None, op=None, all=None, larg=None, rarg=None): # pragma: no cover # noqa: E501
if ((distinctClause is not None
and intoClause is targetList is fromClause is whereClause is groupClause is havingClause is windowClause is valuesLists is sortClause is limitOffset is limitCount is limitOption is lockingClause is withClause is op is all is larg is rarg is None # noqa: E501
and isinstance(distinctClause, dict)
and '@' in distinctClause)):
super().__init__(distinctClause)
else:
self.distinctClause = distinctClause
self.intoClause = intoClause
self.targetList = targetList
self.fromClause = fromClause
self.whereClause = whereClause
self.groupClause = groupClause
self.havingClause = havingClause
self.windowClause = windowClause
self.valuesLists = valuesLists
self.sortClause = sortClause
self.limitOffset = limitOffset
self.limitCount = limitCount
self.limitOption = limitOption
self.lockingClause = lockingClause
self.withClause = withClause
self.op = op
self.all = all
self.larg = larg
self.rarg = rarg
class SetOperationStmt(Node):
__slots__ = {'op': 'SetOperation', 'all': 'bool', 'larg': 'Node*', 'rarg': 'Node*', 'colTypes': 'List*', 'colTypmods': 'List*', 'colCollations': 'List*', 'groupClauses': 'List*'} # noqa: E501
def __init__(self, op=None, all=None, larg=None, rarg=None, colTypes=None, colTypmods=None, colCollations=None, groupClauses=None): # pragma: no cover # noqa: E501
if ((op is not None
and all is larg is rarg is colTypes is colTypmods is colCollations is groupClauses is None # noqa: E501
and isinstance(op, dict)
and '@' in op)):
super().__init__(op)
else:
self.op = op
self.all = all
self.larg = larg
self.rarg = rarg
self.colTypes = colTypes
self.colTypmods = colTypmods
self.colCollations = colCollations
self.groupClauses = groupClauses
class SetToDefault(Expr):
__slots__ = {'typeMod': 'int32', 'location': 'int'} # noqa: E501
def __init__(self, typeMod=None, location=None): # pragma: no cover # noqa: E501
if ((typeMod is not None
and location is None # noqa: E501
and isinstance(typeMod, dict)
and '@' in typeMod)):
super().__init__(typeMod)
else:
self.typeMod = typeMod
self.location = location
class SortBy(Node):
__slots__ = {'node': 'Node*', 'sortby_dir': 'SortByDir', 'sortby_nulls': 'SortByNulls', 'useOp': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, node=None, sortby_dir=None, sortby_nulls=None, useOp=None, location=None): # pragma: no cover # noqa: E501
if ((node is not None
and sortby_dir is sortby_nulls is useOp is location is None # noqa: E501
and isinstance(node, dict)
and '@' in node)):
super().__init__(node)
else:
self.node = node
self.sortby_dir = sortby_dir
self.sortby_nulls = sortby_nulls
self.useOp = useOp
self.location = location
class SortGroupClause(Node):
__slots__ = {'tleSortGroupRef': 'Index', 'nulls_first': 'bool', 'hashable': 'bool'} # noqa: E501
def __init__(self, tleSortGroupRef=None, nulls_first=None, hashable=None): # pragma: no cover # noqa: E501
if ((tleSortGroupRef is not None
and nulls_first is hashable is None # noqa: E501
and isinstance(tleSortGroupRef, dict)
and '@' in tleSortGroupRef)):
super().__init__(tleSortGroupRef)
else:
self.tleSortGroupRef = tleSortGroupRef
self.nulls_first = nulls_first
self.hashable = hashable
class SubLink(Expr):
__slots__ = {'subLinkType': 'SubLinkType', 'subLinkId': 'int', 'testexpr': 'Node*', 'operName': 'List*', 'subselect': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, subLinkType=None, subLinkId=None, testexpr=None, operName=None, subselect=None, location=None): # pragma: no cover # noqa: E501
if ((subLinkType is not None
and subLinkId is testexpr is operName is subselect is location is None # noqa: E501
and isinstance(subLinkType, dict)
and '@' in subLinkType)):
super().__init__(subLinkType)
else:
self.subLinkType = subLinkType
self.subLinkId = subLinkId
self.testexpr = testexpr
self.operName = operName
self.subselect = subselect
self.location = location
class SubPlan(Expr):
__slots__ = {'subLinkType': 'SubLinkType', 'testexpr': 'Node*', 'paramIds': 'List*', 'plan_id': 'int', 'plan_name': 'char*', 'firstColTypmod': 'int32', 'useHashTable': 'bool', 'unknownEqFalse': 'bool', 'parallel_safe': 'bool', 'setParam': 'List*', 'parParam': 'List*', 'args': 'List*', 'startup_cost': 'Cost', 'per_call_cost': 'Cost'} # noqa: E501
def __init__(self, subLinkType=None, testexpr=None, paramIds=None, plan_id=None, plan_name=None, firstColTypmod=None, useHashTable=None, unknownEqFalse=None, parallel_safe=None, setParam=None, parParam=None, args=None, startup_cost=None, per_call_cost=None): # pragma: no cover # noqa: E501
if ((subLinkType is not None
and testexpr is paramIds is plan_id is plan_name is firstColTypmod is useHashTable is unknownEqFalse is parallel_safe is setParam is parParam is args is startup_cost is per_call_cost is None # noqa: E501
and isinstance(subLinkType, dict)
and '@' in subLinkType)):
super().__init__(subLinkType)
else:
self.subLinkType = subLinkType
self.testexpr = testexpr
self.paramIds = paramIds
self.plan_id = plan_id
self.plan_name = plan_name
self.firstColTypmod = firstColTypmod
self.useHashTable = useHashTable
self.unknownEqFalse = unknownEqFalse
self.parallel_safe = parallel_safe
self.setParam = setParam
self.parParam = parParam
self.args = args
self.startup_cost = startup_cost
self.per_call_cost = per_call_cost
class SubscriptingRef(Expr):
__slots__ = {'reftypmod': 'int32', 'refupperindexpr': 'List*', 'reflowerindexpr': 'List*', 'refexpr': 'Expr*', 'refassgnexpr': 'Expr*'} # noqa: E501
def __init__(self, reftypmod=None, refupperindexpr=None, reflowerindexpr=None, refexpr=None, refassgnexpr=None): # pragma: no cover # noqa: E501
if ((reftypmod is not None
and refupperindexpr is reflowerindexpr is refexpr is refassgnexpr is None # noqa: E501
and isinstance(reftypmod, dict)
and '@' in reftypmod)):
super().__init__(reftypmod)
else:
self.reftypmod = reftypmod
self.refupperindexpr = refupperindexpr
self.reflowerindexpr = reflowerindexpr
self.refexpr = refexpr
self.refassgnexpr = refassgnexpr
class TableFunc(Node):
__slots__ = {'ns_uris': 'List*', 'ns_names': 'List*', 'docexpr': 'Node*', 'rowexpr': 'Node*', 'colnames': 'List*', 'coltypes': 'List*', 'coltypmods': 'List*', 'colcollations': 'List*', 'colexprs': 'List*', 'coldefexprs': 'List*', 'notnulls': 'Bitmapset*', 'ordinalitycol': 'int', 'location': 'int'} # noqa: E501
def __init__(self, ns_uris=None, ns_names=None, docexpr=None, rowexpr=None, colnames=None, coltypes=None, coltypmods=None, colcollations=None, colexprs=None, coldefexprs=None, notnulls=None, ordinalitycol=None, location=None): # pragma: no cover # noqa: E501
if ((ns_uris is not None
and ns_names is docexpr is rowexpr is colnames is coltypes is coltypmods is colcollations is colexprs is coldefexprs is notnulls is ordinalitycol is location is None # noqa: E501
and isinstance(ns_uris, dict)
and '@' in ns_uris)):
super().__init__(ns_uris)
else:
self.ns_uris = ns_uris
self.ns_names = ns_names
self.docexpr = docexpr
self.rowexpr = rowexpr
self.colnames = colnames
self.coltypes = coltypes
self.coltypmods = coltypmods
self.colcollations = colcollations
self.colexprs = colexprs
self.coldefexprs = coldefexprs
self.notnulls = notnulls
self.ordinalitycol = ordinalitycol
self.location = location
class TableLikeClause(Node):
__slots__ = {'relation': 'RangeVar*', 'options': 'bits32'} # noqa: E501
def __init__(self, relation=None, options=None): # pragma: no cover # noqa: E501
if ((relation is not None
and options is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.options = options
class TableSampleClause(Node):
__slots__ = {'args': 'List*', 'repeatable': 'Expr*'} # noqa: E501
def __init__(self, args=None, repeatable=None): # pragma: no cover # noqa: E501
if ((args is not None
and repeatable is None # noqa: E501
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
self.repeatable = repeatable
class TargetEntry(Expr):
__slots__ = {'expr': 'Expr*', 'resno': 'AttrNumber', 'resname': 'char*', 'ressortgroupref': 'Index', 'resorigcol': 'AttrNumber', 'resjunk': 'bool'} # noqa: E501
def __init__(self, expr=None, resno=None, resname=None, ressortgroupref=None, resorigcol=None, resjunk=None): # pragma: no cover # noqa: E501
if ((expr is not None
and resno is resname is ressortgroupref is resorigcol is resjunk is None # noqa: E501
and isinstance(expr, dict)
and '@' in expr)):
super().__init__(expr)
else:
self.expr = expr
self.resno = resno
self.resname = resname
self.ressortgroupref = ressortgroupref
self.resorigcol = resorigcol
self.resjunk = resjunk
class TransactionStmt(Node):
__slots__ = {'kind': 'TransactionStmtKind', 'options': 'List*', 'savepoint_name': 'char*', 'gid': 'char*', 'chain': 'bool'} # noqa: E501
def __init__(self, kind=None, options=None, savepoint_name=None, gid=None, chain=None): # pragma: no cover # noqa: E501
if ((kind is not None
and options is savepoint_name is gid is chain is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.options = options
self.savepoint_name = savepoint_name
self.gid = gid
self.chain = chain
class TriggerTransition(Node):
__slots__ = {'name': 'char*', 'isNew': 'bool', 'isTable': 'bool'} # noqa: E501
def __init__(self, name=None, isNew=None, isTable=None): # pragma: no cover # noqa: E501
if ((name is not None
and isNew is isTable is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.isNew = isNew
self.isTable = isTable
class TruncateStmt(Node):
__slots__ = {'relations': 'List*', 'restart_seqs': 'bool', 'behavior': 'DropBehavior'} # noqa: E501
def __init__(self, relations=None, restart_seqs=None, behavior=None): # pragma: no cover # noqa: E501
if ((relations is not None
and restart_seqs is behavior is None # noqa: E501
and isinstance(relations, dict)
and '@' in relations)):
super().__init__(relations)
else:
self.relations = relations
self.restart_seqs = restart_seqs
self.behavior = behavior
class TypeCast(Node):
__slots__ = {'arg': 'Node*', 'typeName': 'TypeName*', 'location': 'int'} # noqa: E501
def __init__(self, arg=None, typeName=None, location=None): # pragma: no cover # noqa: E501
if ((arg is not None
and typeName is location is None # noqa: E501
and isinstance(arg, dict)
and '@' in arg)):
super().__init__(arg)
else:
self.arg = arg
self.typeName = typeName
self.location = location
class TypeName(Node):
__slots__ = {'names': 'List*', 'setof': 'bool', 'pct_type': 'bool', 'typmods': 'List*', 'typemod': 'int32', 'arrayBounds': 'List*', 'location': 'int'} # noqa: E501
def __init__(self, names=None, setof=None, pct_type=None, typmods=None, typemod=None, arrayBounds=None, location=None): # pragma: no cover # noqa: E501
if ((names is not None
and setof is pct_type is typmods is typemod is arrayBounds is location is None # noqa: E501
and isinstance(names, dict)
and '@' in names)):
super().__init__(names)
else:
self.names = names
self.setof = setof
self.pct_type = pct_type
self.typmods = typmods
self.typemod = typemod
self.arrayBounds = arrayBounds
self.location = location
class UnlistenStmt(Node):
__slots__ = {'conditionname': 'char*'} # noqa: E501
def __init__(self, conditionname=None): # pragma: no cover # noqa: E501
if ((conditionname is not None
and isinstance(conditionname, dict)
and '@' in conditionname)):
super().__init__(conditionname)
else:
self.conditionname = conditionname
class UpdateStmt(Node):
__slots__ = {'relation': 'RangeVar*', 'targetList': 'List*', 'whereClause': 'Node*', 'fromClause': 'List*', 'returningList': 'List*', 'withClause': 'WithClause*'} # noqa: E501
def __init__(self, relation=None, targetList=None, whereClause=None, fromClause=None, returningList=None, withClause=None): # pragma: no cover # noqa: E501
if ((relation is not None
and targetList is whereClause is fromClause is returningList is withClause is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.targetList = targetList
self.whereClause = whereClause
self.fromClause = fromClause
self.returningList = returningList
self.withClause = withClause
class VacuumRelation(Node):
__slots__ = {'relation': 'RangeVar*', 'va_cols': 'List*'} # noqa: E501
def __init__(self, relation=None, va_cols=None): # pragma: no cover # noqa: E501
if ((relation is not None
and va_cols is None # noqa: E501
and isinstance(relation, dict)
and '@' in relation)):
super().__init__(relation)
else:
self.relation = relation
self.va_cols = va_cols
class VacuumStmt(Node):
__slots__ = {'options': 'List*', 'rels': 'List*', 'is_vacuumcmd': 'bool'} # noqa: E501
def __init__(self, options=None, rels=None, is_vacuumcmd=None): # pragma: no cover # noqa: E501
if ((options is not None
and rels is is_vacuumcmd is None # noqa: E501
and isinstance(options, dict)
and '@' in options)):
super().__init__(options)
else:
self.options = options
self.rels = rels
self.is_vacuumcmd = is_vacuumcmd
class Var(Expr):
__slots__ = {'varno': 'Index', 'varattno': 'AttrNumber', 'vartypmod': 'int32', 'varlevelsup': 'Index', 'varnosyn': 'Index', 'varattnosyn': 'AttrNumber', 'location': 'int'} # noqa: E501
def __init__(self, varno=None, varattno=None, vartypmod=None, varlevelsup=None, varnosyn=None, varattnosyn=None, location=None): # pragma: no cover # noqa: E501
if ((varno is not None
and varattno is vartypmod is varlevelsup is varnosyn is varattnosyn is location is None # noqa: E501
and isinstance(varno, dict)
and '@' in varno)):
super().__init__(varno)
else:
self.varno = varno
self.varattno = varattno
self.vartypmod = vartypmod
self.varlevelsup = varlevelsup
self.varnosyn = varnosyn
self.varattnosyn = varattnosyn
self.location = location
class VariableSetStmt(Node):
__slots__ = {'kind': 'VariableSetKind', 'name': 'char*', 'args': 'List*', 'is_local': 'bool'} # noqa: E501
def __init__(self, kind=None, name=None, args=None, is_local=None): # pragma: no cover # noqa: E501
if ((kind is not None
and name is args is is_local is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.name = name
self.args = args
self.is_local = is_local
class VariableShowStmt(Node):
__slots__ = {'name': 'char*'} # noqa: E501
def __init__(self, name=None): # pragma: no cover # noqa: E501
if ((name is not None
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
class ViewStmt(Node):
__slots__ = {'view': 'RangeVar*', 'aliases': 'List*', 'query': 'Node*', 'replace': 'bool', 'options': 'List*', 'withCheckOption': 'ViewCheckOption'} # noqa: E501
def __init__(self, view=None, aliases=None, query=None, replace=None, options=None, withCheckOption=None): # pragma: no cover # noqa: E501
if ((view is not None
and aliases is query is replace is options is withCheckOption is None # noqa: E501
and isinstance(view, dict)
and '@' in view)):
super().__init__(view)
else:
self.view = view
self.aliases = aliases
self.query = query
self.replace = replace
self.options = options
self.withCheckOption = withCheckOption
class WindowClause(Node):
__slots__ = {'name': 'char*', 'refname': 'char*', 'partitionClause': 'List*', 'orderClause': 'List*', 'frameOptions': 'int', 'startOffset': 'Node*', 'endOffset': 'Node*', 'inRangeAsc': 'bool', 'inRangeNullsFirst': 'bool', 'winref': 'Index', 'copiedOrder': 'bool'} # noqa: E501
def __init__(self, name=None, refname=None, partitionClause=None, orderClause=None, frameOptions=None, startOffset=None, endOffset=None, inRangeAsc=None, inRangeNullsFirst=None, winref=None, copiedOrder=None): # pragma: no cover # noqa: E501
if ((name is not None
and refname is partitionClause is orderClause is frameOptions is startOffset is endOffset is inRangeAsc is inRangeNullsFirst is winref is copiedOrder is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.refname = refname
self.partitionClause = partitionClause
self.orderClause = orderClause
self.frameOptions = frameOptions
self.startOffset = startOffset
self.endOffset = endOffset
self.inRangeAsc = inRangeAsc
self.inRangeNullsFirst = inRangeNullsFirst
self.winref = winref
self.copiedOrder = copiedOrder
class WindowDef(Node):
__slots__ = {'name': 'char*', 'refname': 'char*', 'partitionClause': 'List*', 'orderClause': 'List*', 'frameOptions': 'int', 'startOffset': 'Node*', 'endOffset': 'Node*', 'location': 'int'} # noqa: E501
def __init__(self, name=None, refname=None, partitionClause=None, orderClause=None, frameOptions=None, startOffset=None, endOffset=None, location=None): # pragma: no cover # noqa: E501
if ((name is not None
and refname is partitionClause is orderClause is frameOptions is startOffset is endOffset is location is None # noqa: E501
and isinstance(name, dict)
and '@' in name)):
super().__init__(name)
else:
self.name = name
self.refname = refname
self.partitionClause = partitionClause
self.orderClause = orderClause
self.frameOptions = frameOptions
self.startOffset = startOffset
self.endOffset = endOffset
self.location = location
class WindowFunc(Expr):
__slots__ = {'args': 'List*', 'aggfilter': 'Expr*', 'winref': 'Index', 'winstar': 'bool', 'winagg': 'bool', 'location': 'int'} # noqa: E501
def __init__(self, args=None, aggfilter=None, winref=None, winstar=None, winagg=None, location=None): # pragma: no cover # noqa: E501
if ((args is not None
and aggfilter is winref is winstar is winagg is location is None # noqa: E501
and isinstance(args, dict)
and '@' in args)):
super().__init__(args)
else:
self.args = args
self.aggfilter = aggfilter
self.winref = winref
self.winstar = winstar
self.winagg = winagg
self.location = location
class WithCheckOption(Node):
__slots__ = {'kind': 'WCOKind', 'relname': 'char*', 'polname': 'char*', 'qual': 'Node*', 'cascaded': 'bool'} # noqa: E501
def __init__(self, kind=None, relname=None, polname=None, qual=None, cascaded=None): # pragma: no cover # noqa: E501
if ((kind is not None
and relname is polname is qual is cascaded is None # noqa: E501
and isinstance(kind, dict)
and '@' in kind)):
super().__init__(kind)
else:
self.kind = kind
self.relname = relname
self.polname = polname
self.qual = qual
self.cascaded = cascaded
class WithClause(Node):
__slots__ = {'ctes': 'List*', 'recursive': 'bool', 'location': 'int'} # noqa: E501
def __init__(self, ctes=None, recursive=None, location=None): # pragma: no cover # noqa: E501
if ((ctes is not None
and recursive is location is None # noqa: E501
and isinstance(ctes, dict)
and '@' in ctes)):
super().__init__(ctes)
else:
self.ctes = ctes
self.recursive = recursive
self.location = location
class XmlExpr(Expr):
__slots__ = {'op': 'XmlExprOp', 'name': 'char*', 'named_args': 'List*', 'arg_names': 'List*', 'args': 'List*', 'xmloption': 'XmlOptionType', 'typmod': 'int32', 'location': 'int'} # noqa: E501
def __init__(self, op=None, name=None, named_args=None, arg_names=None, args=None, xmloption=None, typmod=None, location=None): # pragma: no cover # noqa: E501
if ((op is not None
and name is named_args is arg_names is args is xmloption is typmod is location is None # noqa: E501
and isinstance(op, dict)
and '@' in op)):
super().__init__(op)
else:
self.op = op
self.name = name
self.named_args = named_args
self.arg_names = arg_names
self.args = args
self.xmloption = xmloption
self.typmod = typmod
self.location = location
class XmlSerialize(Node):
__slots__ = {'xmloption': 'XmlOptionType', 'expr': 'Node*', 'typeName': 'TypeName*', 'location': 'int'} # noqa: E501
def __init__(self, xmloption=None, expr=None, typeName=None, location=None): # pragma: no cover # noqa: E501
if ((xmloption is not None
and expr is typeName is location is None # noqa: E501
and isinstance(xmloption, dict)
and '@' in xmloption)):
super().__init__(xmloption)
else:
self.xmloption = xmloption
self.expr = expr
self.typeName = typeName
self.location = location
def _fixup_attribute_types_in_slots():
G = globals()
def traverse_sub_classes(cls):
for subc in cls.__subclasses__():
yield subc
yield from traverse_sub_classes(subc)
for cls in traverse_sub_classes(Node):
slots = cls.__slots__
if not (slots
and isinstance(slots, dict)
and isinstance(next(iter(slots.values())), str)):
continue
for attr in slots:
adaptor = None
ctype = slots[attr]
if ctype == 'List*':
ptype = (list, tuple)
def adaptor(value):
return tuple(G[i['@']](i)
if isinstance(i, dict) and '@' in i
else i
for i in value)
elif ctype == 'bool':
ptype = (bool, int)
adaptor = bool
elif ctype == 'char':
ptype = (str, int)
def adaptor(value):
if isinstance(value, int):
value = chr(value)
elif len(value) != 1:
raise ValueError(f'Bad value for attribute {cls.__name__}.{attr},'
f' expected a single char, got {value!r}')
return value
elif ctype == 'char*':
ptype = str
elif ctype in ('Expr*', 'Node*'):
ptype = (dict, list, tuple, Node)
def adaptor(value):
if isinstance(value, dict):
if '@' in value:
value = G[value['@']](value)
elif isinstance(value, (list, tuple)):
value = tuple(G[i['@']](i)
if isinstance(i, dict) and '@' in i
else i
for i in value)
return value
elif ctype in ('Value', 'Value*'):
ptype = (int, str, float, Decimal, Value)
elif ctype in ('int', 'int16', 'bits32', 'int32', 'uint32', 'uint64',
'AttrNumber', 'AclMode', 'Index', 'SubTransactionId'):
ptype = int
elif ctype == 'Cost':
ptype = float
elif ctype == 'CreateStmt':
ptype = (dict, CreateStmt)
def adaptor(value):
if isinstance(value, dict):
if '@' in value:
value = G[value['@']](value)
return value
elif ctype == 'Bitmapset*':
ptype = (list, set, tuple)
def adaptor(value):
if isinstance(value, (list, tuple)):
return set(value)
else:
return value
else:
from pglast import enums
if hasattr(enums, ctype):
ptype = (int, str, dict, getattr(enums, ctype))
else:
if ctype.endswith('*'):
ptype = G.get(ctype[:-1])
if ptype is None:
raise NotImplementedError(f'unknown {ctype!r}') from None
else:
ptype = (dict, ptype)
slots[attr] = SlotTypeInfo(ctype, ptype, adaptor)
_fixup_attribute_types_in_slots()
del _fixup_attribute_types_in_slots
|
python
|
"""
mqtt_base_client.py
====================================
Base MQTT Client
"""
import paho.mqtt.client as mqtt
from helper import run_async
import _thread
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def on_subscribe_callback(client, userdata, mid, granted_qos):
"""
on_subscribe callback
:param client:
:param userdata:
:param mid:
:param granted_qos:
:return:
"""
log.info("subscribe topic")
def on_connect_callback(client, userdata, flags, rc):
"""
on_connect callback
:param client:
:param userdata:
:param flags:
:param rc:
:return:
"""
log.info("Connected with result code " + str(rc))
def on_message_callback(client, userdata, msg):
"""
on_message callback
:param client:
:param userdata:
:param msg:
:return:
"""
# logging.info("on_message_callback:" + str(msg))
client.msg_queue.put(msg)
def on_publish_callback(client, userdata, mid):
"""
on_publish Callback
:param client:
:param userdata:
:param mid:
:return:
"""
log.info('on_publish_callback')
class BaseClient(object):
"""
Base Class for MQTT-Client
"""
client = None
def __init__(self, broker="iot.eclipse.org", port=1883, sub_queue=None, pub_queue=None, msg_queue=None, password=None, username=None):
"""
Init BaseClient
:param broker:
:param port:
:param sub_queue:
:param pub_queue:
:param msg_queue:
:param password:
:param username:
"""
log.info("run: __init__()")
self.client = mqtt.Client()
self.client.sub_queue = sub_queue
self.client.pub_queue = pub_queue
self.client.msg_queue = msg_queue
self.client.on_connect = on_connect_callback
self.client.on_message = on_message_callback
self.client.on_publish = on_publish_callback
self.client.on_subscribe = on_subscribe_callback
if (password is not None) and (username is not None):
self.client.username_pw_set(username=username,password=password)
try:
self.client.connect(broker, port)
self.client.loop_start()
self.start_sub_queue()
self.start_pub_queue()
except ConnectionRefusedError as e:
log.error(e)
log.info('Exiting main...')
_thread.interrupt_main()
exit(0)
except OSError as e:
log.error(e)
log.info('Exiting main ...')
_thread.interrupt_main()
exit(0)
except KeyboardInterrupt as e:
log.error(e)
log.info('Exiting main ...')
_thread.interrupt_main()
exit(0)
@run_async
def start_sub_queue(self):
"""
Start subscribe queue for handel asynchronous callbacks
:return:
"""
log.info("run: start_sub_queue()")
while True:
topic = self.client.sub_queue.get()
self.client.subscribe(topic)
@run_async
def start_pub_queue(self):
"""
Start publish queue for handel asynchronous callbacks
:return:
"""
log.info("run: start_pub_queue()")
while True:
msg = self.client.pub_queue.get()
self.client.publish(topic=msg['topic'], payload=msg['payload'])
|
python
|
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, DateField,IntegerField, FloatField, SelectField, SelectMultipleField, RadioField, TextAreaField, Form, FieldList, FormField
from wtforms.fields.html5 import DateField
from wtforms.widgets import ListWidget, CheckboxInput
from wtforms.validators import DataRequired, Length, ValidationError
from app.cadastros.models import Cadastro, Unidades
def verfica_cadastro(form, field): # validador de cadastro existente
cadastro = Cadastro.query.get(field.data.upper())
if cadastro:
raise ValidationError('Esse número já está cadastrado ou está incorreto.')
class MultiCheckbox(SelectMultipleField):
widget = ListWidget(prefix_label=False)
option_widget = CheckboxInput()
# class CPFSubform(Form):
# # Subformulario para adicionar campos dinamicamente ao formulario para responsaveis do cadastro
# responsavel = StringField('Responsável:')
# cpf = StringField('CPF')
class CriaCadastro(FlaskForm):
numero = StringField('Numero do Cadastro', validators=[DataRequired(message='O número do cadastro é obrigatório'), Length(min=7,max=8 ,message='O número do cadastro deve possuir entre 7 e 8 caracteres'),verfica_cadastro])
unidade = SelectField('Unidade', choices=[], validators=[DataRequired(message='É obrigatório inserir o nome da unidade')])
titulo = StringField('Titulo do Projeto', validators=[DataRequired(message=('Preencimento Obrigatório'))])
acesso =SelectField('Objeto do Acesso',choices=[(None,'Selecione uma opção'),('Patrimônio Genético', 'Patrimônio Genético'), ('Conhecimento Tradicional Associado', 'Conhecimento Tradicional Associado'), ('Patrimônio Genético e Conhecimento Tradicional Associado','Patrimônio Genético e Conhecimento Tradicional Associado')], validators=[DataRequired(message='Campo Obrigatório')])
data_cadastro = DateField('Data do Cadastro', format='%Y-%m-%d',validators=[DataRequired(message=('Preenchimento Obrigatório'))])
situacao = SelectField('Situação', choices=[(None,'Selecione uma opção'),('Aguardando Revisão', 'Aguardando Revisão'),('Concluído','Concluído'),('Revisado','Revisado')], validators=[DataRequired(message='Selecione uma das opções')])
responsavel = TextAreaField('Responsável')
cpf = TextAreaField('CPF do Responsável')
modalidade = SelectField('Modalidade', choices=[(None,'Selecione uma opção'),('Regularização', 'Regularização'), ('Cadastro Novo', 'Cadastro Novo'),('Adequação','Adequaçao')], validators=[DataRequired(message='Selecione uma das opções')])
finalidade = MultiCheckbox('Finalidade do Acesso',choices=[('Pesquisa','Pesquisa'),('Bioprospecção', 'Bioprospecção'),('Desenvolvimento Tecnológico','Desenvolvimento Tecnológico'),('Pesquisa e Desenvolvimento Tecnológico','Pesquisa e Desenvolvimento Tecnológico')], validators=[DataRequired(message=('Selecione uma das opções'))])
aut_inst = StringField('Autorizacao Instituicao')
aut_processo = StringField('Numero do Processo')
aut_numero = StringField('Numero da Autorização')
aut_validade = StringField('Data da Validade da Autorização')
curb = RadioField('CURB', choices=[('sim','Sim'),('nao','Não')])
data_inicio = StringField('Data Inicio:')
data_fim = StringField('Data Fim')
membro_nome = TextAreaField("Membros Instituição")
membro_instituicao = TextAreaField('Instituição')
componente_tipo = TextAreaField('Tipo do Componente')
componente_especie = TextAreaField('Especie Componente')
raca_local = StringField('Raça Localmente Adaptada')
envio_amostra = RadioField('Envio de Amostra:',choices=[('sim','Sim'),('nao','Não')], validators=[DataRequired(message='Selecione uma das opções')])
cta = SelectField('Conhecimento Tradicional Associado:',choices=[(None,'Selecione uma opção'),('Sim Origem Identificável', 'Sim Origem Identificável'), ('Sim Origem Não Identificável', 'Sim Origem Não Identificável'), ('Não', 'Não')])
componente_acessado = StringField('Conhecimento Tradicional Associado Acessado')
submit = SubmitField('Inserir')
class EditaCadastroForm(FlaskForm):
numero = StringField('Numero do Cadastro', validators=[DataRequired(message='O número do cadastro é obrigatório'), Length(min=8,max=8, message='O número do cadastro deve ter 8 caracteres')])
unidade = SelectField('Unidade', choices=[], validators=[DataRequired(message='É obrigatório inserir o nome da unidade')])
titulo = StringField('Titulo do Projeto', validators=[DataRequired(message=('Preencimento Obrigatório'))])
acesso =SelectField('Objeto do Acesso',choices=[(None,'Selecione uma opção'),('Patrimônio Genético', 'Patrimônio Genético'), ('Conhecimento Tradicional Associado', 'Conhecimento Tradicional Associado'), ('Patrimônio Genético e Conhecimento Tradicional Associado','Patrimônio Genético e Conhecimento Tradicional Associado')], validators=[DataRequired(message='Campo Obrigatório')])
data_cadastro = DateField('Data do Cadastro', format='%Y-%m-%d',validators=[DataRequired(message=('Preenchimento Obrigatório'))])
situacao = SelectField('Situação', choices=[(None,'Selecione uma opção'),('Aguardando Revisão', 'Aguardando Revisão'),('Concluído','Concluído'),('Revisado','Revisado')], validators=[DataRequired(message='Selecione uma das opções')])
responsavel = TextAreaField('Responsável')
cpf = TextAreaField('CPF do Responsável')
modalidade = SelectField('Modalidade', choices=[(None,'Selecione uma opção'),('Regularização', 'Regularização'), ('Cadastro Novo', 'Cadastro Novo'),('Adequação','Adequaçao')], validators=[DataRequired(message='Selecione uma das opções')])
finalidade = MultiCheckbox('Finalidade do Acesso',choices=[('Pesquisa','Pesquisa'),('Bioprospecção', 'Bioprospecção'),('Desenvolvimento Tecnológico','Desenvolvimento Tecnológico'),('Pesquisa e Desenvolvimento Tecnológico','Pesquisa e Desenvolvimento Tecnológico')], validators=[DataRequired(message=('Selecione uma das opções'))])
aut_inst = StringField('Autorizacao Instituicao')
aut_processo = StringField('Numero do Processo')
aut_numero = StringField('Numero da Autorização')
aut_validade = StringField('Data da Validade da Autorização', default=None)
curb = RadioField('CURB', choices=[('sim','Sim'),('nao','Não')])
data_inicio = StringField('Data Inicio:')
data_fim = StringField('Data Fim')
membro_nome = TextAreaField("Membros Instituição")
membro_instituicao = TextAreaField('Instituição')
componente_tipo = TextAreaField('Tipo do Componente')
componente_especie = TextAreaField('Especie Componente')
raca_local = StringField('Raça Localmente Adaptada')
envio_amostra = RadioField('Envio de Amostra:',choices=[('sim','Sim'),('nao','Não')], validators=[DataRequired(message='Selecione uma das opções')])
cta = SelectField('Conhecimento Tradicional Associado:',choices=[('Sim Origem Identificável', 'Sim Origem Identificável'), ('Sim Origem Não Identificável', 'Sim Origem Não Identificável'), ('Não', 'Não')])
componente_acessado = StringField('Conhecimento Tradicional Associado Acessado')
submit = SubmitField('Inserir')
class ResponsavelForm(FlaskForm):
nome = StringField('Nome')
cpf = StringField('CPF')
telefone = StringField('Telefone')
email = StringField('Email')
instituicao = SelectField('Unidade', choices=[])
submit = SubmitField('Enviar')
class UnidadeForm(FlaskForm):
cnpj = StringField('CNPJ')
endereco = StringField('Endereço')
cidade = StringField('Cidade')
estado = SelectField('Estado', choices=[])
cep = StringField('Cep')
chefe_geral = StringField('Chefe-Geral')
telefone = StringField('Telefone')
submit = SubmitField('Enviar')
|
python
|
"""Thread function's arguments
When target function you want to call to run in a thread
has arguments.
"""
import threading, time
def pause(seconds):
i = 0
while i < seconds:
print('Run thread: ' + threading.currentThread().name)
i = i + 1
time.sleep(1)
print('Start main')
threading.Thread(target=pause, name='B', args=[5]).start()
print('End main')
# Start main
# Run thread: B
# End main
# Run thread: B
# Run thread: B
# Run thread: B
# Run thread: B
|
python
|
import logging
import os
import sys
from constants.dbpedia import LINKS_FILE
from extras.dbpedia.loader import start_crawling
log = logging.getLogger( __name__ )
if __name__ == '__main__':
if not os.path.isfile( LINKS_FILE ):
log.error( 'File with links to DBpedia-related files not found. nothing to do' )
sys.exit()
with open( LINKS_FILE, 'rt' ) as f:
urls = [ line.strip() for line in f ]
if len( urls ) == 0:
log.error( 'File empty' )
sys.exit()
start_crawling( urls, 'dumps/dbpedia-en', 12 )
|
python
|
# -*- coding: utf-8 -*-
"""
site.py
~~~~~~~
Flask main app
:copyright: (c) 2015 by Vivek R.
:license: BSD, see LICENSE for more details.
"""
import os
import datetime
from urlparse import urljoin
from collections import Counter, OrderedDict
from flask import Flask
from flask_frozen import Freezer
from werkzeug.contrib.atom import AtomFeed
from flask import render_template, abort, redirect, url_for, \
request, make_response, current_app, Blueprint, send_from_directory
from flask_flatpages import FlatPages, pygments_style_defs
from olaf import contents_dir, content_extension, get_current_dir
from olaf.utils import timestamp_tostring, date_tostring, \
font_size, date_format, create_directory
# initialize extensions
freeze = Freezer()
contents = FlatPages()
app = Blueprint('app', __name__) # create blueprint
exclude_from_sitemap = [] # List of urls to be excluded from XML sitemap
def create_app(current_path, theme_path, **kwargs):
"""
Create app with dynamic configurations
"""
flask_app = Flask(
__name__,
template_folder=os.path.join(theme_path, 'templates'),
static_folder=os.path.join(theme_path, 'static'))
# update configurations
flask_app.config.from_pyfile(os.path.join(
current_path, 'config.py'))
freeze_path = current_path
if kwargs.get('freeze_path'):
freeze_path = kwargs['freeze_path']
freeze_static = False
if kwargs.get('freeze_static'):
freeze_static = True
flask_app.config.update(
current_path=current_path,
FREEZER_DESTINATION=freeze_path,
FREEZER_RELATIVE_URLS=freeze_static,
FREEZER_REMOVE_EXTRA_FILES=False,
FLATPAGES_AUTO_RELOAD=True,
FLATPAGES_EXTENSION=content_extension,
FLATPAGES_ROOT=os.path.join(current_path, contents_dir))
# initialize with current flask app
contents.init_app(flask_app)
freeze.init_app(flask_app)
# Register blueprint as root
flask_app.register_blueprint(app)
# check for duplicate slugs
check_duplicate_slugs(contents)
# filter contents for posts and pages only
filter_valid_contents(contents)
with flask_app.app_context():
# Set home page
flask_app.add_url_rule('/', 'app.index', get_index())
# Register utility functions to be used in jinja2 templates
flask_app.jinja_env.globals.update(
timestamp_tostring=timestamp_tostring,
date_tostring=date_tostring,
font_size=font_size,
content_type=check_content_type,
date_format=date_format,
config=current_app.config)
return flask_app
def filter_valid_contents(contents):
"""
filter contents to only post and pages and
add url attribute to individual content.
"""
contents = [post for post in contents if (
post.path.startswith('posts/') or
post.path.startswith('pages/'))]
for post in contents:
if(post.path.startswith('posts/')
or post.path.startswith('pages/')):
post.slug = post.path[6:]
def check_content_type(path, content_type):
"""
check for specific content type
"""
if content_type == 'post':
if path.startswith('posts/'):
return True
if content_type == 'page':
if path.startswith('pages/'):
return True
return False
def check_duplicate_slugs(contents):
"""
check for duplicate slugs
"""
slugs = []
for post in contents:
slug = ''
if post.path.startswith('pages/'):
slug = post.path.split('pages/')[1]
elif post.path.startswith('posts/'):
slug = post.path.split('posts/')[1]
if slug and slug in slugs:
raise ValueError('Duplicate slug : {}'.format())
def get_posts(**filters):
"""
Filters posts
All arguments are optional
Optional keyword arguments
'sort' : boolean :: sort by timestamp (default: True)
'reverse' : boolean :: Reverse the order (default: True)
'tag' : string :: Filters by tag name (default: None)
'page_no' : integer :: Paginates results and returns result
according to page_no (default: None)
'limit' : integer :: Pagination limit (default: global limit)
'abort' : boolean :: Aborts with 404 error if no posts in
filtered results (default: False)
"""
posts = [post for post in contents if (
post.path.startswith('posts/') and
post.meta.get('date') and
post.meta.get('title'))]
# import pdb; pdb.set_trace()
# Filter conditions
# Sort posts by timestamp (True by default)
sort = filters.get('sort', True)
if(sort):
posts.sort(
key=lambda x: x.meta['date'],
reverse=filters.get('reverse', True))
# Filter based on tag
tag = filters.get('tag')
if(tag):
posts = [post for post in posts
if tag in (post.meta.get('tags') or [])]
# Filter based on year and month
year = filters.get('year')
if(year):
posts = [post for post in posts
if post.meta['date'].year == year]
# Filter by month only if year is given
month = filters.get('month')
if month:
posts = [post for post in posts
if post.meta['date'].month == month]
# Get total number of posts without pagination
post_meta = {}
post_meta['total_pages'] = len(posts)
# Filter based on page number and pagination limit
page_no = filters.get('page_no')
limit = filters.get('limit') or current_app.config['SITE']['limit'] or 10
max_pages = 0
if(page_no):
paginated = [posts[n:n + limit] for n in range(0, len(posts), limit)]
max_pages = len(paginated)
try:
posts = paginated[page_no - 1]
except IndexError:
posts = []
post_meta['max_pages'] = max_pages
# Abort if posts not found
if not posts and filters.get('abort') is True:
abort(404)
return (posts, post_meta)
def get_post_by_slug(slug):
"""
filter contents by slug
"""
content = [post for post in contents if post.slug == slug]
return content
"""
Views
"""
@app.route('/404.html')
def custom_404():
"""
custom 404 page view
"""
return render_template('404.html')
@app.route('/pygments.css')
def pygments_css():
"""
default pygments style
"""
pyments_style = current_app.config['SITE'].get('pygments_style') or 'tango'
return (pygments_style_defs(pyments_style), 200, {'Content-Type': 'text/css'})
exclude_from_sitemap.append('/pygments.css') # Excludes url from sitemap
@app.route('/assets/<path:filename>')
def custom_static(filename):
"""
custom assets folder
"""
# custom assets folder
assets_path = os.path.join(
get_current_dir(),
current_app.config['SITE'].get('assets') or 'assets')
# create assets folder if not there
if not os.path.exists(assets_path):
create_directory(assets_path)
return send_from_directory(assets_path, filename)
def get_index():
"""
check if custom home page set else return default index view
"""
if current_app.config['SITE'].get('custom_home_page'):
content = get_post_by_slug(current_app.config['SITE']['custom_home_page'])
# Exception if slug not found both in pages and posts
if not content:
raise Exception('Custom home page url not found')
# Exception if duplicates found
if len(content) > 1:
raise Exception('Duplicate slug')
return custom_index
else:
return default_index
def default_index():
"""
default index view
"""
posts, post_meta = get_posts(page_no=1)
return render_template('index.html',
page_no=1, posts=posts, next_page=post_meta['max_pages'] > 1)
def custom_index():
"""
custom home page view
"""
content = get_post_by_slug(current_app.config['SITE']['custom_home_page'])
content[0].meta['type'] = 'page'
return render_template('content.html', content=content[0])
@app.route('/pages/<int:page_no>/')
def pagination(page_no):
"""
home page pagination view
"""
# Redirect if it is a first page (except when custom home page is set)
if page_no == 1 and not current_app.config['SITE'].get('custom_home_page'):
return redirect(url_for('.index'))
posts, post_meta = get_posts(page_no=page_no, abort=True)
return render_template('index.html', page_no=page_no,
posts=posts, next_page=(post_meta['max_pages'] > page_no),
previous_page=(page_no > 1))
@app.route('/<path:slug>/')
def posts(slug):
"""
individual post/page view
"""
content = get_post_by_slug(slug)
if not content:
abort(404) # Slug not found both in pages and posts
# Exception if duplicates found
if len(content) > 1:
raise Exception('Duplicate slug')
disqus_html = ''
disqus_file_path = os.path.join(current_app.config['current_path'], 'disqus.html')
with open(disqus_file_path, 'r') as f:
disqus_html = f.read()
return render_template('content.html', content=content[0],
disqus_html=disqus_html)
# Tag views
@app.route('/tags/')
def tags():
"""
list of tags view
"""
# import pdb; pdb.set_trace()
tags = [tag for post in contents if post.meta.get('tags')
for tag in post.meta['tags']]
tags = sorted(Counter(tags).items()) # Count tag occurances
max_occ = 0 if not tags else max([tag[1] for tag in tags])
return render_template('tags.html', tags=tags, max_occ=max_occ)
@app.route('/tags/<string:tag>/')
def tag_page(tag):
"""
individual tag view
"""
posts, post_meta = get_posts(tag=tag, page_no=1, abort=True)
return render_template('tag.html', tag=tag, posts=posts,
page_no=1, next_page=(post_meta['max_pages'] > 1),
len = post_meta['total_pages'])
@app.route('/tags/<string:tag>/pages/<int:page_no>/')
def tag_pages(tag, page_no):
"""
pagination for Individual tags
"""
posts, post_meta = get_posts(tag=tag, page_no=page_no, abort=True)
# Redirect if it is a first page
if page_no == 1:
return redirect(url_for('.tag_page', tag=tag))
return render_template('tag.html', tag=tag, posts=posts,
page_no=page_no, next_page=(post_meta['max_pages'] > page_no),
len = post_meta['total_pages'], previous_page=(page_no > 1))
@app.route('/list/posts/')
def list_posts():
"""
all posts list view
"""
return render_template("list_posts.html", posts=get_posts()[0])
@app.route('/list/pages/')
def list_pages():
"""
all pages list view
"""
pages = [page for page in contents
if page.path.startswith('pages/')]
return render_template("list_pages.html", pages=pages)
@app.route('/archive/')
def archive():
"""
date based archive view
"""
# Get all posts dates in format (year, month)
dates = [(post.meta['date'].year, post.meta['date'].month)
for post in contents if post.meta.get('date')]
# Get sorted yearly archive lists ex: [(year, no_occur), ...]
yearly = sorted(Counter([date[0] for date in dates]).items(), reverse=True)
# Get sorted yearly and monthly archive lists [((year, month), no_occur), ...]
monthly = sorted(Counter([date for date in dates]).items(), reverse=True)
yearly_dict = OrderedDict()
for i in yearly:
year = i[0]
yearly_dict[year] = {}
yearly_dict[year]['count'] = i[1]
yearly_dict[year]['months'] = [(j[0][1], j[1])
for j in monthly if j[0][0] == year]
return render_template('archive.html', archive=yearly_dict)
@app.route('/archive/<int:year>/')
def yearly_archive(year):
"""
yearly archive view
"""
posts, post_meta = get_posts(year=year, abort=True)
return render_template('archive_page.html', tag=year, year=year, posts=posts)
@app.route('/archive/<int:year>/<int:month>/')
def monthly_archive(year, month):
"""
monthly archive view
"""
date_string = date_tostring(year, month, format='%b %Y')
posts, post_meta = get_posts(year=year, month=month, abort=True)
return render_template('archive_page.html', tag=date_string, year=year,
month=month, posts=posts)
@app.route('/recent.atom')
def recent_feed():
"""
atom feed generator
"""
posts, max_page = get_posts()
feed_limit = current_app.config['SITE'].get('feed_limit', 10)
domain_url = current_app.config['SITE'].get('domain_url')
if not domain_url:
domain_url = request.url_root
feed = AtomFeed('Recent Articles',
url=domain_url,
feed_url=urljoin(domain_url, '/recent.atom'),
id=urljoin(domain_url, '/recent.atom'))
for post in posts[:feed_limit]:
dated = post.meta['date']
updated = dated
if post.meta.get('updated'):
updated = post.meta['updated']
# if its a date object convert to datetime object
# since tzinfo needed to create feeds
if isinstance(updated, datetime.date):
updated = datetime.datetime.combine(
updated, datetime.datetime.min.time())
if isinstance(dated, datetime.date):
dated = datetime.datetime.combine(
dated, datetime.datetime.min.time())
feed.add(
post.meta.get('title'),
unicode(post.html),
content_type='html',
author=post.meta.get(
'author', ', '.join(
current_app.config['SITE'].get('author', []))),
url=urljoin(domain_url, post.slug),
updated=updated,
published=dated,
xml_base=urljoin(domain_url, '/recent.atom'))
return feed.get_response()
@app.route('/sitemap.xml', methods=['GET'])
def sitemap():
"""
XML sitemap generator
"""
resources = []
# Set last updated date for static pages as 10 days before
ten_days_ago = (
datetime.datetime.now() -
datetime.timedelta(days=10)).date().isoformat()
# import pdb; pdb.set_trace()
domain_url = current_app.config['SITE'].get('domain_url')
if not domain_url:
domain_url = request.url_root
# Add static pages
for rule in current_app.url_map.iter_rules():
if ("GET" in rule.methods and len(rule.arguments) == 0 and
rule.rule not in exclude_from_sitemap):
resources.append(
{
'url': urljoin(domain_url, rule.rule),
'modified': ten_days_ago
}
)
# Add posts
posts, max_page = get_posts()
for content in contents:
# Get post update or creation date
if content.meta.get('updated'):
updated = content.meta['updated'].isoformat()
elif content.meta.get('date'):
updated = content.meta['date'].isoformat()
else:
updated = ten_days_ago
# Add posts url
resources.append(
{
'url': urljoin(domain_url, content.slug),
'modified': updated
}
)
sitemap_xml = render_template('sitemap.xml', resources=resources)
response = make_response(sitemap_xml)
response.headers["Content-Type"] = "application/xml"
return response
|
python
|
from allennlp.predictors.predictor import Predictor
from typing import List
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance
@Predictor.register("rationale_predictor")
class RationalePredictor(Predictor) :
def _json_to_instance(self, json_dict):
raise NotImplementedError
def predict_batch_instance(self, instances: List[Instance]) -> List[JsonDict]:
self._model.prediction_mode = True
outputs = self._model.forward_on_instances(instances)
return sanitize(outputs)
|
python
|
from setuptools import setup, find_packages
with open("README.md", "r") as f:
long_description = f.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='alfrodull',
version='0.1.0',
author='Philip Laine',
author_email='[email protected]',
description='Alfrodull is a utility that controls lights based on the a computers events',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/phillebaba/alfrodull',
packages=find_packages(),
install_requires=requirements,
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
],
entry_points='''
[console_scripts]
alfrodull=alfrodull.main:main
'''
)
|
python
|
annoy_index_db_path = 'cache/index.db'
already_img_response = 'there are not math image'
success_response = 'success'
dim_800x800 = (800,800)
|
python
|
#!/usr/bin/env python3
# (C) Copyright 2022 European Centre for Medium-Range Weather Forecasts.
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
import climetlab as cml
def test_source():
ds = cml.load_source(
"newsource",
arg1="1",
arg2="2",
)
df = ds.to_pandas()
print(df)
if __name__ == "__main__":
test_source()
|
python
|
from typing import Any, Dict
import pytest
from nuplan.common.utils.testing.nuplan_test import NUPLAN_TEST_PLUGIN, nuplan_test
from nuplan.planning.metrics.evaluation_metrics.common.ego_yaw_acceleration import EgoYawAccelerationStatistics
from nuplan.planning.metrics.utils.testing_utils import metric_statistic_test
@nuplan_test(path='json/ego_yaw_acceleration/ego_yaw_acceleration.json')
def test_ego_yaw_acceleration(scene: Dict[str, Any]) -> None:
"""
Tests ego yaw acceleration statistics as expected.
:param scene: the json scene
"""
metric = EgoYawAccelerationStatistics('ego_yaw_acceleration_statistics', 'Dynamics', max_abs_yaw_accel=3.0)
metric_statistic_test(scene=scene, metric=metric)
if __name__ == '__main__':
raise SystemExit(pytest.main([__file__], plugins=[NUPLAN_TEST_PLUGIN]))
|
python
|
import pandas as pd
import numpy as np
from src.configs import *
from src.features.transform import categorical_to_ordinal
import collections
class HousePriceData:
'''
Load House Price data for Kaggle competition
'''
def __init__(self, train_path, test_path):
self.trainset = pd.read_csv(train_path)
self.testset = pd.read_csv(test_path)
self.target = self.trainset["SalePrice"]
self.workset = None
self.train_id = self.trainset["Id"]
self.test_id = self.testset["Id"]
# Keep track of feature to use to train in class
# Don'T really like that, but can't find a better way for now
self.original_feature_name = list(self.trainset)
self.created_feature = list()
self.ignored_feature = list()
self.usable_feature_name = list()
self._create_join_workset()
self._replace_significant_nan_values()
self._replace_all_nan_values()
self._change_col_type()
self._apply_feature_engineering()
def _replace_significant_nan_values(self, filler="MISSING"):
for col in COL_WITH_NAN_SIGNIFICATION:
self.workset[col] = self.workset[col].fillna(filler)
self.update_train_and_test_set(self.workset)
def get_usable_feature_name(self):
self.usable_feature_name = self.original_feature_name
for feature_name in self.created_feature:
self.usable_feature_name.append(feature_name)
for feature_name in self.ignored_feature:
try:
self.usable_feature_name.remove(feature_name)
except Exception as e:
pass
return self.usable_feature_name
def add_created_features(self, feature_names):
if isinstance(feature_names, str):
self.created_feature.append(feature_names)
elif isinstance(feature_names, collections.Iterable):
for i in feature_names:
self.created_feature.append(i)
else:
raise ValueError('Not valid feature_names type. Should be str or Iterable')
def add_ignore_features(self, feature_names):
if isinstance(feature_names, str):
self.ignored_feature.append(feature_names)
elif isinstance(feature_names, collections.Iterable):
for i in feature_names:
self.ignored_feature.append(i)
else:
raise ValueError('Not valid feature_names type. Should be str or Iterable')
def _replace_all_nan_values(self, filler="NO"):
self.workset = self.workset.fillna(filler)
self.update_train_and_test_set(self.workset)
def _create_join_workset(self):
self.workset = pd.concat([self.trainset[ORIGINAL_FEATURE_COLS], self.testset[ORIGINAL_FEATURE_COLS]], axis=0)
def update_train_and_test_set(self, workset):
self.trainset = workset[workset['Id'].isin(self.train_id)]
self.testset = workset[workset['Id'].isin(self.test_id)]
def update_workset(self, workset):
self.workset = workset
self.update_train_and_test_set(self.workset)
def _change_col_type(self):
for col in ["MoSold", "MSSubClass"]:
self.workset[col] = self.workset[col].astype('str')
self.update_train_and_test_set(self.workset)
def _apply_feature_engineering(self):
self.update_train_and_test_set(self.workset)
|
python
|
#!/usr/bin/env python
# coding=utf-8
import os
import shutil
from src.core.setcore import *
# Py2/3 compatibility
# Python3 renamed raw_input to input
try: input = raw_input
except NameError: pass
dest = ("src/html/")
url = ("")
debug_msg(mod_name(), "entering src.html.templates.template'", 1)
#
# used for pre-defined templates
#
print("""
--------------------------------------------------------
**** Important Information ****
For templates, when a POST is initiated to harvest
credentials, you will need a site for it to redirect.
You can configure this option under:
/etc/setoolkit/set.config
Edit this file, and change HARVESTER_REDIRECT and
HARVESTER_URL to the sites you want to redirect to
after it is posted. If you do not set these, then
it will not redirect properly. This only goes for
templates.
--------------------------------------------------------""")
print("""
1. Java Required
2. Google
3. Twitter
""")
choice = raw_input(setprompt(["2"], "Select a template"))
if choice == "exit":
exit_set()
# file used for nextpage in java applet attack
# if nothing is selected
if choice == "":
choice = "1"
# if java required
if choice == "1":
if os.path.isfile("src/html/index.template"):
os.remove("src/html/index.template")
shutil.copyfile("src/html/templates/java/index.template", "src/html/index.template")
url = ""
# if google
if choice == "2":
if os.path.isfile("src/html/index.template"):
os.remove("src/html/index.template")
shutil.copyfile("src/html/templates/google/index.template", "src/html/index.template")
url = "http://www.google.com"
# if twitter
if choice == "3":
if os.path.isfile("src/html/index.template"):
os.remove("src/html/index.template")
shutil.copyfile("src/html/templates/twitter/index.template", "src/html/index.template")
url = "http://www.twitter.com"
if not os.path.isdir(os.path.join(userconfigpath, "web_clone")):
os.makedirs(os.path.join(userconfigpath, "web_clone/"))
if os.path.isfile(os.path.join(userconfigpath, "web_clone/index.html")):
os.remove(os.path.join(userconfigpath, "web_clone/index.html"))
shutil.copyfile("src/html/index.template", os.path.join(userconfigpath, "web_clone/index.html"))
with open(os.path.join(userconfigpath, "site.template"), 'w') as filewrite:
filewrite.write("TEMPLATE=SELF\nURL={0}".format(url))
debug_msg(mod_name(), "exiting src.html.templates.template'", 1)
|
python
|
from typing import Any, Optional
from fastapi import HTTPException
class NotFoundHTTPException(HTTPException):
"""Http 404 Not Found exception"""
def __init__(self, headers: Optional[dict[str, Any]] = None) -> None:
super().__init__(404, detail="Not Found", headers=headers)
class BadRequestHTTPException(HTTPException):
"""Http 400 Bad Request exception"""
def __init__(
self, detail: Any = None, headers: Optional[dict[str, Any]] = None
) -> None:
super().__init__(400, detail=detail, headers=headers)
|
python
|
from setuptools import setup
setup(name="spikerlib",
version="0.8",
description="Collection of tools for analysing spike trains",
author="Achilleas Koutsou",
author_email="[email protected]",
#package_dir={'': 'spikerlib'},
packages=["spikerlib", "spikerlib.metrics"]
)
|
python
|
"""Parse CaffeModel.
Helped by caffe2theano, MarcBS's Caffe2Keras module.
Author: Yuhuang Hu
Email : [email protected]
"""
from __future__ import print_function
from collections import OrderedDict
import numpy as np
from scipy.io import loadmat
from transcaffe import caffe_pb2, utils
from google.protobuf.text_format import Merge
from keras.models import Model
from transcaffe import layers as L
v1_map = {0: 'NONE', 1: 'ACCURACY', 2: 'BNLL', 3: 'CONCAT', 4: 'CONVOLUTION',
5: 'DATA', 6: 'DROPOUT', 7: 'EUCLIDEANLOSS', 8: 'FLATTEN',
9: 'HDF5DATA', 10: 'HDF5OUTPUT', 11: 'IM2COL', 12: 'IMAGEDATA',
13: 'INFOGAINLOSS', 14: 'INNERPRODUCT', 15: 'LRN',
16: 'MULTINOMIALLOGISTICLOSS', 17: 'POOLING', 18: 'RELU',
19: 'SIGMOID', 20: 'SOFTMAX', 21: 'SOFTMAXWITHLOSS', 22: 'SPLIT',
23: 'TANH', 24: 'WINDOWDATA', 25: 'ELTWISE', 26: 'POWER',
27: 'SIGMOIDCROSSENTROPYLOSS', 28: 'HINGELOSS', 29: 'MEMORYDATA',
30: 'ARGMAX', 31: 'THRESHOLD', 32: 'DUMMY_DATA', 33: 'SLICE',
34: 'MVN', 35: 'ABSVAL', 36: 'SILENCE', 37: 'CONTRASTIVELOSS',
38: 'EXP', 39: 'DECONVOLUTION'}
def load(model_def, model_bin, target_lib="keras"):
"""Load a Caffe model and convert to target library.
Parameters
----------
model_def : string
absolute path of a given .protobuf text
model_bin : string
absolute path of a given .caffemodel binary
target_lib : string
target library, currently only Keras is supported.
In planning: Lasagne, TensorFlow
Returns
-------
model : keras.models.model
a loaded model.
"""
print ("[MESSAGE] Target model is loading...")
net_param = parse_protobuf(model_def)
layers, version = get_layers(net_param)
input_dim = get_input_size(net_param)
model = get_model(layers, 1, tuple(input_dim[1:]), net_param.name)
print ("[MESSAGE] Printing converted model...")
model.summary()
print ("[MESSAGE] The model is built.")
print ("[MESSAGE] Parsing network parameters...")
param_layers, _ = parse_caffemodel(model_bin)
net_weights = get_network_weights(param_layers, version)
print ("[MESSAGE] Loading parameters into network...")
build_model(model, net_weights)
print ("[MESSAGE] The model is loaded successfully.")
return model
def parse_caffemodel(filename):
"""Parse a given caffemodel.
Parameters
----------
filename : string
absolute path of a given .caffemodel
Returns
-------
layers : list
The list representation of the network
version : string
pretrined network version
"""
utils.file_checker(filename)
net_param = caffe_pb2.NetParameter()
f = open(filename, mode="rb")
contents = f.read()
f.close()
net_param.ParseFromString(contents)
return get_layers(net_param)
def parse_mean_file(filename, mode="proto"):
"""Parse a mean file by given path.
TODO: complete more options based on different Caffe Models
Parameters
----------
filename : string
absolute path of the mean file
mode : string
"proto" for .binaryproto file
"mat" for MAT binary file
Returns
-------
mean_mat : numpy.ndarray
an array that contains the mean values
"""
utils.file_checker(filename)
if mode == "proto":
tp = caffe_pb2.TransformationParameter()
f = open(filename, mode="rb")
mean_contents = f.read()
f.close()
tp.ParseFromString(mean_contents)
mean_mat = np.array(tp.mean_value).reshape((3,
tp.crop_size,
tp.crop_size))
mean_mat = np.transpose(mean_mat, (1, 2, 0))
elif mode == "mat":
# based on VGG's Mat file.
mean_contents = loadmat(filename)
mean_mat = mean_contents["image_mean"]
print(mean_mat.shape)
return mean_mat
def parse_protobuf(filename):
"""Parse a given protobuf file.
Parameters
----------
filename : string
absolute path of .prototxt file
Returns
-------
net_param : caffe_pb2.NetParameter
The parsed .prototxt structure.
"""
utils.file_checker(filename)
f = open(filename, mode="rb")
net_param = caffe_pb2.NetParameter()
net_def = f.read()
# append quotes around type information if needed.
# it seems not working because has newer definititon?
# net_def = f.read().split("\n")
# for i, line in enumerate(net_def):
# l = line.strip().replace(" ", "").split('#')[0]
# if len(l) > 6 and l[:5] == 'type:' and l[5] != "\'" and l[5] != '\"':
# type_ = l[5:]
# net_def[i] = ' type: "' + type_ + '"'
#
# net_def = '\n'.join(net_def)
# Check before Merge? For V1?
Merge(net_def, net_param)
f.close()
return net_param
def get_layers(net_param):
"""Get layers information.
Parameters
----------
net_param : caffe_pb2.NetParameter
A pretrined network description.
Returns
-------
layers : list
description of the layers.
version : string
version information of the pretrained model.
"""
if len(net_param.layers) > 0:
return net_param.layers[:], "V1"
elif len(net_param.layer) > 0:
return net_param.layer[:], "V2"
else:
raise Exception("Couldn't find layers!")
def get_layer_type(layer):
"""Get a given layer type.
Parameters
----------
layer : caffe_pb2.V1LayerParameter
a given layer in the network
Returns
-------
type : int or string
type of the layer.
"""
if type(layer.type) == int:
return str(v1_map[layer.type]).lower()
else:
return str(layer.type).lower()
def get_input_size(net_param):
"""Get input parameters, or guess one at least.
Parameters
----------
net_param : caffe_pb2.NetParameter
structure that contains all the network parameters
Returns
-------
in_size : tuple
tuple that defines the input size
"""
if len(net_param.input_dim) != 0:
return net_param.input_dim
elif len(net_param.input_shape) != 0:
return net_param.input_shape
else:
print("[MESSAGE] Couldn't find Input shape in the Network Parameters."
"The returned shape is inferenced from the network name")
# try:
# scale = layer.transform_param.scale
# scale = 1 if scale <= 0 else scale
# except AttributeError:
# pass
return []
def check_phase(layer, phase):
"""Check if the layer matches with the target phase.
Parameters
----------
layer : caffe_pb2.V1LayerParameter
A given layer.
phase : int
0 : train
1 : test
"""
try:
return True if layer.include[0].phase == phase else False
except IndexError:
return True
def get_network(layers, phase):
"""Get structure of the network.
Parameters
----------
layers : list
list of layers parsed from network parameters
phase : int
0 : train
1 : test
"""
num_layers = len(layers)
network = OrderedDict()
for i in xrange(num_layers):
layer = layers[i]
if check_phase(layer, phase):
layer_id = "trans_layer_"+str(i)
if layer_id not in network:
network[layer_id] = []
prev_blobs = map(str, layer.bottom)
next_blobs = map(str, layer.top)
for blob in prev_blobs+next_blobs:
if blob not in network:
network[blob] = []
for blob in prev_blobs:
network[blob].append(layer_id)
network[layer_id].extend(next_blobs)
network = remove_loops(network)
network = remove_blobs(network)
return network
def remove_loops(network):
"""Remove potential loops from the network.
Parameters
----------
network : OrderedDict
given network dictionary
new_network : OrderedDict
a loops free altered network.
"""
for e in network:
if e.startswith("trans_layer_"):
continue
idx = 0
while idx < len(network[e]):
next_e = network[e][idx]
if e in network[next_e]:
new_e = e+"_"+str(idx)
network[e].remove(next_e)
network[new_e] = network[e]
network[e] = [next_e]
network[next_e] = [new_e]
for n in network[new_e]:
if network[n] == [e]:
network[n] = [new_e]
e = new_e
idx = 0
else:
idx += 1
return network
def remove_blobs(network):
"""Remove blobs from network.
Parameters
----------
network : OrderedDict
given network dictionary
Returns
-------
new_network : OrderedDict
blobs removed network dictionary
"""
new_network = OrderedDict()
def get_idx(x): return int(x[12:])
for e in network:
if e.startswith("trans_layer_"):
idx = get_idx(e)
if idx not in new_network:
new_network[idx] = []
for next_e in network[e]:
next_es = map(get_idx, network[next_e])
new_network[idx].extend(next_es)
return new_network
def reverse_net(network):
"""Reverse a network.
Parameters
----------
network : OrderedDict
A parsed network
Returns
-------
rev : OrderedDict
reversed network
"""
rev = OrderedDict()
for node in network.keys():
rev[node] = []
for node in network.keys():
for n in network[node]:
rev[n].append(node)
return rev
def get_input_layers(network):
"""Get input layers (layers with zero in-order).
Parameters
----------
network : OrderedDict
A parsed network
Returns
-------
in_layers : list
a list of input layers
"""
return get_output_layers(reverse_net(network))
def get_output_layers(network):
"""Get output layers (layers with zero out-order).
Parameters
----------
network : OrderedDict
A parsed network
Returns
-------
out_layers : list
a list of out layers
"""
out_layers = []
for idx in network:
if network[idx] == []:
out_layers.append(idx)
return out_layers
def get_model(layers, phase, input_dim, model_name, lib_type="keras"):
"""Get a model by given network parameters.
Parameters
----------
layers : list
network structure by given parsed network.
phase : int
0 : train
1 : test
input_dim : list
the input dimension
model_name : string
the name of the given model.
lib_type : string
currently only Keras is supported.
"""
network = get_network(layers, phase)
if len(network) == 0:
raise Exception("No valid network is parsed!")
in_layers = get_input_layers(network)
out_layers = get_output_layers(network)
rev_network = reverse_net(network)
def data_layer(x): get_layer_type(x) in ['data', 'imagedata', 'memorydata',
'hdf5data', 'windowdata']
# remove the link from input to output.
for in_idx in in_layers:
for out_idx in out_layers:
if out_idx in network[in_idx] and data_layer(layers[in_idx]):
network[in_idx].remove[out_idx]
net = [None]*(max(network)+1)
for layer_id in network:
layer = layers[layer_id]
layer_name = layer.name
layer_type = get_layer_type(layer)
if layer_id in in_layers:
net[layer_id] = L.input_layer(input_dim, layer_name)
else:
layer_in = [None]*(len(rev_network[layer_id]))
for l in xrange(len(rev_network[layer_id])):
layer_in[l] = net[rev_network[layer_id][l]]
if layer_type in ["relu", "sigmoid", "softmax", "softmaxwithloss",
"split", "tanh"]:
net[layer_id] = L.activation(act_type=layer_type,
name=layer_name)(layer_in)
elif layer_type == "batchnorm":
epsilon = layer.batchnorm_param.eps
axis = layer.scale_param.axis
net[layer_id] = L.batch_norm(epsilon=epsilon, axis=axis,
name=layer_name)(layer_in)
elif layer_type == "lrn":
alpha = layer.lrn_param.alpha
k = layer.lrn_param.k
beta = layer.lrn_param.beta
n = layer.lrn_param.local_size
net[layer_id] = L.lrn(alpha, k, beta, n, layer_name)(layer_in)
elif layer_type == "scale":
axis = layer.scale_param.axis
net[layer_id] = L.scale(axis, layer_name)(layer_in)
elif layer_type == "dropout":
prob = layer.dropout_param.dropout_ratio
net[layer_id] = L.dropout(prob, name=layer_name)(layer_in)
elif layer_type == "flatten":
net[layer_id] = L.flatten(name=layer_name)(layer_in)
elif layer_type == "concat":
axis = layer.concat_param.axis
net[layer_id] = L.merge(layer_in, mode='concat',
concat_axis=1, name=layer_name)
elif layer_type == "eltwise":
axis = layer.scale_param.axis
op = layer.eltwise_param.operation
if op == 0:
mode = "mul"
elif op == 1:
mode = "sum"
elif op == 2:
mode == "max"
else:
raise NotImplementedError("Operation is not implemented!")
net[layer_id] = L.merge(layer_in, mode=mode, concat_axis=axis,
name=layer_name)
elif layer_type == "innerproduct":
output_dim = layer.inner_product_param.num_output
if len(layer_in[0]._keras_shape[1:]) > 1:
layer_in = L.flatten(name=layer_name+"_flatten")(layer_in)
net[layer_id] = L.dense(output_dim, name=layer_name)(layer_in)
elif layer_type == "convolution":
has_bias = layer.convolution_param.bias_term
nb_filter = layer.convolution_param.num_output
nb_col = (layer.convolution_param.kernel_size or
[layer.convolution_param.kernel_h])[0]
nb_row = (layer.convolution_param.kernel_size or
[layer.convolution_param.kernel_w])[0]
stride_h = (layer.convolution_param.stride or
[layer.convolution_param.stride_h])[0] or 1
stride_w = (layer.convolution_param.stride or
[layer.convolution_param.stride_w])[0] or 1
pad_h = (layer.convolution_param.pad or
[layer.convolution_param.pad_h])[0]
pad_w = (layer.convolution_param.pad or
[layer.convolution_param.pad_w])[0]
if pad_h + pad_w > 0:
layer_in = L.zeropadding(padding=(pad_h, pad_w),
name=layer_name)(layer_in)
net[layer_id] = L.convolution(nb_filter, nb_row, nb_col,
bias=has_bias,
subsample=(stride_h, stride_w),
name=layer_name)(layer_in)
elif layer_type == "pooling":
kernel_h = layer.pooling_param.kernel_size or \
layer.pooling_param.kernel_h
kernel_w = layer.pooling_param.kernel_size or \
layer.pooling_param.kernel_w
stride_h = layer.pooling_param.stride or \
layer.pooling_param.stride_h or 1
stride_w = layer.pooling_param.stride or \
layer.pooling_param.stride_w or 1
pad_h = layer.pooling_param.pad or layer.pooling_param.pad_h
pad_w = layer.pooling_param.pad or layer.pooling_param.pad_w
if pad_h + pad_w > 0:
layer_in = L.zeropadding(padding=(pad_h, pad_w),
name=layer_name)(layer_in)
net[layer_id] = L.pooling(pool_size=(kernel_h, kernel_w),
strides=(stride_h, stride_w),
pool_type=layer.pooling_param.pool,
name=layer_name)(layer_in)
in_l = [None]*(len(in_layers))
out_l = [None]*(len(out_layers))
for i in xrange(len(in_layers)):
in_l[i] = net[in_layers[i]]
for i in xrange(len(out_layers)):
out_l[i] = net[out_layers[i]]
return Model(input=in_l, output=out_l, name=model_name)
def get_network_weights(layers, version):
"""Parse network weights.
Parameters
----------
layers : list
List of parameter layers from caffemodel
version : "string"
"V1" or "V2"
Return
------
net_weights : OrderedDict
network's weights
"""
net_weights = OrderedDict()
for layer in layers:
layer_type = get_layer_type(layer)
if layer_type == "innerproduct":
blobs = layer.blobs
if (version == "V1"):
num_filters = blobs[0].num
num_channels = blobs[0].channels
num_col = blobs[0].height
num_row = blobs[0].width
elif (version == "V2"):
if (len(blobs[0].shape.dim) == 4):
num_filters = int(blobs[0].shape.dim[0])
num_channels = int(blobs[0].shape.dim[1])
num_col = int(blobs[0].shape.dim[2])
num_row = int(blobs[0].shape.dim[3])
else:
num_filters = 1
num_channels = 1
num_col = int(blobs[0].shape.dim[0])
num_row = int(blobs[0].shape.dim[1])
else:
raise Exception("Can't recognize the version %s" % (version))
W = np.array(blobs[0].data).reshape(num_filters, num_channels,
num_col, num_row)[0, 0, :, :]
W = W.T
b = np.array(blobs[1].data)
layer_weights = [W.astype(dtype=np.float32),
b.astype(dtype=np.float32)]
net_weights[layer.name] = layer_weights
elif layer_type == "convolution":
blobs = layer.blobs
if (version == "V1"):
num_filters = blobs[0].num
num_channels = blobs[0].channels
num_col = blobs[0].height
num_row = blobs[0].width
elif (version == "V2"):
num_filters = int(blobs[0].shape.dim[0])
num_channels = int(blobs[0].shape.dim[1])
num_col = int(blobs[0].shape.dim[2])
num_row = int(blobs[0].shape.dim[3])
else:
raise Exception("Can't recognize the version %s" % (version))
num_group = layer.convolution_param.group
num_channels *= num_group
W = np.zeros((num_filters, num_channels, num_col, num_row))
if layer.convolution_param.bias_term:
b = np.array(blobs[1].data)
else:
b = None
group_ds = len(blobs[0].data) // num_group
ncs_group = num_channels // num_group
nfs_group = num_filters // num_group
for i in range(num_group):
group_weights = W[i*nfs_group: (i+1)*nfs_group,
i*ncs_group: (i+1)*ncs_group, :, :]
group_weights[:] = np.array(
blobs[0].data[i*group_ds:
(i+1)*group_ds]).reshape(group_weights.shape)
for i in range(W.shape[0]):
for j in range(W.shape[1]):
W[i, j] = np.rot90(W[i, j], 2)
if b is not None:
layer_weights = [W.astype(dtype=np.float32),
b.astype(dtype=np.float32)]
else:
layer_weights = [W.astype(dtype=np.float32)]
net_weights[layer.name] = layer_weights
elif layer_type == "batchnorm":
blobs = layer.blobs
if (version == "V2"):
num_kernels = int(blobs[0].shape.dim[0])
else:
raise NotImplementedError("Batchnorm is not "
"implemented in %s" % (version))
W_mean = np.array(blobs[0].data)
W_std = np.array(blobs[1].data)
net_weights[layer.name] = [np.ones(num_kernels),
np.zeros(num_kernels),
W_mean.astype(dtype=np.float32),
W_std.astype(dtype=np.float32)]
return net_weights
def build_model(model, net_weights):
"""Load network's weights to model.
Parameters
----------
model : keras.models.model
The model structure of Keras
net_weights : OrderedDict
networ's weights
"""
for layer in model.layers:
if layer.name in net_weights:
model.get_layer(layer.name).set_weights(net_weights[layer.name])
|
python
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from collections import defaultdict
from translator.hot.syntax.hot_resource import HotResource
# Name used to dynamically load appropriate map class.
TARGET_CLASS_NAME = 'ToscaClusterAutoscaling'
SCALE_POLICY = 'senlin.policy.scaling-1.0'
SERVER_TYPE = 'os.nova.server-1.0'
SCALE_TYPE = {'SCALE_IN': 'CLUSTER_SCALE_IN',
'SCALE_OUT': 'CLUSTER_SCALE_OUT'}
ALARM_METER_NAME = {'utilization': 'cpu_util'}
ALARM_COMPARISON_OPERATOR = {'greater_than': 'gt', 'gerater_equal': 'ge',
'less_than': 'lt', 'less_equal': 'le',
'equal': 'eq', 'not_equal': 'ne'}
ALARM_STATISTIC = {'mean': 'mean', 'median': 'median', 'summary': 'sum',
'maximum': 'max', 'minimum': 'min', 'last': 'last',
'std': 'std', 'first': 'first', 'count': 'count'}
class ToscaClusterAutoscaling(HotResource):
'''Translate TOSCA node type tosca.policies.Scaling.Cluster'''
toscatype = 'tosca.policies.Scaling.Cluster'
def __init__(self, policy, csar_dir=None):
hot_type = "OS::Senlin::Policy"
super(ToscaClusterAutoscaling, self).__init__(policy,
type=hot_type,
csar_dir=csar_dir)
self.policy = policy
def _generate_scale_properties(self,
target_cluster_nodes,
cluster_scale_type):
properties = {}
bindings = []
policy_res = {}
adjustment = {}
properties["type"] = SCALE_POLICY
for cluster_node in target_cluster_nodes:
bindings.append({'cluster': cluster_node})
properties["bindings"] = bindings
policy_res["event"] = cluster_scale_type
adjustment["type"] = "CHANGE_IN_CAPACITY"
adjustment["number"] = self.\
policy.entity_tpl["properties"]["increment"]
policy_res["adjustment"] = adjustment
properties["properties"] = policy_res
return properties
def handle_expansion(self):
hot_resources = []
hot_type = 'OS::Aodh::GnocchiAggregationByResourcesAlarm'
trigger_receivers = defaultdict(list)
for node in self.policy.properties['targets']:
for trigger in self.policy.entity_tpl['triggers']:
for action in self.policy.\
entity_tpl['triggers'][trigger]['action']:
scale_name = action
action_sample = self.policy.\
entity_tpl['triggers'][trigger]['action'][action]
scale_type = action_sample['type']
scale_implement = action_sample['implementation']
(entity, method) = scale_implement.split('.')
receiver_prop = {}
receiver_prop['cluster'] = {
"get_resource": "%s_cluster" % node
}
receiver_prop['action'] = SCALE_TYPE[scale_type]
receiver_prop['type'] = method
receiver_name = node + '_' + scale_name + '_receiver'
trigger_receivers[trigger].append(receiver_name)
receiver_resources = HotResource(self.nodetemplate,
type='OS::Senlin::Receiver',
name=receiver_name,
properties=receiver_prop)
hot_resources.append(receiver_resources)
for trigger in self.policy.entity_tpl['triggers']:
sample = self.policy.\
entity_tpl['triggers'][trigger]['condition']
(meter_name, comparison_operator, threshold) = \
sample["constraint"].split()
threshold = threshold.strip("%")
alarm_prop = {}
alarm_prop["description"] = self.policy.entity_tpl['description']
alarm_prop["metric"] = self.policy.\
entity_tpl['triggers'][trigger]['event_type']['metric']
alarm_prop["aggregation_method"] = \
ALARM_STATISTIC[sample['aggregation_method']]
alarm_prop["granularity"] = sample["granularity"]
alarm_prop["evaluation_periods"] = sample["evaluations"]
alarm_prop["threshold"] = threshold
alarm_prop["resource_type"] = sample.get("resource_type",
"instance")
alarm_prop["comparison_operator"] = \
ALARM_COMPARISON_OPERATOR[comparison_operator]
alarm_prop["repeat_actions"] = "True"
alarm_prop["alarm_actions"] = []
for index in range(len(trigger_receivers[trigger])):
alarm_prop["alarm_actions"].\
append({'get_attr': [trigger_receivers[trigger][index],
'channel',
'alarm_url']})
ceilometer_resources = HotResource(self.nodetemplate,
type=hot_type,
name=trigger + '_alarm',
properties=alarm_prop)
hot_resources.append(ceilometer_resources)
return hot_resources
def handle_properties(self, resources):
remove_resources = []
networks = defaultdict(list)
for index, resource in enumerate(resources):
if resource.type == 'OS::Neutron::Port':
for hot_resource in resource.depends_on_nodes:
if hot_resource.type != 'OS::Neutron::Net':
networks[hot_resource.name].\
append(
{'network': '%s' % resource.properties['network']}
)
remove_resources.append(resource)
elif resource.type == 'OS::Neutron::Net':
remove_resources.append(resource)
elif resource.name in self.policy.properties['targets'] and \
resource.type != 'OS::Senlin::Policy':
props = {}
del resource.properties['user_data_format']
del resource.properties['networks']
props['type'] = SERVER_TYPE
props['properties'] = resource.properties
profile_resources = \
HotResource(resource,
type='OS::Senlin::Profile',
name=resource.name,
properties=props)
resources.pop(index)
resources.insert(index, profile_resources)
for remove_resource in remove_resources:
resources.remove(remove_resource)
for index, resource in enumerate(resources):
if resource.name in self.policy.properties['targets']:
resource.properties['properties']['networks'] = \
networks[resource.name]
for node in self.policy.properties['targets']:
props = {}
props["profile"] = {'get_resource': '%s' % node}
temp = self.policy.entity_tpl["properties"]
props["min_size"] = temp["min_instances"]
props["max_size"] = temp["max_instances"]
props["desired_capacity"] = temp["default_instances"]
self.cluster_name = '%s_cluster' % node
cluster_resources = \
HotResource(self.nodetemplate,
type='OS::Senlin::Cluster',
name=self.cluster_name,
properties=props)
resources.append(cluster_resources)
trigger_num = len(self.policy.entity_tpl['triggers'])
for num, trigger in enumerate(self.policy.entity_tpl['triggers']):
target_cluster_nodes = []
for action in self.policy.\
entity_tpl['triggers'][trigger]['action']:
scale_type = self.policy.\
entity_tpl['triggers'][trigger]['action'][action]['type']
for node in self.policy.properties['targets']:
target_cluster_nodes.\
append({"get_resource": "%s_cluster" % node})
cluster_scale_type = SCALE_TYPE[scale_type]
scale_in_props = \
self._generate_scale_properties(target_cluster_nodes,
cluster_scale_type)
if num == trigger_num - 1:
self.name = self.name + '_' + trigger
self.properties = scale_in_props
break
policy_resources = \
HotResource(self.nodetemplate,
type='OS::Senlin::Policy',
name=self.name + '_' + trigger,
properties=scale_in_props)
resources.append(policy_resources)
return resources
|
python
|
import json
from dejavu import Dejavu
from dejavu.logic.recognizer.file_recognizer import FileRecognizer
from dejavu.logic.recognizer.microphone_recognizer import MicrophoneRecognizer
# load config from a JSON file (or anything outputting a python dictionary)
config = {
"database": {
"host": "db",
"user": "postgres",
"password": "password",
"database": "dejavu"
},
"database_type": "postgres"
}
if __name__ == '__main__':
# create a Dejavu instance
djv = Dejavu(config)
# Fingerprint all the mp3's in the directory we give it
djv.fingerprint_directory("test", [".wav"])
# Recognize audio from a file
results = djv.recognize(FileRecognizer, "mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
print(f"From file we recognized: {results}\n")
# Or use a recognizer without the shortcut, in anyway you would like
recognizer = FileRecognizer(djv)
results = recognizer.recognize_file("mp3/Josh-Woodward--I-Want-To-Destroy-Something-Beautiful.mp3")
print(f"No shortcut, we recognized: {results}\n")
results = djv.recognize(FileRecognizer, "test/sean_secs.wav")
print(f"self: {results}\n")
|
python
|
#!/usr/bin/env python
# coding: utf-8
# # Exercises 9: Functions
#
# There are some tricky questions in here - don't be afraid to ask for help. You might find it useful to work out a rough structure or process on paper before going to code.
#
# ## Task 1: Regular functions
#
# 1. Write a function to find the maximum of three numbers
# In[14]:
# Solution
# This is a 'helper' function that will help the main function
def max_of_two(x, y) :
if x > y :
return x
return y
# Main function - finds max of two, then finds max of that max and the third number
def max_of_three(x, y, z) :
return max_of_two(x, max_of_two(y, z))
print(max_of_three(31, 67, -10))
# 2. Write a function that sums all numbers in a list
# In[15]:
# Solution
def sum(numbers_list) :
total = 0 # Initialise this to zero - it'll end up as the result
for x in numbers_list :
total += x # Increase the total sum by each element in the list
return total
print(sum([1, 2, 5, 10, 25]))
# 3. Write a function that reverses a string
#
# E.g. "123abcde" becomes "edcba321".
# Hint: you can use `len(string)` as the starting index and work backwards
# In[16]:
# Solution
def string_reverse(string) :
rev_string = "" # initialise an empty string
index = len(string) # Start by looking at the last element
while index > 0 :
rev_string += string[index - 1]
index -= 1 # Decrease index to move backwards through the string
return rev_string
string = "123abcde"
print(string)
print(string_reverse(string))
# ## Task 2: Recursive Functions
#
# For the next three exercises, try thinking first about your base case and then your recursive case. Write your code on paper first if it helps!
#
# 1. Write a functio called `recursive_exponent(base, exp)` that takes a `base` and an `exp` as parameters and _recursively_ computes base ^ exp. You are not allowed to use the `**` operator!
# In[17]:
# Solution
def recursive_exponent(base, exp):
# Base case 1 - this is how we know we're finished recursing
if exp == 1:
return base
else:
return base * recursive_exponent(base, exp - 1)
print("2^6 =", recursive_exponent(2, 6))
# 2. Write a function called `recursive_countdown(n)` that uses recursion to print numbers from `n` to `0`, where `n` will be a positive integer parameter.
# In[18]:
# Solution
def recursive_countdown(n):
# Base case 0 - how we know we're finished recursing
if n == 0:
print(n)
else:
print(n, end=', ')
recursive_countdown(n-1)
recursive_countdown(10)
# # Task 3: Higher-Order Function
#
# A higher-order function is a function that either contains other functions as parameters or returns a function as an output.
#
# For this exercise, we will write a function named `apply_fun_on_dict(a, my_fun)`. This function will apply a given function `my_fun` on the values of the dictionary `a`. For example, it could calculate the square of each value.
#
# The function `my_fun` that we want to apply to the dictionary in the main function will be defined as:
# ```python
# def my_fun(element):
# return element**2
# ```
#
# Then, the dictionary `a` will be:
# ```python
# a = {"apple": 6,
# "banana": 2,
# "hello": 5,
# "world": 4}
# ```
# and so `apply_fun_on_dict(a, my_fun)` should give the result `{"apple": 36, "banana": 4, "hello": 25, "world": 16}`.
# In[19]:
# Solution
def apply_fun_on_dict(a, my_fun):
return {k: my_fun(v) for k, v in a.items()}
def my_fun(n):
return n**2
a = {'apple': 6, 'banana': 2, 'hello': 5, 'world': 4}
print(apply_fun_on_dict(a, my_fun))
# In[ ]:
|
python
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common Webapp2 handlers."""
import cgi
import functools
import httplib
from inspect import isclass
import logging
import sys
import traceback
import webapp2
from google.appengine.api import modules
from upvote.gae.shared.common import json_utils
from upvote.gae.shared.common import utils
_COMMON_ERROR_CODES = [
httplib.BAD_REQUEST, httplib.FORBIDDEN, httplib.NOT_FOUND,
httplib.INTERNAL_SERVER_ERROR]
def _HtmlEscape(s):
"""Escape a string to make it HTML-safe."""
return cgi.escape(s, quote=True).replace("'", ''')
def RecordRequest(original_function):
"""Decorator function to increment RequestCounter on response success."""
# functools.wraps restores the original properties of the wrapped function.
# This is useful for debugging and tracing.
@functools.wraps(original_function)
def _RecordRequest(handler, *args, **kwargs):
"""Wraps `original_function` to increment RequestCounter after calling.
The call to `original_function` should cause all intentional or
unintentional errors to raise an exception:
* Intentional errors should be indicated with the abort call and will be
caught with the registered ErrorHandler for the application.
* Unintentional errors will be caught by the `handle_exception` handler
Each of these handlers will increment the proper status values on
RequestCounter.
Args:
handler: The handler's `self` argument
*args: The args to be passed to original_function
**kwargs: The kwargs to be passed to original_function
Returns:
A wrapped version of `original_function`
"""
ret = original_function(handler, *args, **kwargs)
handler.RequestCounter.Increment(handler.response.status_int)
return ret
return _RecordRequest
class UpvoteRequestHandler(webapp2.RequestHandler):
"""Base class for all Upvote RequestHandlers."""
@property
def RequestCounter(self):
"""Returns a monitoring.RequestCounter specific to this webapp2.RequestHandler.
Subclasses should override this method in order to enable monitoring of
requests made to this RequestHandler.
Returns:
A monitoring.RequestCounter to be used for tracking requests to this
RequestHandler.
"""
return None
@property
def json_encoder(self):
if not hasattr(self, '_json_encoder'):
self._json_encoder = json_utils.JSONEncoder()
return self._json_encoder
def handle_exception(self, exception, unused_debug_mode):
"""Handle any uncaught exceptions.
Args:
exception: The exception that was thrown.
unused_debug_mode: True if the application is running in debug mode.
"""
# Default to a 500.
http_status = httplib.INTERNAL_SERVER_ERROR
# Calls to abort() raise a child class of HTTPException, so extract the
# HTTP status and explanation if possible.
if isinstance(exception, webapp2.HTTPException):
http_status = getattr(exception, 'code', httplib.INTERNAL_SERVER_ERROR)
# Write out the exception's explanation to the response body
escaped_explanation = _HtmlEscape(str(exception))
self.response.write(escaped_explanation)
# If the RequestHandler has a corresponding request counter, increment it.
if self.RequestCounter is not None:
self.RequestCounter.Increment(http_status)
# If the exception occurs within a unit test, make sure the stacktrace is
# easily discerned from the console.
if not utils.RunningInProd():
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
# Set the response code and log the exception regardless.
self.response.set_status(http_status)
logging.exception(exception)
def respond_json(self, response_data):
try:
response_json = self.json_encoder.encode(response_data)
except TypeError as e:
logging.error('Failed to serialize JSON response: %s', e)
self.abort(httplib.INTERNAL_SERVER_ERROR, 'Failed to serialize response')
else:
self.response.content_type = 'application/json'
self.response.write(response_json)
class AckHandler(webapp2.RequestHandler):
"""Simple handler for responding with HTTP 200."""
def get(self):
self.response.status = httplib.OK
self.response.write('ACK (%s)' % modules.get_current_module_name())
def _GetHandlerFromRequest(request):
"""Safely extracts a request handler from a Request.
Args:
request: A webapp2.Request instance.
Returns:
The handler that corresponds to the given Request (which can be a class or
method), or None if there is no such handler (e.g. 404's).
"""
route = getattr(request, 'route', None)
if route is not None:
return getattr(route, 'handler', None)
def CreateErrorHandler(http_status):
"""Creates a WSGIApplication error handler function for an HTTP status."""
def ErrorHandler(request, response, exception):
"""Error handling method to be registered to WSGIApplication.error_handlers.
Args:
request: A webapp2.Request instance.
response: A webapp2.Response instance.
exception: The uncaught exception.
"""
handler = _GetHandlerFromRequest(request)
# If the target RequestHandler is an UpvoteRequestHandler, see if there's an
# associated RequestCounter and increment it to reflect the error.
if isclass(handler) and issubclass(handler, UpvoteRequestHandler):
request_counter = handler().RequestCounter
if request_counter is not None:
request_counter.Increment(http_status)
response.set_status(http_status)
logging.exception(exception)
raise exception
return ErrorHandler
def CreateErrorHandlersForApplications(
wsgi_apps, error_codes=None):
"""Helper method for creating error handlers for the given HTTP statuses.
Args:
wsgi_apps: A list of webapp2.WSGIApplication instances.
error_codes: A list of HTTP status integers to create error handlers for.
"""
error_codes = _COMMON_ERROR_CODES if error_codes is None else error_codes
for wsgi_app in wsgi_apps:
for error_code in error_codes:
wsgi_app.error_handlers[error_code] = CreateErrorHandler(error_code)
|
python
|
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from deperceiver.models.debug_model import DebugModel
if __name__ == '__main__':
model = DebugModel()
wandb_logger = WandbLogger(
name='debug_cifar',
project='DePerceiver',
log_model=True,
entity='deperceiver',
)
trainer = Trainer(
gpus=4,
accelerator='ddp',
logger=wandb_logger,
gradient_clip_val=10,
)
wandb_logger.watch(model)
trainer.fit(model)
|
python
|
def img_to_encoding(image_path, model):
# loading the image with resizing the image
img = load_img(image_path, target_size=(160, 160))
print('\nImage data :',img)
print("\nImage Data :",img.shape)
# converting the img data in the form of pixcel values
img = np.around(np.array(img) / 255.0, decimals=12)
print('\nImage pixcel value :',img)
print("\nImage pixcel shape :",img.shape)
# expanding the dimension for making the image to fit for the input
x_train = np.expand_dims(img, axis=0)
print('\nx_train :',x_train)
print("\nx_train shape :",x_train.shape)
# predicting the embedding of the image by passing the image to the model
embedding = model.predict(x_train)
print('\nEmbedding :',embedding)
print('\nEmbedding shape :',embedding.shape)
# linalg.norm - used to calculate one of the eight different matrix norms or vector norms
# linalg - used to return the eigenvalues and eigenvectors of a real symmetric matrix.
embedding = embedding / np.linalg.norm(embedding, ord=2)
print('\nEmbedding :',embedding)
print('\nEmbedding shape :',embedding.shape)
return embedding
# importing the database in the program as a dict datatype
face_database = {}
# listdir - used to get the list of all files and directories in the specified directory.
for folder_name in os.listdir('database'):
print('\nfolder_name :',folder_name)
# path.join - concatenates various path components with exactly one directory separator ('/')
for image_name in os.listdir(os.path.join('database',folder_name)): # database/foldder_name
print('\nimage_name :',image_name)
# splitext - used to split the path name into a pair root and extension.
# basename - used to get the base name in specified path
user_name = os.path.splitext(os.path.basename(image_name))
print('\nUser name : \n',user_name)
# img_to_encoding - used to get the face embedding for a image
face_database[user_name] = img_to_encoding(os.path.join('database',folder_name,image_name), model)
print(face_database)
|
python
|
from styx_msgs.msg import TrafficLight
from keras.models import load_model
import cv2
import numpy as np
import tensorflow as tf
import os
import rospy
from PIL import Image
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
class TLSimClassifier(object):
def __init__(self):
#TODO load classifier
model_file = DIR_PATH + '/models/sim-classifier-8.h5'
self.model = load_model(DIR_PATH + '/models/sim-classifier-8.h5')
rospy.loginfo("TLSimClassifier load model %s" , model_file)
self.model._make_predict_function()
self.graph = tf.get_default_graph()
self.light_state = TrafficLight.UNKNOWN
def get_state_string(self, state):
if (state == 0):
state_s = "RED"
elif (state == 1):
state_s = "YELLOW"
elif (state == 2):
state_s = "GREEN"
else:
state_s = "UNKNOWN"
return state_s
def get_classification(self, image):
"""Determines the color of the traffic light in the image
Args:
image (cv::Mat): image containing the traffic light
Returns:
int: ID of traffic light color (specified in styx_msgs/TrafficLight)
"""
#TODO implement light color prediction
classification_tl_key = {0: TrafficLight.RED, 1: TrafficLight.YELLOW, 2: TrafficLight.GREEN, 4: TrafficLight.UNKNOWN}
resized = cv2.resize(image, (80,60))/255.
test_img = np.array([resized])
# run the prediction
with self.graph.as_default():
model_predict = self.model.predict(test_img)
if model_predict[0][np.argmax(model_predict[0])] > 0.5:
self.light_state = classification_tl_key[np.argmax(model_predict[0])]
return self.light_state
def transfer_image_into_numpy_array(self, image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# Simple test
def _main(_):
flags = tf.app.flags.FLAGS
image_path = flags.input_image
model_path = flags.model_path
simulator = flags.simulator
print 'image_path=', image_path
print 'model_path=', model_path
print 'simulator=', simulator
image = Image.open(image_path)
image.show()
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
classifier = TLSimClassifier()
image_np = classifier.transfer_image_into_numpy_array(image)
classification = classifier.get_classification(image_np)
state_s = classifier.get_state_string(classification)
print(state_s)
if __name__ == '__main__':
flags = tf.app.flags
flags.DEFINE_string('input_image', 'light2.jpeg', 'Path to input image')
flags.DEFINE_string('model_path', 'models/ssd_mobilenet_v1_coco_2018_01_28', 'Path to the second model')
flags.DEFINE_bool('simulator', False, 'Whether image is coming from a simulator or not')
tf.app.run(main=_main)
|
python
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import galaxy.main.fields
import galaxy.main.mixins
class Migration(migrations.Migration):
dependencies = [('main', '0049_auto_20161013_1744')]
operations = [
migrations.CreateModel(
name='Video',
fields=[
(
'id',
models.AutoField(
verbose_name='ID',
serialize=False,
auto_created=True,
primary_key=True,
),
),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
(
'description',
galaxy.main.fields.TruncatingCharField(
default=b'', max_length=255, blank=True
),
),
('active', models.BooleanField(default=True, db_index=True)),
('url', models.CharField(unique=True, max_length=256)),
],
options={'verbose_name': 'videos'},
bases=(models.Model, galaxy.main.mixins.DirtyMixin),
),
migrations.AddField(
model_name='role',
name='videos',
field=models.ManyToManyField(
related_name='videos',
verbose_name=b'videos',
editable=False,
to='main.Video',
blank=True,
),
),
]
|
python
|
from __future__ import annotations
import numpy as np
from bqskitrs import Circuit as Circ
from bqskit.ir.circuit import Circuit
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
def check_gradient(circ: Circuit, num_params: int) -> None:
totaldiff = [0] * num_params
eps = 1e-5
repeats = 100
for _ in range(repeats):
v = np.random.rand(num_params) * 2 * np.pi
M, Js = circ.get_unitary_and_grad(v)
for i in range(num_params):
v2 = np.copy(v)
v2[i] = v[i] + eps
U1 = circ.get_unitary(v2)
if isinstance(U1, UnitaryMatrix):
utry1 = U1
else:
utry1 = U1
v2[i] = v[i] - eps
U2 = circ.get_unitary(v2)
if isinstance(U2, UnitaryMatrix):
utry2 = U2
else:
utry2 = U2
FD = (utry1 - utry2) / (2 * eps)
diffs = np.sum(np.abs(FD - Js[i]))
totaldiff[i] += diffs
for i in range(num_params):
assert totaldiff[i] < eps
def test_gradients(r3_qubit_circuit: Circuit) -> None:
check_gradient(r3_qubit_circuit, r3_qubit_circuit.num_params)
def test_gradients_native(r3_qubit_circuit: Circuit) -> None:
circ = Circ(r3_qubit_circuit)
check_gradient(circ, r3_qubit_circuit.num_params)
|
python
|
"""WMEL diagrams."""
# --- import --------------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
# --- define --------------------------------------------------------------------------------------
# --- subplot -------------------------------------------------------------------------------------
class Subplot:
"""Subplot containing WMEL."""
def __init__(
self,
ax,
energies,
number_of_interactions=4,
title="",
title_font_size=16,
state_names=None,
virtual=[None],
state_font_size=14,
state_text_buffer=0.5,
label_side="left",
):
"""Subplot.
Parameters
----------
ax : matplotlib axis
The axis.
energies : 1D array-like
Energies (scaled between 0 and 1)
number_of_interactions : integer
Number of interactions in diagram.
title : string (optional)
Title of subplot. Default is empty string.
state_names: list of str (optional)
list of the names of the states
virtual: list of ints (optional)
list of indexes of any vitual energy states
state_font_size: numtype (optional)
font size for the state lables
state_text_buffer: numtype (optional)
space between the energy level bars and the state labels
"""
self.ax = ax
self.energies = energies
self.interactions = number_of_interactions
self.state_names = state_names
# Plot Energy Levels
for i in range(len(self.energies)):
if i in virtual:
linestyle = "--"
else:
linestyle = "-"
self.ax.axhline(self.energies[i], color="k", linewidth=2, ls=linestyle, zorder=5)
# add state names
if isinstance(state_names, list):
for i in range(len(self.energies)):
if label_side == "left":
ax.text(
-state_text_buffer,
energies[i],
state_names[i],
fontsize=state_font_size,
verticalalignment="center",
horizontalalignment="center",
)
elif label_side == "right":
ax.text(
1 + state_text_buffer,
energies[i],
state_names[i],
fontsize=state_font_size,
verticalalignment="center",
horizontalalignment="center",
)
# calculate interaction_positons
self.x_pos = np.linspace(0, 1, number_of_interactions)
# set limits
self.ax.set_xlim(-0.1, 1.1)
self.ax.set_ylim(-0.01, 1.01)
# remove guff
self.ax.axis("off")
# title
self.ax.set_title(title, fontsize=title_font_size)
def add_arrow(
self,
index,
between,
kind,
label="",
head_length=10,
head_aspect=1,
font_size=14,
color="k",
):
"""Add an arrow to the WMEL diagram.
Parameters
----------
index : integer
The interaction, or start and stop interaction for the arrow.
between : 2-element iterable of integers
The inital and final state of the arrow
kind : {'ket', 'bra'}
The kind of interaction.
label : string (optional)
Interaction label. Default is empty string.
head_length: number (optional)
size of arrow head
font_size : number (optional)
Label font size. Default is 14.
color : matplotlib color (optional)
Arrow color. Default is black.
Returns
-------
[line,arrow_head,text]
"""
if hasattr(index, "index"):
x_pos = list(index)
else:
x_pos = [index] * 2
x_pos = [np.linspace(0, 1, self.interactions)[i] for i in x_pos]
y_pos = [self.energies[between[0]], self.energies[between[1]]]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
elif arrow_length < 0:
direction = -1
else:
raise ValueError("between invalid!")
length = abs(y_pos[0] - y_pos[1])
if kind == "ket":
line = self.ax.plot(x_pos, y_pos, linestyle="-", color=color, linewidth=2, zorder=9)
elif kind == "bra":
line = self.ax.plot(x_pos, y_pos, linestyle="--", color=color, linewidth=2, zorder=9)
elif kind == "out":
yi = np.linspace(y_pos[0], y_pos[1], 100)
xi = (
np.sin((yi - y_pos[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40
+ x_pos[0]
)
line = self.ax.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt", zorder=9
)
else:
raise ValueError("kind is not 'ket', 'out', or 'bra'.")
# add arrow head
dx = x_pos[1] - x_pos[0]
dy = y_pos[1] - y_pos[0]
xytext = (x_pos[1] - dx * 1e-2, y_pos[1] - dy * 1e-2)
annotation = self.ax.annotate(
"",
xy=(x_pos[1], y_pos[1]),
xytext=xytext,
arrowprops=dict(
fc=color,
ec=color,
shrink=0,
headwidth=head_length * head_aspect,
headlength=head_length,
linewidth=0,
zorder=10,
),
size=25,
)
# add text
text = self.ax.text(
np.mean(x_pos), -0.15, label, fontsize=font_size, horizontalalignment="center"
)
return line, annotation.arrow_patch, text
# --- artist --------------------------------------------------------------------------------------
class Artist:
"""Dedicated WMEL figure artist."""
def __init__(
self,
size,
energies,
state_names=None,
number_of_interactions=4,
virtual=[None],
state_font_size=8,
state_text_buffer=0.5,
):
"""Initialize.
Parameters
----------
size : [rows, collumns]
Layout.
energies : list of numbers
State energies.
state_names : list of strings (optional)
State names. Default is None.
number_of_interactions : integer (optional)
Number of interactions. Default is 4.
virtual : list of integers (optional)
Indices of states which are virtual. Default is [None].
state_font_size : number (optional)
State font size. Default is 8.
state_text_buffer : number (optional)
Size of buffer around state text. Default is 0.5.
"""
# create figure
figsize = [int(size[0] * ((number_of_interactions + 1.0) / 6.0)), size[1] * 2.5]
fig, (subplots) = plt.subplots(size[1], size[0], figsize=figsize)
self.fig = fig
# wrap subplots if need be
if size == [1, 1]:
self.subplots = np.array([[subplots]])
plt.subplots_adjust(left=0.3)
elif size[1] == 1:
self.subplots = np.array([subplots])
else:
self.subplots = subplots
# add energy levels
self.energies = energies
for plot in self.subplots.flatten():
for i in range(len(self.energies)):
if i in virtual:
linestyle = "--"
else:
linestyle = "-"
plot.axhline(energies[i], color="k", linewidth=2, linestyle=linestyle)
# add state names to leftmost plots
if state_names:
for i in range(size[1]):
plot = self.subplots[i][0]
for j in range(len(self.energies)):
plot.text(
-state_text_buffer,
energies[j],
state_names[j],
fontsize=state_font_size,
verticalalignment="center",
horizontalalignment="center",
)
# calculate interaction_positons
self.x_pos = np.linspace(0, 1, number_of_interactions)
# plot cleans up a bunch - call it now as well as later
self.plot()
def label_rows(self, labels, font_size=15, text_buffer=1.5):
"""Label rows.
Parameters
----------
labels : list of strings
Labels.
font_size : number (optional)
Font size. Default is 15.
text_buffer : number
Buffer around text. Default is 1.5.
"""
for i in range(len(self.subplots)):
plot = self.subplots[i][-1]
plot.text(
text_buffer,
0.5,
labels[i],
fontsize=font_size,
verticalalignment="center",
horizontalalignment="center",
)
def label_columns(self, labels, font_size=15, text_buffer=1.15):
"""Label columns.
Parameters
----------
labels : list of strings
Labels.
font_size : number (optional)
Font size. Default is 15.
text_buffer : number
Buffer around text. Default is 1.5.
"""
for i in range(len(labels)):
plot = self.subplots[0][i]
plot.text(
0.5,
text_buffer,
labels[i],
fontsize=font_size,
verticalalignment="center",
horizontalalignment="center",
)
def clear_diagram(self, diagram):
"""Clear diagram.
Parameters
----------
diagram : [column, row]
Diagram to clear.
"""
plot = self.subplots[diagram[1]][diagram[0]]
plot.cla()
def add_arrow(
self, diagram, number, between, kind, label="", head_length=0.075, font_size=7, color="k"
):
"""Add arrow.
Parameters
----------
diagram : [column, row]
Diagram position.
number : integer
Arrow position.
between : [start, stop]
Arrow span.
kind : {'ket', 'bra', 'out'}
Arrow style.
label : string (optional)
Arrow label. Default is ''.
head_length : number (optional)
Arrow head length. Default 0.075.
font_size : number (optional)
Font size. Default is 7.
color : matplotlib color
Arrow color. Default is 'k'.
Returns
-------
list
[line, arrow_head, text]
"""
column, row = diagram
x_pos = self.x_pos[number]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
y_poss = [self.energies[between[0]], self.energies[between[1]] - head_length]
elif arrow_length < 0:
direction = -1
y_poss = [self.energies[between[0]], self.energies[between[1]] + head_length]
else:
raise ValueError("Variable between invalid")
subplot = self.subplots[row][column]
# add line
length = abs(y_poss[0] - y_poss[1])
if kind == "ket":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="-", color=color, linewidth=2)
elif kind == "bra":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="--", color=color, linewidth=2)
elif kind == "out":
yi = np.linspace(y_poss[0], y_poss[1], 100)
xi = (
np.sin((yi - y_poss[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40 + x_pos
)
line = subplot.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt"
)
# add arrow head
arrow_head = subplot.arrow(
self.x_pos[number],
arrow_end - head_length * direction,
0,
0.0001 * direction,
head_width=head_length * 2,
head_length=head_length,
fc=color,
ec=color,
linestyle="solid",
linewidth=0,
)
# add text
text = subplot.text(
self.x_pos[number], -0.1, label, fontsize=font_size, horizontalalignment="center"
)
return line, arrow_head, text
def plot(self, save_path=None, close=False, bbox_inches="tight", pad_inches=1):
"""Plot figure.
Parameters
----------
save_path : string (optional)
Save path. Default is None.
close : boolean (optional)
Toggle automatic figure closure after plotting.
Default is False.
bbox_inches : number (optional)
Bounding box size, in inches. Default is 'tight'.
pad_inches : number (optional)
Pad inches. Default is 1.
"""
# final manipulations
for plot in self.subplots.flatten():
# set limits
plot.set_xlim(-0.1, 1.1)
plot.set_ylim(-0.1, 1.1)
# remove guff
plot.axis("off")
# save
if save_path:
plt.savefig(
save_path,
transparent=True,
dpi=300,
bbox_inches=bbox_inches,
pad_inches=pad_inches,
)
# close
if close:
plt.close()
|
python
|
import torch.utils.data as data
import cv2
import numpy as np
import math
from lib.utils import data_utils
from pycocotools.coco import COCO
import os
from lib.utils.tless import tless_utils, visualize_utils, tless_config
from PIL import Image
import glob
class Dataset(data.Dataset):
def __init__(self, ann_file, split):
super(Dataset, self).__init__()
self.split = split
self.coco = COCO(ann_file)
self.anns = np.array(self.coco.getImgIds())
self.anns = self.anns[:500] if split == 'mini' else self.anns
self.json_category_id_to_contiguous_id = {v: i for i, v in enumerate(self.coco.getCatIds())}
def read_original_data(self, img_id):
ann_ids = self.coco.getAnnIds(imgIds=img_id)
annos = self.coco.loadAnns(ann_ids)
path = self.coco.loadImgs(int(img_id))[0]['rgb_path']
img = cv2.imread(path)
boxes = [anno['bbox'] for anno in annos]
category_ids = [anno['category_id'] for anno in annos]
cls_ids = [self.json_category_id_to_contiguous_id[category_id] for category_id in category_ids]
return img, boxes, cls_ids
def prepare_detection(self, box, ct_hm, cls_id, wh, ct_cls, ct_ind):
ct_hm = ct_hm[cls_id]
ct_cls.append(cls_id)
x_min, y_min, x_max, y_max = box
ct = np.array([(x_min + x_max) / 2, (y_min + y_max) / 2], dtype=np.float32)
ct = np.round(ct).astype(np.int32)
h, w = y_max - y_min, x_max - x_min
radius = data_utils.gaussian_radius((math.ceil(h), math.ceil(w)))
radius = max(0, int(radius))
data_utils.draw_umich_gaussian(ct_hm, ct, radius)
wh.append([w, h])
ct_ind.append(ct[1] * ct_hm.shape[1] + ct[0])
x_min, y_min = ct[0] - w / 2, ct[1] - h / 2
x_max, y_max = ct[0] + w / 2, ct[1] + h / 2
decode_box = [x_min, y_min, x_max, y_max]
return decode_box
def __getitem__(self, index):
img_id = self.anns[index]
img, bboxes, cls_ids = self.read_original_data(img_id)
orig_img, inp, trans_input, trans_output, center, scale, inp_out_hw = \
tless_utils.augment(img, self.split)
bboxes = tless_utils.transform_bbox(bboxes, trans_output, inp_out_hw[2], inp_out_hw[3])
output_h, output_w = inp_out_hw[2:]
ct_hm = np.zeros([30, output_h, output_w], dtype=np.float32)
wh = []
ct_cls = []
ct_ind = []
bboxes_ = []
for i in range(len(bboxes)):
cls_id = cls_ids[i]
bbox = bboxes[i]
if bbox[2] == bbox[0] or bbox[3] == bbox[1]:
continue
bboxes_.append(bbox)
self.prepare_detection(bbox, ct_hm, cls_id, wh, ct_cls, ct_ind)
ret = {'inp': inp}
detection = {'ct_hm': ct_hm, 'wh': wh, 'ct_cls': ct_cls, 'ct_ind': ct_ind}
ret.update(detection)
# visualize_utils.visualize_detection(orig_img, ret)
ct_num = len(ct_ind)
meta = {'center': center, 'scale': scale, 'ct_num': ct_num}
ret.update({'meta': meta})
return ret
def __len__(self):
return len(self.anns)
|
python
|
"""
Proxy discovery operations
"""
import os
import socket
import logging
import functools
from contextlib import closing
from dataclasses import dataclass
from typing import Mapping, Tuple, List
from urllib.parse import urlparse
from nspawn import CONFIG
logger = logging.getLogger(__name__)
@dataclass
class ProxyConfig:
entry_map:Mapping[str, str]
def key_for(self, scheme:str) -> str:
return f"{scheme.lower()}_proxy"
def key_for_no(self) -> str:
return self.key_for('no')
def no_proxy(self) -> str:
return self.entry_map.get(self.key_for_no(), None)
def has_no_proxy(self) -> bool:
return self.key_for_no() in self.entry_map
def with_no_proxy(self, entry:str) -> None:
self.entry_map[self.key_for_no()] = entry
def proxy_for(self, scheme:str) -> str:
return self.entry_map.get(self.key_for(scheme), None)
def has_proxy_for(self, scheme:str) -> bool:
return self.key_for(scheme) in self.entry_map
def with_proxy_for(self, scheme:str , entry:str) -> None:
self.entry_map[self.key_for(scheme)] = entry.lower()
def into_entry_list(self) -> List[str]:
return [f"{key}={value}" for key, value in self.entry_map.items()]
def verify_proxy_connect(url:str) -> bool:
urlbean = urlparse(url)
host = urlbean.hostname
port = urlbean.port
addr = (host, port)
timeout = float(CONFIG['proxy']['socket_timeout'])
result = False
try:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as channel:
channel.settimeout(timeout)
channel.connect(addr)
result = True
except:
result = False
logger.debug(f"verify_proxy: {addr} result: {result}")
return result
@functools.lru_cache(maxsize=1) # load once per session
def discover_proxy_config() -> ProxyConfig:
proxy_config = ProxyConfig(dict())
proxy_check_list = CONFIG.get_list('proxy', 'proxy_check_list')
proxy_config_text = CONFIG['proxy']['proxy_config_text']
def apply_config(entry_text: str) -> None:
entry_list = entry_text.splitlines()
for entry in entry_list:
if not '=' in entry:
continue
entry = entry.lower().strip()
key, value = entry.split('=', 1)
key, value = (key.strip(), value.strip())
if key == 'no_proxy':
proxy_config.with_no_proxy(value)
elif key.endswith('_proxy'):
scheme = key.replace('_proxy', '')
if proxy_config.has_proxy_for(scheme):
pass
elif verify_proxy_connect(value):
proxy_config.with_proxy_for(scheme, value)
else:
continue
for proxy_check in proxy_check_list:
if proxy_check == 'user':
apply_config(os.popen('env').read())
elif proxy_check == 'root':
apply_config(os.popen('sudo env').read())
elif proxy_check == 'config':
apply_config(proxy_config_text)
else:
raise RuntimeError(f"Invalid proxy check: {proxy_check}")
logger.debug(f"proxy_config: {proxy_config}")
return proxy_config
|
python
|
"""
Partition the numbers using a very simple round-robin algorithm.
Programmer: Erel Segal-Halevi
Since: 2022-02
"""
from typing import Callable, List, Any
from prtpy import outputtypes as out, objectives as obj, Bins
def roundrobin(
bins: Bins,
items: List[any],
valueof: Callable[[Any], float] = lambda x: x,
):
"""
Partition the given items using the roundrobin number partitioning algorithm.
>>> from prtpy.bins import BinsKeepingContents, BinsKeepingSums
>>> roundrobin(BinsKeepingContents(2), items=[1,2,3,3,5,9,9]).bins
[[9, 5, 3, 1], [9, 3, 2]]
>>> roundrobin(BinsKeepingContents(3), items=[1,2,3,3,5,9,9]).bins
[[9, 3, 1], [9, 3], [5, 2]]
>>> list(roundrobin(BinsKeepingContents(3), items=[1,2,3,3,5,9,9]).sums)
[13.0, 12.0, 7.0]
>>> from prtpy import partition
>>> partition(algorithm=roundrobin, numbins=3, items={"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9})
[['f', 'c', 'a'], ['g', 'd'], ['e', 'b']]
>>> partition(algorithm=roundrobin, numbins=2, items={"a":1, "b":2, "c":3, "d":3, "e":5, "f":9, "g":9}, outputtype=out.Sums)
array([18., 14.])
"""
ibin = 0
for item in sorted(items, key=valueof, reverse=True):
bins.add_item_to_bin(item, ibin)
ibin = (ibin+1) % bins.num
return bins
if __name__ == "__main__":
import doctest
(failures, tests) = doctest.testmod(report=True)
print("{} failures, {} tests".format(failures, tests))
|
python
|
import cv2
import dlib
import threading
import numpy as np
from keras.models import load_model
from scipy.spatial import distance as dist
from imutils import face_utils
import sys
from tensorflow import Graph, Session
import utils.logging_data as LOG
'''
Blink frequence, This file predicts blinking
Make sure models are reachable!
Code assumes from:
https://github.com/iparaskev/simple-blink-detector
'''
from keras import backend as K
# Blink detector
# Class that calcualte blink frequence
#
class Blink_frequency(threading.Thread):
index = 0
# Initiate thread
# parameters name , shared_variables reference
#
def __init__(self, name = None, shared_variables = None, index = 0 ):
threading.Thread.__init__(self)
self.name = name
self.shared_variables = shared_variables
self.index = index
# make this run at correct time
def run(self):
LOG.info("Start blink frequency "+ str(self.index), "SYSTEM-"+self.shared_variables.name)
# load model
model = load_model('../../model/blinkModel.hdf5')
close_counter = blinks = mem_counter= 0
state = ''
#Wait for detection
while self.shared_variables.frame[self.index] is None:
pass
while self.shared_variables.system_running is not None:
if self.shared_variables.frame[self.index] is not None:
frame = self.shared_variables.frame[self.index]
eyes = self.cropEyes(frame)
if eyes is None:
continue
else:
left_eye,right_eye = eyes
prediction = (model.predict(self.cnnPreprocess(left_eye)) + model.predict(self.cnnPreprocess(right_eye)))/2.0
if prediction > 0.5 :
state = 'open'
close_counter = 0
else:
state = 'close'
close_counter += 1
if state == 'open' and mem_counter > 1:
blinks += 1
mem_counter = close_counter
#save blinking
#eye_state
self.shared_variables.eye_state[self.index] = state
#blinks
self.shared_variables.blinks[self.index] = blinks
#eye_left
self.shared_variables.eye_left[self.index] = left_eye
#eye_right
self.shared_variables.eye_right[self.index] = right_eye
if self.shared_variables.debug:
LOG.debug(str(state) + " " + str(blinks) + " from "+str(self.index),"SYSTEM-"+self.shared_variables.name)
LOG.info("Ending blink freq " + str(self.index), "SYSTEM-"+self.shared_variables.name)
# make the image to have the same format as at training
def cnnPreprocess(self,img):
img = img.astype('float32')
img /= 255
img = np.expand_dims(img, axis=2)
img = np.expand_dims(img, axis=0)
return img
def cropEyes(self,frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
shape = self.shared_variables.landmarks[self.index]
#Only for dlib
if len(shape) < 10 :
return
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
l_uppery = min(leftEye[1:3,1])
l_lowy = max(leftEye[4:,1])
l_dify = abs(l_uppery - l_lowy)
lw = (leftEye[3][0] - leftEye[0][0])
minxl = (leftEye[0][0] - ((34-lw)/2))
maxxl = (leftEye[3][0] + ((34-lw)/2))
minyl = (l_uppery - ((26-l_dify)/2))
maxyl = (l_lowy + ((26-l_dify)/2))
left_eye_rect = np.rint([minxl, minyl, maxxl, maxyl])
left_eye_rect = left_eye_rect.astype(int)
left_eye_image = gray[(left_eye_rect[1]):left_eye_rect[3], (left_eye_rect[0]):left_eye_rect[2]]
r_uppery = min(rightEye[1:3,1])
r_lowy = max(rightEye[4:,1])
r_dify = abs(r_uppery - r_lowy)
rw = (rightEye[3][0] - rightEye[0][0])
minxr = (rightEye[0][0]-((34-rw)/2))
maxxr = (rightEye[3][0] + ((34-rw)/2))
minyr = (r_uppery - ((26-r_dify)/2))
maxyr = (r_lowy + ((26-r_dify)/2))
right_eye_rect = np.rint([minxr, minyr, maxxr, maxyr])
right_eye_rect = right_eye_rect.astype(int)
right_eye_image = gray[right_eye_rect[1]:right_eye_rect[3], right_eye_rect[0]:right_eye_rect[2]]
if 0 in left_eye_image.shape or 0 in right_eye_image.shape:
return None
left_eye_image = cv2.resize(left_eye_image, (34, 26))
right_eye_image = cv2.resize(right_eye_image, (34, 26))
right_eye_image = cv2.flip(right_eye_image, 1)
return left_eye_image, right_eye_image
|
python
|
import sys
import argparse
import os
import re
import yaml
from . import workflow
class Runner(object):
tasks = [
]
out_and_cache_subfolder_with_sumatra_label = True
def run(self):
parser = argparse.ArgumentParser(description='Run workflow')
parser.add_argument('config_path', type=str)
parser.add_argument('--workdir', type=str, default=None)
parser.add_argument('--out', type=str, default=None)
parser.add_argument('--cache', type=str, default=None)
parser.add_argument('--range', type=str, default=None)
args = parser.parse_args()
config = self._load_config(args.config_path)
out_path = args.out
cache_path = args.cache
if self.out_and_cache_subfolder_with_sumatra_label and 'sumatra_label' in config:
if out_path:
out_path = os.path.join(out_path, config['sumatra_label'])
if cache_path:
cache_path = os.path.join(cache_path, config['sumatra_label'])
tasks = []
if args.range:
single_id_match = re.match(r'^(\d*)$', args.range)
start_end_match = re.match(r'^(\d*)-(\d*)$', args.range)
if single_id_match is not None:
tasks = [int(single_id_match.group(1))]
elif start_end_match is not None:
start = int(start_end_match.group(1))
end = int(start_end_match.group(2))
if end >= start:
tasks = [x for x in range(start, end + 1)]
wf = workflow.Workflow(config, available_tasks=self._get_task_dictionary(), work_dir=args.workdir, output_path=out_path,
cache_path=cache_path)
wf.run(tasks_to_execute=tasks)
def _get_task_dictionary(self):
return {k.name: k for k in self.tasks}
def _load_config(self, path):
with open(path, 'r') as yml_file:
cfg = yaml.load(yml_file)
return cfg
|
python
|
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2018 Nortxort
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from datetime import datetime
import aioconsole
try:
# try importing optional module.
from colorama import init, Style, Fore
init(autoreset=True)
class Color:
"""
Predefined colorama colors.
"""
RED = Fore.RED
GREEN = Fore.GREEN
YELLOW = Fore.YELLOW
CYAN = Fore.CYAN
MAGENTA = Fore.MAGENTA
BLUE = Fore.BLUE
WHITE = Fore.WHITE
B_RED = Style.BRIGHT + RED
B_GREEN = Style.BRIGHT + GREEN
B_YELLOW = Style.BRIGHT + YELLOW
B_CYAN = Style.BRIGHT + CYAN
B_MAGENTA = Style.BRIGHT + MAGENTA
B_BLUE = Style.BRIGHT + BLUE
RESET = Style.RESET_ALL
except ImportError:
# importing failed, use dummies
init = None
Style = None
Fore = None
class Color:
"""
Dummy class in case importing colorama failed.
"""
RED = ''
GREEN = ''
YELLOW = ''
CYAN = ''
MAGENTA = ''
BLUE = ''
WHITE = ''
B_RED = ''
B_GREEN = ''
B_YELLOW = ''
B_CYAN = ''
B_MAGENTA = ''
B_BLUE = ''
RESET = ''
class Console:
"""
A class for reading and writing to console.
"""
def __init__(self, loop, clock_color='',
use24hour=True, log=False, log_path=''):
self._loop = loop
self._clock_color = clock_color
self._use24hour = use24hour
self._chat_logging = log # not sure
self._log_path = log_path # not sure
async def input(self, prompt):
"""
Asynchronous input.
:param prompt: Input prompt.
:type prompt: str
"""
return await aioconsole.ainput(prompt, loop=self._loop)
def write(self, text, color='', *, ts=True):
"""
Writes text to console.
:param text: The text to write.
:type text: str
:param color: Optional Color
:type color: str
:param ts: Show a timestamp before the text.
:type ts: bool
"""
time_stamp = ''
if ts:
time_stamp = f'[{_ts(as24hour=self._use24hour)}] '
txt = f'{self._clock_color}{time_stamp}{Color.RESET}{color}{text}'
print(txt)
def _ts(as24hour=False):
"""
Timestamp in the format HH:MM:SS
NOTE: milliseconds is included for the 24 hour format.
:param as24hour: Use 24 hour time format.
:type as24hour: bool
:return: A string representing the time.
:rtype: str
"""
now = datetime.utcnow()
fmt = '%I:%M:%S:%p'
if as24hour:
fmt = '%H:%M:%S:%f'
ts = now.strftime(fmt)
if as24hour:
return ts[:-3]
return ts
|
python
|
import json
from dotenv import load_dotenv
from os import getenv
from plex_trakt_sync.path import config_file, env_file, default_config_file
from os.path import exists
class Config(dict):
env_keys = [
"PLEX_BASEURL",
"PLEX_FALLBACKURL",
"PLEX_TOKEN",
"PLEX_USERNAME",
"TRAKT_USERNAME",
]
initialized = False
def __getitem__(self, item):
if not self.initialized:
self.initialize()
return dict.__getitem__(self, item)
def initialize(self):
if not exists(config_file):
with open(default_config_file, "r") as fp:
defaults = json.load(fp)
with open(config_file, "w") as fp:
fp.write(json.dumps(defaults, indent=4))
with open(config_file, "r") as fp:
config = json.load(fp)
self.update(config)
self.initialized = True
load_dotenv()
if not getenv("PLEX_TOKEN") or not getenv("TRAKT_USERNAME"):
print("First run, please follow those configuration instructions.")
from get_env_data import get_env_data
get_env_data()
load_dotenv()
for key in self.env_keys:
self[key] = getenv(key)
def save(self):
with open(env_file, "w") as txt:
txt.write("# This is .env file for PlexTraktSync\n")
for key in self.env_keys:
if key in self:
txt.write("{}={}\n".format(key, self[key]))
else:
txt.write("{}=\n".format(key))
CONFIG = Config()
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.