class Encapsulada:

    atributo_visible = 'soy visible'
    _atributo_protegido = 'soy protegido'
    __atributo_privado = 'soy un atributo privado'

    def get_atributo_privado(self):
        return self.__atributo_privado

    def set_atributo_privado(self, cambio):
        self.__atributo_privado = cambio


# coding: utf-8

"""
    NetBox API

    API to access NetBox  # noqa: E501

    OpenAPI spec version: 2.8

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import unittest

import netbox_client
from netbox_client.models.writable_front_port import WritableFrontPort  # noqa: E501
from netbox_client.rest import ApiException

class TestWritableFrontPort(unittest.TestCase):
    """WritableFrontPort unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def testWritableFrontPort(self):
        """Test WritableFrontPort"""
        # FIXME: construct object with mandatory attributes with example values
        # model = netbox_client.models.writable_front_port.WritableFrontPort()  # noqa: E501
        pass

if __name__ == '__main__':
    unittest.main()


from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class lsp_admin_group_include_all(PybindBase):
  """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module brocade-mpls - based on the path /brocade_mpls_rpc/show-mpls-lsp-debug/output/lsp/show-mpls-lsp-debug-info/show-mpls-lsp-common-info/lsp-config-frr-admin-groups/lsp-admin-group/lsp-admin-group-include-all. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.
  """
  __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__lsp_admin_group_include_all_group_id',)

  _yang_name = 'lsp-admin-group-include-all'
  _rest_name = 'lsp-admin-group-include-all'

  _pybind_generated_by = 'container'

  def __init__(self, *args, **kwargs):

    path_helper_ = kwargs.pop("path_helper", None)
    if path_helper_ is False:
      self._path_helper = False
    elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
      self._path_helper = path_helper_
    elif hasattr(self, "_parent"):
      path_helper_ = getattr(self._parent, "_path_helper", False)
      self._path_helper = path_helper_
    else:
      self._path_helper = False

    extmethods = kwargs.pop("extmethods", None)
    if extmethods is False:
      self._extmethods = False
    elif extmethods is not None and isinstance(extmethods, dict):
      self._extmethods = extmethods
    elif hasattr(self, "_parent"):
      extmethods = getattr(self._parent, "_extmethods", None)
      self._extmethods = extmethods
    else:
      self._extmethods = False
    self.__lsp_admin_group_include_all_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-all-group-id", rest_name="lsp-admin-group-include-all-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)

    load = kwargs.pop("load", None)
    if args:
      if len(args) > 1:
        raise TypeError("cannot create a YANG container with >1 argument")
      all_attr = True
      for e in self._pyangbind_elements:
        if not hasattr(args[0], e):
          all_attr = False
          break
      if not all_attr:
        raise ValueError("Supplied object did not have the correct attributes")
      for e in self._pyangbind_elements:
        nobj = getattr(args[0], e)
        if nobj._changed() is False:
          continue
        setmethod = getattr(self, "_set_%s" % e)
        if load is None:
          setmethod(getattr(args[0], e))
        else:
          setmethod(getattr(args[0], e), load=load)

  def _path(self):
    if hasattr(self, "_parent"):
      return self._parent._path()+[self._yang_name]
    else:
      return [u'brocade_mpls_rpc', u'show-mpls-lsp-debug', u'output', u'lsp', u'show-mpls-lsp-debug-info', u'show-mpls-lsp-common-info', u'lsp-config-frr-admin-groups', u'lsp-admin-group', u'lsp-admin-group-include-all']

  def _rest_path(self):
    if hasattr(self, "_parent"):
      if self._rest_name:
        return self._parent._rest_path()+[self._rest_name]
      else:
        return self._parent._rest_path()
    else:
      return [u'show-mpls-lsp-debug', u'output', u'lsp', u'lsp-config-frr-admin-groups', u'lsp-admin-group-include-all']

  def _get_lsp_admin_group_include_all_group_id(self):
    """
    Getter method for lsp_admin_group_include_all_group_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_debug/output/lsp/show_mpls_lsp_debug_info/show_mpls_lsp_common_info/lsp_config_frr_admin_groups/lsp_admin_group/lsp_admin_group_include_all/lsp_admin_group_include_all_group_id (uint32)

    YANG Description: Include all admin group id
    """
    return self.__lsp_admin_group_include_all_group_id

  def _set_lsp_admin_group_include_all_group_id(self, v, load=False):
    """
    Setter method for lsp_admin_group_include_all_group_id, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_debug/output/lsp/show_mpls_lsp_debug_info/show_mpls_lsp_common_info/lsp_config_frr_admin_groups/lsp_admin_group/lsp_admin_group_include_all/lsp_admin_group_include_all_group_id (uint32)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_lsp_admin_group_include_all_group_id is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_lsp_admin_group_include_all_group_id() directly.

    YANG Description: Include all admin group id
    """
    parent = getattr(self, "_parent", None)
    if parent is not None and load is False:
      raise AttributeError("Cannot set keys directly when" +
                             " within an instantiated list")

    if hasattr(v, "_utype"):
      v = v._utype(v)
    try:
      t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-all-group-id", rest_name="lsp-admin-group-include-all-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)
    except (TypeError, ValueError):
      raise ValueError({
          'error-string': """lsp_admin_group_include_all_group_id must be of a type compatible with uint32""",
          'defined-type': "uint32",
          'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-all-group-id", rest_name="lsp-admin-group-include-all-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)""",
        })

    self.__lsp_admin_group_include_all_group_id = t
    if hasattr(self, '_set'):
      self._set()

  def _unset_lsp_admin_group_include_all_group_id(self):
    self.__lsp_admin_group_include_all_group_id = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="lsp-admin-group-include-all-group-id", rest_name="lsp-admin-group-include-all-group-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='uint32', is_config=True)

  lsp_admin_group_include_all_group_id = __builtin__.property(_get_lsp_admin_group_include_all_group_id, _set_lsp_admin_group_include_all_group_id)

  _pyangbind_elements = {'lsp_admin_group_include_all_group_id': lsp_admin_group_include_all_group_id, }


from __future__ import absolute_import
import pynndescent
from ann_benchmarks.algorithms.base import BaseANN

class PyNNDescent(BaseANN):
    def __init__(self, metric, n_neighbors=10, n_trees=8, leaf_size=20):
        self._n_neighbors = int(n_neighbors)
        self._n_trees = int(n_trees)
        self._leaf_size = int(leaf_size)
        self._queue_size=None
        self._pynnd_metric = {'angular': 'cosine',
                              'euclidean': 'euclidean',
                              'hamming': 'hamming',
                              'jaccard': 'jaccard'}[metric]

    def fit(self, X):
            self._index = pynndescent.NNDescent(X,
                                                n_neighbors=self._n_neighbors,
                                                n_trees=self._n_trees,
                                                leaf_size=self._leaf_size,
                                                metric=self._pynnd_metric)

    def set_query_arguments(self, queue_size):
        self._queue_size = float(queue_size)

    def query(self, v, n):
        ind, dist = self._index.query(v.reshape(1, -1).astype('float32'), k=n, queue_size=self._queue_size)
        return ind[0]

    def use_threads(self):
        return False

    def __str__(self):
        return 'PyNNDescent(n_neighbors=%d, n_trees=%d, leaf_size=%d, queue_size=%.2f)' % (self._n_neighbors,
                                                                                self._n_trees,
                                                                                self._leaf_size,
                                                                                self._queue_size)


import os
import json
import uuid

import boto3

from datasources.stac.query import STACQuery
from datasources.sources.base import Datasource

client = boto3.client('s3')
bucket = 'usgs-lidar-public'

class USGS3DEP(Datasource):

    stac_compliant = False
    tags = ['Elevation', 'Raster']

    def __init__(self, manifest):
        super().__init__(manifest)

    def search(self, spatial, temporal=None, properties=None, limit=10, **kwargs):
        from db import Database

        names = []
        stac_query = STACQuery(spatial, temporal, properties)
        # projects = stac_query.check_spatial(self.__class__.__name__)[:limit]

        with Database.load(read_only=True, deployed=True) as db:
            projects = db.spatial_query({"type": "Feature", "geometry": stac_query.spatial})

        searches = 0
        for item in projects:
            if item['name'] not in names:
                if temporal and item['year']:
                    if stac_query.temporal[0].year != item['year'] or stac_query.temporal[1].year != item['year']:
                        continue

                if properties:
                    item.update({'properties': stac_query})

                if searches < limit:
                    self.manifest.searches.append([self, item])
                    searches+=1

        # searches = 0
        # for item in projects:
        #     if item['name'] not in names:
        #     # Temporal check by checking year of start/end date
        #         if temporal and item['year']:
        #             if stac_query.temporal[0].year == item['year'] or stac_query.temporal[1].year == item['year']:
        #                 if properties:
        #                     item.update({'properties': stac_query})
        #                 self.manifest.searches.append([self, item])
        #                 names.append(item['name'])
        #         else:
        #             self.manifest.searches.append([self, item])
        #             names.append(item['name'])

    def execute(self, query):
        # Download metadata from query item
        response = client.get_object(Bucket=bucket, Key=os.path.join(query['name'], 'ept.json'))
        metadata = json.loads(response['Body'].read().decode('utf-8'))

        xvals = [x[0] for x in query['geometry']['coordinates'][0]]
        yvals = [y[1] for y in query['geometry']['coordinates'][0]]

        stac_item = {
            'id': str(uuid.uuid4()),
            'type': 'Feature',
            'bbox': [min(xvals), min(yvals), max(xvals), max(yvals)],
            'geometry': query['geometry'],
            'properties': {
                'datetime': f"{query['year']}-01-01T00:00:00.00Z",
                'eo:epsg': metadata['srs']['horizontal'],
                'pc:count': metadata['points'],
                'pc:type': 'lidar',
                'pc:encoding': metadata['dataType'],
                'pc:schema': metadata['schema'],
                'legacy:span': metadata['span'],
                'legacy:version': metadata['version'],
            },
            'assets': {
                's3path': {
                    'href': f"s3://{bucket}/{query['name']}",
                    'title': 'EPT data'
                }
            },
        }

        if "properties" in list(query):
            if query['properties'].check_properties(stac_item['properties']):
                return [stac_item]
        else:
            return [stac_item]


import re
import collections

from enum import Enum

from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,     REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION

from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns

_meta_table = {
    'HistRecordEnum' : _MetaInfoEnum('HistRecordEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper',
        {
            'cfghist-bag-record-all':'cfghist_bag_record_all',
            'cfghist-bag-record-alarm':'cfghist_bag_record_alarm',
            'cfghist-bag-record-cfs-check':'cfghist_bag_record_cfs_check',
            'cfghist-bag-record-commit':'cfghist_bag_record_commit',
            'cfghist-bag-record-oir':'cfghist_bag_record_oir',
            'cfghist-bag-record-shutdown':'cfghist_bag_record_shutdown',
            'cfghist-bag-record-startup':'cfghist_bag_record_startup',
            'cfghist-bag-record-backup':'cfghist_bag_record_backup',
            'cfghist-bag-record-rebase':'cfghist_bag_record_rebase',
            'cfghist-bag-record-last':'cfghist_bag_record_last',
        }, 'Cisco-IOS-XR-config-cfgmgr-exec-oper', _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper']),
    'CfgHistGl.RecordType.Record.Info.AlarmInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.AlarmInfo',
            False,
            [
            _MetaInfoClassMember('state', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                State
                ''',
                'state',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('where', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Where
                ''',
                'where',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'alarm-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.CfscheckInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.CfscheckInfo',
            False,
            [
            _MetaInfoClassMember('line', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Line
                ''',
                'line',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('user-id', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                UserId
                ''',
                'user_id',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'cfscheck-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.CommitInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.CommitInfo',
            False,
            [
            _MetaInfoClassMember('client-name', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Client name
                ''',
                'client_name',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('comment', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Comment
                ''',
                'comment',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('commit-id', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                CommitId
                ''',
                'commit_id',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('label', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Label
                ''',
                'label',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('line', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Line
                ''',
                'line',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('user-id', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                UserId
                ''',
                'user_id',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'commit-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.OirInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.OirInfo',
            False,
            [
            _MetaInfoClassMember('config-name', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Config Name
                ''',
                'config_name',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('config-type', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Config Type
                ''',
                'config_type',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('operation', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Operation
                ''',
                'operation',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'oir-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.ShutdownInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.ShutdownInfo',
            False,
            [
            _MetaInfoClassMember('comment', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Comment
                ''',
                'comment',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'shutdown-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.StartupInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.StartupInfo',
            False,
            [
            _MetaInfoClassMember('boot-path', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Boot Path
                ''',
                'boot_path',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('how-booted', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                How Booted
                ''',
                'how_booted',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'startup-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info.BackupInfo' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info.BackupInfo',
            False,
            [
            _MetaInfoClassMember('comment', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                Comment
                ''',
                'comment',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'backup-info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record.Info' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record.Info',
            False,
            [
            _MetaInfoClassMember('a', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                B
                ''',
                'a',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('alarm-info', REFERENCE_CLASS, 'AlarmInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.AlarmInfo',
                [], [],
                '''                alarm info
                ''',
                'alarm_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('backup-info', REFERENCE_CLASS, 'BackupInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.BackupInfo',
                [], [],
                '''                backup info
                ''',
                'backup_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('cfscheck-info', REFERENCE_CLASS, 'CfscheckInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.CfscheckInfo',
                [], [],
                '''                cfscheck info
                ''',
                'cfscheck_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('commit-info', REFERENCE_CLASS, 'CommitInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.CommitInfo',
                [], [],
                '''                commit info
                ''',
                'commit_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('oir-info', REFERENCE_CLASS, 'OirInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.OirInfo',
                [], [],
                '''                oir info
                ''',
                'oir_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('shutdown-info', REFERENCE_CLASS, 'ShutdownInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.ShutdownInfo',
                [], [],
                '''                shutdown info
                ''',
                'shutdown_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('startup-info', REFERENCE_CLASS, 'StartupInfo' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info.StartupInfo',
                [], [],
                '''                startup info
                ''',
                'startup_info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('type', REFERENCE_ENUM_CLASS, 'HistRecordEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'HistRecordEnum',
                [], [],
                '''                type
                ''',
                'type',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'info',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType.Record' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType.Record',
            False,
            [
            _MetaInfoClassMember('record', ATTRIBUTE, 'int' , None, None,
                [('-2147483648', '2147483647')], [],
                '''                Record
                ''',
                'record',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', True),
            _MetaInfoClassMember('info', REFERENCE_CLASS, 'Info' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record.Info',
                [], [],
                '''                Content of the history
                ''',
                'info',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('record-type', REFERENCE_ENUM_CLASS, 'HistRecordEnum' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'HistRecordEnum',
                [], [],
                '''                Record type
                ''',
                'record_type',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            _MetaInfoClassMember('timestamp', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                Time stamp for the history
                ''',
                'timestamp',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'record',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl.RecordType' : {
        'meta_info' : _MetaInfoClass('CfgHistGl.RecordType',
            False,
            [
            _MetaInfoClassMember('record-type', ATTRIBUTE, 'str' , None, None,
                [], ['[\\w\\-\\.:,_@#%$\\+=\\|;]+'],
                '''                Record type
                ''',
                'record_type',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', True),
            _MetaInfoClassMember('record', REFERENCE_LIST, 'Record' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType.Record',
                [], [],
                '''                History summary information for a specific type
                of history
                ''',
                'record',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'record-type',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
    'CfgHistGl' : {
        'meta_info' : _MetaInfoClass('CfgHistGl',
            False,
            [
            _MetaInfoClassMember('record-type', REFERENCE_LIST, 'RecordType' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper', 'CfgHistGl.RecordType',
                [], [],
                '''                History summary information for a specific type
                of history
                ''',
                'record_type',
                'Cisco-IOS-XR-config-cfgmgr-exec-oper', False),
            ],
            'Cisco-IOS-XR-config-cfgmgr-exec-oper',
            'cfg-hist-gl',
            _yang_ns._namespaces['Cisco-IOS-XR-config-cfgmgr-exec-oper'],
        'ydk.models.cisco_ios_xr.Cisco_IOS_XR_config_cfgmgr_exec_oper'
        ),
    },
}
_meta_table['CfgHistGl.RecordType.Record.Info.AlarmInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.CfscheckInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.CommitInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.OirInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.ShutdownInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.StartupInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info.BackupInfo']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info']
_meta_table['CfgHistGl.RecordType.Record.Info']['meta_info'].parent =_meta_table['CfgHistGl.RecordType.Record']['meta_info']
_meta_table['CfgHistGl.RecordType.Record']['meta_info'].parent =_meta_table['CfgHistGl.RecordType']['meta_info']
_meta_table['CfgHistGl.RecordType']['meta_info'].parent =_meta_table['CfgHistGl']['meta_info']


from __future__ import absolute_import
# Copyright (c) 2010-2018 openpyxl

"""Write the shared string table."""
from io import BytesIO

# package imports
from openpyxl2.xml.constants import SHEET_MAIN_NS
from openpyxl2.xml.functions import Element, xmlfile, SubElement

PRESERVE_SPACE = '{%s}space' % "http://www.w3.org/XML/1998/namespace"

def write_string_table(string_table):
    """Write the string table xml."""
    out = BytesIO()

    with xmlfile(out) as xf:
        with xf.element("sst", xmlns=SHEET_MAIN_NS, uniqueCount="%d" % len(string_table)):

            for key in string_table:
                el = Element('si')
                text = SubElement(el, 't')
                text.text = key
                if key.strip() != key:
                    text.set(PRESERVE_SPACE, 'preserve')
                xf.write(el)

    return  out.getvalue()


"""
Building Block
==============

"""

from __future__ import annotations

import logging
import os
import typing
import warnings
from collections.abc import Collection
from functools import partial

import numpy as np
import rdkit.Chem.AllChem as rdkit
import vabene

from ...utilities import OneOrMany, flatten, remake
from ..atoms import Atom
from ..bonds import Bond
from ..functional_groups import FunctionalGroup, FunctionalGroupFactory
from .molecule import Molecule

logger = logging.getLogger(__name__)

class BuildingBlock(Molecule):
    """
    Represents a building block of a :class:`.ConstructedMolecule`.

    A :class:`BuildingBlock` can represent either an entire molecule or
    a molecular fragments used to construct a
    :class:`.ConstructedMolecule`. The building block uses
    :class:`.FunctionalGroup` instances to identify which atoms are
    modified during construction.

    """

    # Maps file extensions to functions which can be used to
    # create an rdkit molecule from that file type.
    _init_funcs = {
        '.mol': partial(
            rdkit.MolFromMolFile,
            sanitize=False,
            removeHs=False
        ),

        '.sdf': partial(
            rdkit.MolFromMolFile,
            sanitize=False,
            removeHs=False
        ),

        '.pdb': partial(
            rdkit.MolFromPDBFile,
            sanitize=False,
            removeHs=False,
            proximityBonding=False,
        ),
    }

    _placer_ids: frozenset[int]
    _core_ids: frozenset[int]

    def __init__(
        self,
        smiles: str,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
        position_matrix: typing.Optional[np.ndarray] = None,
    ) -> None:
        """
        Initialize a :class:`.BuildingBlock`.

        Notes:

            The molecule is given 3D coordinates with
            :func:`rdkit.ETKDGv2`.

        Parameters:

            smiles:
                A SMILES string of the molecule.

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

            position_matrix:
                The position matrix the building block should use. If
                ``None``, :func:`rdkit.ETKDGv2` will be used to
                calculate it.

        Raises:

            :class:`RuntimeError`
                If embedding the molecule fails.

        """

        molecule = rdkit.AddHs(rdkit.MolFromSmiles(smiles))
        if position_matrix is None:
            params = rdkit.ETKDGv2()
            random_seed = 4
            params.randomSeed = random_seed
            if rdkit.EmbedMolecule(molecule, params) == -1:
                raise RuntimeError(
                    f'Embedding with seed value of {random_seed} '
                    'failed.'
                )
            rdkit.Kekulize(molecule)
        else:
            # Make sure the position matrix always holds floats.
            position_matrix = np.array(
                position_matrix,
                dtype=np.float64,
            )
            conformer = rdkit.Conformer(molecule.GetNumAtoms())
            for atom_id, position in enumerate(position_matrix):
                conformer.SetAtomPosition(atom_id, position)
            molecule.AddConformer(conformer)

        self._init_from_rdkit_mol(
            molecule=molecule,
            functional_groups=functional_groups,
            placer_ids=placer_ids,
        )

    @classmethod
    def init_from_molecule(
        cls,
        molecule: Molecule,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
    ) -> BuildingBlock:
        """
        Initialize from a :class:`.Molecule`.

        Parameters:

            molecule:
                The molecule to initialize from.

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the
                building block, different *placer* ids will be used by
                the building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

        Returns:

             The building block. It will have the same atoms, bonds and
             atomic positions as `molecule`.

        """

        return cls.init(
            atoms=tuple(molecule.get_atoms()),
            bonds=tuple(molecule.get_bonds()),
            position_matrix=molecule.get_position_matrix(),
            functional_groups=functional_groups,
            placer_ids=placer_ids,
        )

    @classmethod
    def init_from_vabene_molecule(
        cls,
        molecule: vabene.Molecule,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
        position_matrix: typing.Optional[np.ndarray] = None,
    ) -> BuildingBlock:
        """
        Initialize from a :mod:`vabene.Molecule`.

        Notes:

            The molecule is given 3D coordinates with
            :func:`rdkit.ETKDGv2()`.

        Parameters:

            molecule:
                The :class:`vabene.Molecule` from which to initialize.

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

            position_matrix:
                The position matrix the building block should use. If
                ``None``, :func:`rdkit.ETKDGv2` will be used to
                calculate it.

        Returns:

             The building block.

        Raises:

            :class:`RuntimeError`
                If embedding the molecule fails.

        """

        editable = rdkit.EditableMol(rdkit.Mol())
        for atom in molecule.get_atoms():
            rdkit_atom = rdkit.Atom(atom.get_atomic_number())
            rdkit_atom.SetFormalCharge(atom.get_charge())
            editable.AddAtom(rdkit_atom)

        for bond in molecule.get_bonds():
            editable.AddBond(
                beginAtomIdx=bond.get_atom1_id(),
                endAtomIdx=bond.get_atom2_id(),
                order=rdkit.BondType(bond.get_order()),
            )

        rdkit_molecule = editable.GetMol()
        rdkit.SanitizeMol(rdkit_molecule)
        rdkit_molecule = rdkit.AddHs(rdkit_molecule)

        if position_matrix is None:
            params = rdkit.ETKDGv2()
            random_seed = 4
            params.randomSeed = random_seed
            if rdkit.EmbedMolecule(rdkit_molecule, params) == -1:
                raise RuntimeError(
                    f'Embedding with seed value of {random_seed} '
                    'failed.'
                )
        else:
            # Make sure the position matrix always holds floats.
            position_matrix = np.array(
                position_matrix,
                dtype=np.float64,
            )
            conformer = rdkit.Conformer(rdkit_molecule.GetNumAtoms())
            for atom_id, position in enumerate(position_matrix):
                conformer.SetAtomPosition(atom_id, position)
            rdkit_molecule.AddConformer(conformer)

        rdkit.Kekulize(rdkit_molecule)
        return cls.init_from_rdkit_mol(
            molecule=rdkit_molecule,
            functional_groups=functional_groups,
            placer_ids=placer_ids,
        )

    @classmethod
    def init(
        cls,
        atoms: tuple[Atom, ...],
        bonds: tuple[Bond, ...],
        position_matrix: np.ndarray,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
    ) -> BuildingBlock:
        """
        Initialize a :class:`.BuildingBlock` from its components.

        Parameters:

            atoms:
                The atoms of the building block.

            bonds:
                The bonds of the building block.

            position_matrix:
                An ``(n, 3)`` position matrix of the building block.

            functional_groups:
                An :class:`iterable` holding the
                :class:`.FunctionalGroup` instances the building block
                should have, and / or :class:`.FunctionalGroupFactory`
                instances used for creating them.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

        Returns:

            The building block.

        """

        building_block = cls.__new__(cls)
        Molecule.__init__(
            self=building_block,
            atoms=atoms,
            bonds=bonds,
            position_matrix=position_matrix,
        )
        functional_groups = building_block._extract_functional_groups(
            functional_groups=functional_groups,
        )
        building_block._with_functional_groups(functional_groups)
        building_block._placer_ids = (
            building_block._normalize_placer_ids(
                placer_ids=placer_ids,
                functional_groups=building_block._functional_groups,
            )
        )
        building_block._core_ids = frozenset(
            building_block._get_core_ids(
                functional_groups=building_block._functional_groups,
            )
        )
        return building_block

    @classmethod
    def init_from_file(
        cls,
        path: str,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
    ):
        """
        Initialize from a file.

        Parameters:

            path:
                The path to a molecular structure file. Supported file
                types are:

                    #. ``.mol``, ``.sdf`` - MDL V3000 MOL file

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

        Returns:

            The building block.

        Raises:

            :class:`ValueError`
                If the file type cannot be used for initialization.

        """

        _, extension = os.path.splitext(path)

        if extension == '.pdb':
            warnings.warn(
                'Loading from .pdb files is deprecated and will be '
                'removed from stk versions released after 1st Nov '
                '2022. Please use .mol files for loading molecules '
                'instead.',
                category=FutureWarning,
            )

        if extension not in cls._init_funcs:
            raise ValueError(
                f'Unable to initialize from "{extension}" files.'
            )
        # This remake needs to be here because molecules loaded
        # with rdkit often have issues, because rdkit tries to do
        # bits of structural analysis like stereocenters. Remake
        # gets rid of all this problematic metadata.
        molecule = remake(cls._init_funcs[extension](path))

        return cls.init_from_rdkit_mol(
            molecule=molecule,
            functional_groups=functional_groups,
            placer_ids=placer_ids,
        )

    @classmethod
    def init_from_rdkit_mol(
        cls,
        molecule: rdkit.Mol,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ] = (),
        placer_ids: typing.Optional[tuple[int, ...]] = None,
    ) -> BuildingBlock:
        """
        Initialize from an :mod:`rdkit` molecule.

        Warnings:

            For :mod:`rdkit` molecules with non-integer bond orders,
            such as 1.5, the molecule should be kekulized prior to
            calling this method. Otherwise, all bond orders will be
            set to an integer value in the building block.

        Parameters:

            molecule:
                The molecule.

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

        Returns:

            The molecule.

        """

        building_block = cls.__new__(cls)
        building_block._init_from_rdkit_mol(
            molecule=molecule,
            functional_groups=functional_groups,
            placer_ids=placer_ids,
        )
        return building_block

    def _init_from_rdkit_mol(
        self,
        molecule: rdkit.Mol,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ],
        placer_ids: typing.Optional[tuple[int, ...]],
    ) -> None:
        """
        Initialize from an :mod:`rdkit` molecule.

        Parameters:

            molecule:
                The molecule.

            functional_groups:
                An :class:`iterable` of :class:`.FunctionalGroup` or
                :class:`.FunctionalGroupFactory` or both.
                :class:`.FunctionalGroup` instances are added to the
                building block and :class:`.FunctionalGroupFactory`
                instances are used to create :class:`.FunctionalGroup`
                instances the building block should hold.
                :class:`.FunctionalGroup` instances are used to
                identify which atoms are modified during
                :class:`.ConstructedMolecule` construction.

            placer_ids:
                The ids of *placer* atoms. These are the atoms which
                should be used for calculating the position of the
                building block. Depending on the values passed to
                `placer_ids`, and the functional groups in the building
                block, different *placer* ids will be used by the
                building block.

                #. `placer_ids` is passed to the initializer: the
                   passed *placer* ids will be used by the building
                   block.

                #. `placer_ids` is ``None`` and the building block has
                   functional groups: The *placer* ids of the
                   functional groups will be used as the *placer* ids
                   of the building block.

                #. `placer_ids` is ``None`` and `functional_groups` is
                   empty. All atoms of the molecule will be used for
                   *placer* ids.

        """

        atoms = tuple(
            Atom(a.GetIdx(), a.GetAtomicNum(), a.GetFormalCharge())
            for a in molecule.GetAtoms()
        )
        bonds = tuple(
            Bond(
                atom1=atoms[b.GetBeginAtomIdx()],
                atom2=atoms[b.GetEndAtomIdx()],
                order=(
                    9 if b.GetBondType() == rdkit.BondType.DATIVE
                    else b.GetBondTypeAsDouble()
                )
            )
            for b in molecule.GetBonds()
        )
        position_matrix = molecule.GetConformer().GetPositions()

        super().__init__(atoms, bonds, position_matrix)
        self._with_functional_groups(self._extract_functional_groups(
            functional_groups=functional_groups,
        ))
        self._placer_ids = self._normalize_placer_ids(
            placer_ids=placer_ids,
            functional_groups=self._functional_groups,
        )
        self._core_ids = frozenset(self._get_core_ids(
            functional_groups=self._functional_groups,
        ))

    def _normalize_placer_ids(
        self,
        placer_ids: typing.Optional[tuple[int, ...]],
        functional_groups: Collection[FunctionalGroup],
    ) -> frozenset[int]:
        """
        Get the final *placer* ids.

        Parameters:

            placer_ids: The ids of *placer* atoms or ``None``.

            functional_groups:
                The :class:`.FunctionalGroup` instances of the building
                block.

        Returns:

            Depending on the input values, this function will return
            different things.

            #. `placer_ids` is a :class:`tuple` of :class`int`: the
                `placer_ids` will be returned.

            #. `placer_ids` is ``None`` and `functional_groups` is not
                empty: The *placer* ids of the functional groups will
                be returned.

            #. `placer_ids` is ``None`` and `functional_groups` is
               empty. The ids of all atoms in the building block will
               be returned.

        """

        if placer_ids is not None:
            return frozenset(placer_ids)

        if functional_groups:
            return frozenset(flatten(
                functional_group.get_placer_ids()
                for functional_group in functional_groups
            ))

        return frozenset(atom.get_id() for atom in self._atoms)

    def _get_core_ids(
        self,
        functional_groups: typing.Iterable[FunctionalGroup],
    ) -> typing.Iterator[int]:
        """
        Get the final *core* ids.

        This method may return duplicate ids.

        Parameters:

            functional_groups:
                The :class:`.FunctionalGroup` instances of the building
                block.

        Yields:

            The id of an atom defining the core of the molecule.

        """

        functional_group_atom_ids = {
            atom_id
            for functional_group in functional_groups
            for atom_id in functional_group.get_atom_ids()
        }
        for atom in self._atoms:
            atom_id = atom.get_id()
            if atom_id not in functional_group_atom_ids:
                yield atom_id

        for functional_group in functional_groups:
            for atom_id in functional_group.get_core_atom_ids():
                yield atom_id

    def _extract_functional_groups(
        self,
        functional_groups: typing.Iterable[
            typing.Union[FunctionalGroup, FunctionalGroupFactory]
        ],
    ) -> typing.Iterator[FunctionalGroup]:
        """
        Yield functional groups.

        The input can be a mixture of :class:`.FunctionalGroup` and
        :class:`.FunctionalGroupFactory`. The output yields
        :class:`.FunctionalGroup` instances only. Either those
        held directly in `functional_groups` or created by the
        factories in `functional_groups`.

        Parameters:

            functional_groups:
                Can be an :class:`iterable` of both
                :class:`.FunctionalGroup` and
                :class:`.FunctionalGroupFactory`.

        Yields:

            A functional group from `functional_groups`, or created
            by a factory in `functional_groups`.

        """

        for functional_group in functional_groups:
            if isinstance(functional_group, FunctionalGroup):
                yield functional_group
            else:
                # Else it's a factory.
                yield from functional_group.get_functional_groups(self)

    def _with_functional_groups(
        self,
        functional_groups: typing.Iterable[FunctionalGroup],
    ) -> BuildingBlock:
        """
        Modify the molecule.

        """

        self._functional_groups = tuple(functional_groups)
        return self

    def with_functional_groups(
        self,
        functional_groups: typing.Iterable[FunctionalGroup],
    ) -> BuildingBlock:
        """
        Return a clone with specific functional groups.

        Parameters:

            functional_groups:
                :class:`.FunctionalGroup` instances which the clone
                should have.

        Returns:

            The clone.

        """

        return self.clone()._with_functional_groups(functional_groups)

    def _with_canonical_atom_ordering(self) -> BuildingBlock:
        ordering = rdkit.CanonicalRankAtoms(self.to_rdkit_mol())
        super()._with_canonical_atom_ordering()
        id_map = {
            old_id: new_id
            for old_id, new_id in enumerate(ordering)
        }
        self._functional_groups = tuple(
            functional_group.with_ids(id_map)
            for functional_group in self._functional_groups
        )
        self._placer_ids = frozenset(
            id_map[placer_id]
            for placer_id in self._placer_ids
        )
        self._core_ids = frozenset(
            id_map[core_id]
            for core_id in self._core_ids
        )
        return self

    def get_num_functional_groups(self) -> int:
        """
        Return the number of functional groups.

        Returns:

            The number of functional groups in the building block.

        """

        return len(self._functional_groups)

    def get_functional_groups(
        self,
        fg_ids: typing.Optional[OneOrMany[int]] = None,
    ) -> typing.Iterator[FunctionalGroup]:
        """
        Yield the functional groups, ordered by id.

        Parameters:

            fg_ids:
                The ids of functional groups yielded. If ``None``, then
                all functional groups are yielded. Can be a single
                :class:`int`, if a single functional group is
                desired.

        Yields:

            A functional group of the building block.

        """

        if fg_ids is None:
            fg_ids = range(len(self._functional_groups))
        elif isinstance(fg_ids, int):
            fg_ids = (fg_ids, )

        for fg_id in fg_ids:
            yield self._functional_groups[fg_id]

    def clone(self) -> BuildingBlock:
        clone = self._clone()
        clone._functional_groups = self._functional_groups
        clone._placer_ids = self._placer_ids
        clone._core_ids = self._core_ids
        return clone

    def get_num_placers(self) -> int:
        """
        Return the number of *placer* atoms in the building block.

        Returns:

            The number of *placer* atoms in the building block.

        """

        return len(self._placer_ids)

    def get_placer_ids(self) -> typing.Iterator[int]:
        """
        Yield the ids of *placer* atoms.

        *Placer* atoms are those, which should be used to calculate
        the position of the building block.

        See Also:

            :meth:`.FunctionalGroup.get_placer_ids`

        Yields:

            The id of a *placer* atom.

        """

        yield from self._placer_ids

    def get_core_atom_ids(self) -> typing.Iterator[int]:
        """
        Yield ids of atoms which form the core of the building block.

        This includes all atoms in the building block not part of a
        functional group, as well as any atoms in a functional group,
        specifically labelled as core atoms.

        See Also:

            :meth:`.FunctionalGroup.get_core_atom_ids`

        Yields:

            The id of a *core* atom.

        """

        yield from self._core_ids

    def with_canonical_atom_ordering(self) -> BuildingBlock:
        return self.clone()._with_canonical_atom_ordering()

    def with_centroid(
        self,
        position: np.ndarray,
        atom_ids: typing.Optional[OneOrMany[int]] = None,
    ) -> BuildingBlock:

        return self.clone()._with_centroid(position, atom_ids)

    def with_displacement(
        self,
        displacement: np.ndarray,
    ) -> BuildingBlock:

        return self.clone()._with_displacement(displacement)

    def with_position_matrix(
        self,
        position_matrix: np.ndarray,
    ) -> BuildingBlock:

        return self.clone()._with_position_matrix(position_matrix)

    def with_rotation_about_axis(
        self,
        angle: float,
        axis: np.ndarray,
        origin: np.ndarray,
    ) -> BuildingBlock:

        return self.clone()._with_rotation_about_axis(
            angle=angle,
            axis=axis,
            origin=origin,
        )

    def with_rotation_between_vectors(
        self,
        start: np.ndarray,
        target: np.ndarray,
        origin: np.ndarray,
    ) -> BuildingBlock:

        return self.clone()._with_rotation_between_vectors(
            start=start,
            target=target,
            origin=origin,
        )

    def with_rotation_to_minimize_angle(
        self,
        start: np.ndarray,
        target: np.ndarray,
        axis: np.ndarray,
        origin: np.ndarray,
    ) -> BuildingBlock:

        return self.clone()._with_rotation_to_minimize_angle(
            start=start,
            target=target,
            axis=axis,
            origin=origin,
        )

    def with_structure_from_file(
        self,
        path: str,
        extension: typing.Optional[str] = None,
    ) -> BuildingBlock:

        return typing.cast(
            BuildingBlock,
            super().with_structure_from_file(
                path=path,
                extension=extension,
            )
        )

    def write(
        self,
        path: str,
        atom_ids: typing.Optional[OneOrMany[int]] = None,
    ) -> BuildingBlock:

        return typing.cast(
            BuildingBlock,
            super().write(path, atom_ids)
        )

    def __str__(self) -> str:
        if self._functional_groups:
            fg_repr = f', {self._functional_groups!r}'
        else:
            fg_repr = ''

        smiles = rdkit.MolToSmiles(
            mol=rdkit.RemoveHs(self.to_rdkit_mol()),
        )
        return f'{self.__class__.__name__}({smiles!r}{fg_repr})'

    def __repr__(self) -> str:
        return str(self)


#!/usr/bin/env python
""" Entry point for starting Galaxy without starting as part of a web server.

Example Usage: Start a job/workflow handler without a web server and with
a given name using.

galaxy-main --server-name handler0

Start as a daemon with (requires daemonized - install with 'pip install daemonize'):

galaxy-main -d --daemon-log-file=handler0-daemon.log --pid-file handler0.pid --server-name handler0

In daemon mode logging of Galaxy (as opposed to this script) is configured via
a loggers section in Galaxy's ini file - this can be overridden with sensible
defaults logging to a single file with the following:

galaxy-main -d --server-name handler0 --daemon-log-file=handler0-daemon.log --pid-file handler0.pid --log-file handler0.log

This can also be used to start Galaxy as a uWSGI mule, e.g. for job handling:

uwsgi ... --py-call-osafterfork --mule=lib/galaxy/main.py --mule=lib/galaxy/main.py --farm=job-handlers:1,2

The --py-call-osafterfork allows for proper shutdown on SIGTERM/SIGINT.
"""
import functools
import logging
import os
import signal
import sys
import threading
from argparse import ArgumentParser
from configparser import ConfigParser
from logging.config import fileConfig

try:
    from daemonize import Daemonize
except ImportError:
    Daemonize = None

try:
    import uwsgi
except ImportError:
    uwsgi = None

log = logging.getLogger(__name__)

real_file = os.path.realpath(__file__)
GALAXY_ROOT_DIR_ = os.path.abspath(os.path.join(os.path.dirname(real_file), os.pardir))
if not os.path.exists(os.path.join(GALAXY_ROOT_DIR_, 'run.sh')):
    # Galaxy is installed
    GALAXY_ROOT_DIR = None
else:
    GALAXY_ROOT_DIR = GALAXY_ROOT_DIR_
    GALAXY_LIB_DIR = os.path.join(GALAXY_ROOT_DIR_, "lib")
    try:
        sys.path.insert(1, GALAXY_LIB_DIR)
    except Exception:
        log.exception("Failed to add Galaxy to sys.path")
        raise
from galaxy.main_config import (
    absolute_config_path,
    config_is_ini,
    DEFAULT_CONFIG_SECTION,
    DEFAULT_INI_APP,
    find_config,
)
from galaxy.util import unicodify
from galaxy.web_stack import get_app_kwds

REQUIRES_DAEMONIZE_MESSAGE = "Attempted to use Galaxy in daemon mode, but daemonize is unavailable."

DEFAULT_PID = "galaxy.pid"
DEFAULT_VERBOSE = True
DESCRIPTION = "Daemonized entry point for Galaxy."

SHUTDOWN_MSG = '__SHUTDOWN__'
UWSGI_FARMS_VAR = '_GALAXY_UWSGI_FARM_NAMES'

exit = threading.Event()

def load_galaxy_app(
    config_builder,
    config_env=False,
    log=None,
    attach_to_pools=None,
    **kwds
):
    # Allow specification of log so daemon can reuse properly configured one.
    if log is None:
        log = logging.getLogger(__name__)

    # If called in daemon mode, set the ROOT directory and ensure Galaxy is on
    # sys.path.
    if config_env:
        try:
            os.chdir(GALAXY_ROOT_DIR)
        except Exception:
            log.exception("Failed to chdir")
            raise

    config_builder.setup_logging()
    from galaxy.util.properties import load_app_properties
    kwds = config_builder.app_kwds()
    kwds = load_app_properties(**kwds)
    from galaxy.app import UniverseApplication
    app = UniverseApplication(
        global_conf=config_builder.global_conf(),
        attach_to_pools=attach_to_pools,
        **kwds
    )
    app.database_heartbeat.start()
    app.application_stack.log_startup()
    return app

def handle_signal(signum, frame):
    log.info('Received signal %d, exiting', signum)
    if uwsgi and 'mule_id' in dir(uwsgi) and uwsgi.mule_id() > 0:
        farms = os.environ.get(UWSGI_FARMS_VAR, None)
        if farms:
            for farm in farms.split(','):
                uwsgi.farm_msg(farm, SHUTDOWN_MSG)
        else:
            uwsgi.mule_msg(SHUTDOWN_MSG, uwsgi.mule_id())
    exit.set()

def register_signals():
    for name in ('TERM', 'INT', 'HUP'):
        sig = getattr(signal, 'SIG%s' % name)
        signal.signal(sig, handle_signal)

def app_loop(args, log):
    try:
        config_builder = GalaxyConfigBuilder(args)
        config_env = GALAXY_ROOT_DIR is not None
        galaxy_app = load_galaxy_app(
            config_builder,
            config_env=config_env,
            log=log,
            attach_to_pools=args.attach_to_pool,
        )
    except BaseException:
        log.exception("Failed to initialize Galaxy application")
        raise
    try:
        # A timeout is required or the signals won't be handled
        while not exit.wait(20):
            pass
    except (KeyboardInterrupt, SystemExit):
        pass
    try:
        galaxy_app.shutdown()
    except Exception:
        log.exception("Failed to shutdown Galaxy application")
        raise

class GalaxyConfigBuilder:
    """ Generate paste-like configuration from supplied command-line arguments.
    """

    def __init__(self, args=None, **kwds):
        self.config_file = None
        self.config_section = None
        self.app_name = kwds.get("app") or (args and args.app) or DEFAULT_CONFIG_SECTION
        config_file = kwds.get("config_file", None) or (args and args.config_file)
        # If given app_conf_path - use that - else we need to ensure we have a
        # config file path.
        if not config_file and 'config_file' in self.app_kwds():
            config_file = self.app_kwds()['config_file']
        if not config_file:
            galaxy_root = kwds.get("galaxy_root", GALAXY_ROOT_DIR)
            config_file = find_config(config_file, galaxy_root)
            config_file = absolute_config_path(config_file, galaxy_root=galaxy_root)
        self.config_file = unicodify(config_file)
        # FIXME: this won't work for non-Paste ini configs
        if self.config_is_ini:
            self.config_section = "app:%s" % unicodify(kwds.get("app") or (args and args.app) or DEFAULT_INI_APP)
        else:
            self.config_section = self.app_name
        self.log_file = (args and args.log_file)

    @classmethod
    def populate_options(cls, arg_parser):
        arg_parser.add_argument("-c", "--config-file", default=None, help="Galaxy config file (defaults to config/galaxy.ini)")
        arg_parser.add_argument("--ini-path", default=None, help="DEPRECATED: use -c/--config-file")
        arg_parser.add_argument("--app", default=None, help="app section in config file (defaults to 'galaxy' for YAML/JSON, 'main' (w/ 'app:' prepended) for INI")
        arg_parser.add_argument("-d", "--daemonize", default=False, help="Daemonize process", action="store_true")
        arg_parser.add_argument("--daemon-log-file", default=None, help="log file for daemon script ")
        arg_parser.add_argument("--log-file", default=None, help="Galaxy log file (overrides log configuration in config_file if set)")
        arg_parser.add_argument("--pid-file", default=DEFAULT_PID, help="pid file (default is %s)" % DEFAULT_PID)
        arg_parser.add_argument("--server-name", default=None, help="set a galaxy server name")
        arg_parser.add_argument("--attach-to-pool", action="append", default=['job-handlers'], help="attach to asynchronous worker pool (specify multiple times for multiple pools)")

    @property
    def config_is_ini(self):
        return config_is_ini(self.config_file)

    def app_kwds(self):
        kwds = get_app_kwds(self.app_name, app_name=self.app_name)
        if 'config_file' not in kwds:
            kwds['config_file'] = self.config_file
        if 'config_section' not in kwds:
            kwds['config_section'] = self.config_section
        return kwds

    def global_conf(self):
        conf = {}
        if self.config_is_ini:
            conf["__file__"] = self.config_file
        return conf

    def setup_logging(self):
        # Galaxy will attempt to setup logging if loggers is not present in
        # ini config file - this handles that loggers block however if present
        # (the way paste normally would)
        if not self.config_file:
            return
        if self.config_is_ini:
            raw_config = ConfigParser()
            raw_config.read([self.config_file])
            if raw_config.has_section('loggers'):
                config_file = os.path.abspath(self.config_file)
                fileConfig(
                    config_file,
                    dict(__file__=config_file, here=os.path.dirname(config_file))
                )

def main(func=app_loop):
    arg_parser = ArgumentParser(description=DESCRIPTION)
    GalaxyConfigBuilder.populate_options(arg_parser)
    args = arg_parser.parse_args()
    if args.ini_path and not args.config_file:
        args.config_file = args.ini_path
    if args.log_file:
        os.environ["GALAXY_CONFIG_LOG_DESTINATION"] = os.path.abspath(args.log_file)
    if args.server_name:
        os.environ["GALAXY_CONFIG_SERVER_NAME"] = args.server_name
    pid_file = args.pid_file

    log.setLevel(logging.DEBUG)
    log.propagate = False
    register_signals()
    if args.daemonize:
        if Daemonize is None:
            raise ImportError(REQUIRES_DAEMONIZE_MESSAGE)

        keep_fds = []
        if args.daemon_log_file:
            fh = logging.FileHandler(args.daemon_log_file, "w")
            fh.setLevel(logging.DEBUG)
            log.addHandler(fh)
            keep_fds.append(fh.stream.fileno())
        else:
            fh = logging.StreamHandler(sys.stderr)
            fh.setLevel(logging.DEBUG)
            log.addHandler(fh)

        daemon = Daemonize(
            app="galaxy",
            pid=pid_file,
            action=functools.partial(func, args, log),
            verbose=DEFAULT_VERBOSE,
            logger=log,
            keep_fds=keep_fds,
        )
        daemon.start()
    else:
        func(args, log)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import sugartensor as tf
import matplotlib.pyplot as plt

# set log level to debug
tf.sg_verbosity(10)

#
# hyper parameters
#

batch_size = 25
z_dim = 50

#
# create generator
#

# random uniform seed
z = tf.random_uniform((batch_size, z_dim))

with tf.sg_context(name='generator', size=5, stride=2, act='relu', bn=True):
    # generator network
    gen = (z.sg_dense(dim=1024)
           .sg_dense(dim=7*7*128)
           .sg_reshape(shape=(-1, 7, 7, 128))
           .sg_upconv(dim=64)
           .sg_upconv(dim=1, act='sigmoid', bn=False)
           .sg_squeeze())

#
# draw samples
#

with tf.Session() as sess:
    tf.sg_init(sess)
    # restore parameters
    saver = tf.train.Saver()
    saver.restore(sess, tf.train.latest_checkpoint('asset/train/ckpt'))

    # run generator
    imgs = sess.run(gen)

    # plot result
    _, ax = plt.subplots(5, 5, sharex=True, sharey=True)
    for i in range(5):
        for j in range(5):
            ax[i][j].imshow(imgs[i * 5 + j], 'gray')
            ax[i][j].set_axis_off()
    plt.savefig('asset/train/sample.png', dpi=600)
    tf.sg_info('Sample image saved to "asset/train/sample.png"')
    plt.close()


# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

from scrapy import Item, Field

# core thinker object
"""thinker item; represents one Wikipedia page, unless no page"""
class Thinker(Item):
    name = Field()
    link = Field()

    # lists of names
    influences = Field()
    influenced = Field()


from arm.logicnode.arm_nodes import *

class RandomBooleanNode(ArmLogicTreeNode):
    """Generates a random boolean."""
    bl_idname = 'LNRandomBooleanNode'
    bl_label = 'Random Boolean'
    arm_version = 1

    def arm_init(self, context):
        self.add_output('ArmBoolSocket', 'Bool')


# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tfx.components.example_gen.utils."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# Standard Imports

import tensorflow as tf
from tfx.components.example_gen import utils

class UtilsTest(tf.test.TestCase):

  def test_get_default_output_config(self):
    output_config = utils.get_default_output_config()
    self.assertEqual(2, len(output_config.split_config.splits))

if __name__ == '__main__':
  tf.test.main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
from shutil import rmtree
from tempfile import mkdtemp

from pelican.generators import ArticlesGenerator
from pelican.tests.support import unittest, get_settings
import sub_parts

CUR_DIR = os.path.dirname(__file__)

class TestSubParts(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.temp_path = mkdtemp(prefix='pelicantests.')
        settings = get_settings(filenames={})
        settings['PATH'] = os.path.join(CUR_DIR, 'test_data')
        settings['AUTHOR'] = 'Me'
        settings['DEFAULT_DATE'] = (1970, 1, 1)
        settings['DEFAULT_CATEGORY'] = 'Default'
        settings['FILENAME_METADATA'] = '(?P<slug>[^.]+)'
        settings['PLUGINS'] = [sub_parts]
        settings['CACHE_CONTENT'] = False
        context = settings.copy()
        context['generated_content'] = dict()
        context['static_links'] = set()
        cls.generator = ArticlesGenerator(
            context=context, settings=settings,
            path=settings['PATH'], theme=settings['THEME'], output_path=cls.temp_path)
        cls.generator.generate_context()
        cls.all_articles = list(cls.generator.articles)
        sub_parts.patch_subparts(cls.generator)

    @classmethod
    def tearDownClass(cls):
        rmtree(cls.temp_path)

    def test_all_articles(self):
        self.assertEqual(
            sorted(['noparent', 'parent',
                    'parent--explicit', 'parent--implicit']),
            sorted([a.slug for a in self.all_articles]))

    def test_articles(self):
        self.assertEqual(
            sorted(['noparent', 'parent']),
            sorted([a.slug for a in self.generator.articles]))

    def test_dates(self):
        self.assertEqual(
            sorted(['noparent', 'parent']),
            sorted([a.slug for a in self.generator.dates]))

    def test_categories(self):
        self.assertEqual(
            sorted(['noparent', 'parent']),
            sorted([a.slug for a in self.generator.categories[0][1]]))

    def test_tags(self):
        self.assertEqual(
            sorted([a.slug for a in self.all_articles]),
            sorted([a.slug for a in self.generator.tags['atag']]))

    def test_authors(self):
        self.assertEqual(
            sorted([a.slug for a in self.all_articles]),
            sorted([a.slug for a in self.generator.authors[0][1]]))

    def test_subparts(self):
        for a in self.all_articles:
            if a.slug == 'parent':
                self.assertTrue(hasattr(a, 'subparts'))
                self.assertEqual(
                    sorted(['parent--explicit', 'parent--implicit']),
                    sorted([a.slug for a in a.subparts]))
            else:
                self.assertFalse(hasattr(a, 'subparts'))

    def test_subpart_of(self):
        for a in self.all_articles:
            if '--' in a.slug:
                self.assertTrue(hasattr(a, 'subpart_of'))
                self.assertEqual('parent', a.subpart_of.slug)
            else:
                self.assertFalse(hasattr(a, 'subpart_of'))

    def test_subtitle(self):
        for a in self.all_articles:
            if '--' in a.slug:
                self.assertTrue(hasattr(a, 'subtitle'))
                self.assertEqual(a.title,
                                 a.subtitle + ', ' + a.subpart_of.title)

class TestSubPartsPhotos(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.temp_path = mkdtemp(prefix='pelicantests.')
        settings = get_settings(filenames={})
        settings['PATH'] = os.path.join(CUR_DIR, 'test_data')
        settings['AUTHOR'] = 'Me'
        settings['DEFAULT_DATE'] = (1970, 1, 1)
        settings['DEFAULT_CATEGORY'] = 'Default'
        settings['FILENAME_METADATA'] = '(?P<slug>[^.]+)'
        settings['PLUGINS'] = [sub_parts]
        settings['CACHE_CONTENT'] = False
        context = settings.copy()
        context['generated_content'] = dict()
        context['static_links'] = set()
        cls.generator = ArticlesGenerator(
            context=context, settings=settings,
            path=settings['PATH'], theme=settings['THEME'], output_path=cls.temp_path)
        cls.generator.generate_context()
        cls.all_articles = list(cls.generator.articles)
        for a in cls.all_articles:
            a.photo_gallery = [('i.jpg', 'i.jpg', 'it.jpg', '', '')]
        sub_parts.patch_subparts(cls.generator)

    @classmethod
    def tearDownClass(cls):
        rmtree(cls.temp_path)

    def test_subphotos(self):
        for a in self.all_articles:
            if a.slug == 'parent':
                self.assertTrue(hasattr(a, 'subphotos'))
                self.assertEqual(3, a.subphotos)
            else:
                self.assertFalse(hasattr(a, 'subphotos'))

if __name__ == '__main__':
    unittest.main()


import turtle
import os

t = turtle.Pen()
#t.speed(0)
t.shape("turtle")
t.left(90)
for i in range(6):
    t.forward(100)
    t.right(60)
    for j in range(3):
        t.forward(20)
        t.backward(20)
        t.left(60)
    t.right(120)
    t.backward(100)
    t.left(60)

os.system("Pause")


##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *

class Xbacklight(AutotoolsPackage):
    """Xbacklight is used to adjust the backlight brightness where supported.
    It uses the RandR extension to find all outputs on the X server
    supporting backlight brightness control and changes them all in the
    same way."""

    homepage = "http://cgit.freedesktop.org/xorg/app/xbacklight"
    url      = "https://www.x.org/archive/individual/app/xbacklight-1.2.1.tar.gz"

    version('1.2.1', 'e8e4c86b0f867e23aa3532618a697609')

    depends_on('libxcb')
    depends_on('xcb-util')

    depends_on('pkgconfig', type='build')
    depends_on('util-macros', type='build')


import os

def align(step):
    path = os.getcwd()
    file_path = os.path.join(path, 'whales.txt')
    file1 = open(file_path, 'r')
    Lines = file1.readlines()
    initial_pos = [0] * 2000
    final = 0
    for line in Lines:
        input = line.strip()
        poss = input.split(",")
        prev_fuel = -1
        for median in range(0, int(poss[len(poss)-1])+1):
            fuel = 0
            for pos in poss:
                n = abs(int(pos) - int(median))
                fuel += n * (n+1)/2 if step else n
            if fuel < prev_fuel or prev_fuel == -1:
                prev_fuel = fuel

    print(int(prev_fuel))

if __name__ == "__main__":
    align(False)
    align(True)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the Zeitgeist event formatter."""

from __future__ import unicode_literals

import unittest

from plaso.formatters import zeitgeist

from tests.formatters import test_lib

class ZeitgeistFormatterTest(test_lib.EventFormatterTestCase):
  """Tests for the Zeitgeist activity database event formatter."""

  def testInitialization(self):
    """Tests the initialization."""
    event_formatter = zeitgeist.ZeitgeistFormatter()
    self.assertIsNotNone(event_formatter)

  def testGetFormatStringAttributeNames(self):
    """Tests the GetFormatStringAttributeNames function."""
    event_formatter = zeitgeist.ZeitgeistFormatter()

    expected_attribute_names = ['subject_uri']

    self._TestGetFormatStringAttributeNames(
        event_formatter, expected_attribute_names)

  # TODO: add test for GetMessages.

if __name__ == '__main__':
  unittest.main()


#!/usr/bin/env python3
"""
Convert $1 -- a markdown file to an HTML file in `/tmp/vim/<parent>/<basename>.html`.
"""

# Standard Library
from os.path import realpath, basename, isfile, isdir, dirname, abspath
import os
import shutil
import subprocess
import sys
import re
import logging
from logging import Logger
from typing import Dict, Iterable, Optional, Set, Text, List
from subprocess import DEVNULL, PIPE, run

from meta import MATHJAX_CONFS, LongOpt, CodeStyle, FromFmt, Ext, ToFmt
from utils import validate_executables, require_exists, vimdir_path, ensure_exists

# initalise logging with sane configuration
logging.basicConfig(level=logging.WARN,
                    format="%(levelname)s:%(asctime)s  %(message)s")

log: Logger = logging.getLogger()

validate_executables(["pandoc"])

# NOTE this will try to include a lua filter from `./task-list.lua`.
class PandocCmd:
    def __init__(
        self,
        input_file: Text,
        stylesheet: Text = vimdir_path("css", "styles.css"),
        javascript: Text = vimdir_path("js", "script.js"),
        from_fmt: FromFmt = FromFmt.MARKDOWN,
        to_fmt: ToFmt = ToFmt.HTML5,
        exts: List[Ext] = [
            Ext.ASCII_IDENTIFIERS,
            Ext.AUTOLINK_BARE_URIS,
            Ext.COMPACT_DEFINITION_LISTS,
            Ext.FENCED_DIVS,
            Ext.GFM_AUTO_IDENTIFIERS,
            Ext.INTRAWORD_UNDERSCORES,
            Ext.MARKDOWN_ATTRIBUTE,
            Ext.MMD_HEADER_IDENTIFIERS,
            Ext.MMD_LINK_ATTRIBUTES,
            Ext.SMART,
            Ext.TEX_MATH_DOLLARS,
            Ext.TEX_MATH_DOUBLE_BACKSLASH,
            Ext.TEX_MATH_SINGLE_BACKSLASH,
        ],
        no_exts: List[Ext] = [Ext.ALL_SYMBOLS_ESCAPABLE, Ext.ESCAPED_LINE_BREAKS],
        long_opts: Dict[LongOpt, Optional[Text]] = {
            LongOpt.ATX_HEADERS: None,
            LongOpt.REFERENCE_LOCATION: "document",
            LongOpt.SECTION_DIVS: None,
            LongOpt.EMAIL_OBFUSCATION: "javascript",
        },
        code_style: CodeStyle = CodeStyle.TANGO,
        mathjax_version: Text = "2.7.5",
        mathjax_conf: Text = "TeX-AMS_HTML",
        width: int = 80,
        toc_depth: int = 3,
    ) -> None:

        log.debug("initalising a PandocCmd object")

        self.exts: List[Ext] = []
        self.no_exts: List[Ext] = []
        self.long_opts: Dict[LongOpt, Optional[Text]] = dict()

        self.set_opts(long_opts).set_exts(exts).set_no_exts(no_exts).set_input_file(
            input_file
        ).set_opt(LongOpt.STANDALONE).set_to_fmt(to_fmt).set_from_fmt(
            from_fmt
        ).set_mathjax(
            mathjax_version, mathjax_conf
        ).set_width(
            width
        ).set_stylesheet(
            stylesheet
        ).set_code_style(
            code_style
        ).set_javascript(
            javascript
        )

        if toc_depth:
            self.set_toc_depth(toc_depth).set_opt(LongOpt.TOC)

        lua_filter: str = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'task-list.lua')

        if isfile(lua_filter):
            self.set_opt(LongOpt.LUA_FILTER, lua_filter)
        else:
            log.error(f'failed to find lua filter ./{lua_filter}')

    def set_from_fmt(self, fmt: FromFmt) -> object:
        assert fmt in FromFmt, f"from format '{fmt}' invalid"
        self.from_fmt: FromFmt = fmt
        return self

    def set_opt(self, key: LongOpt, val: Optional[Text] = None) -> object:
        self.long_opts[key] = val
        return self

    def set_opts(self, pairs: Dict[LongOpt, Optional[Text]]) -> object:
        for (k, v) in pairs.items():
            self.set_opt(k, v)
        return self

    def set_to_fmt(self, fmt: ToFmt) -> object:
        self.to_fmt = fmt
        return self

    def set_input_file(self, file_path: Text) -> object:
        require_exists(file_path)
        self.input_file = file_path
        return self

    def set_width(self, n: int) -> object:
        assert n and n >= 0, f"invalid value {str(n)}"
        return self.set_opt(LongOpt.COLUMNS, str(n))

    def set_stylesheet(self, css_path: Text) -> object:
        require_exists(css_path)
        return self.set_opt(LongOpt.CSS, css_path)

    def set_javascript(self, js_path: Text) -> object:
        require_exists(js_path)
        self.javascript = js_path
        return self

    def set_toc_depth(self, n: int) -> object:
        assert n and n >= 0, f"invalid value {n}"
        return self.set_opt(LongOpt.TOC_DEPTH, str(n))

    def set_code_style(self, style: CodeStyle) -> object:
        return self.set_opt(LongOpt.HIGHLIGHT_STYLE, style._name_.lower())

    def set_mathjax(self, version: Text, cfg: Text) -> object:
        assert cfg and cfg in MATHJAX_CONFS, f"unreconginsed MathJax config {cfg}"
        assert (
            version
            and len(version) >= 3
            and version[0] == "2"
            and version[1] == "."
            and str.isdigit(version[2])
        ), f"unrecognised MathJax version {version}"
        return self.set_opt(
            LongOpt.MATHJAX,
            f"https://cdnjs.cloudflare.com/ajax/libs/mathjax/{version}/MathJax.js?config={cfg}",
        )

    def set_exts(self, exts: Iterable[Ext]) -> object:
        for ext in exts:
            self.set_ext(ext)
        return self

    def set_ext(self, ext: Ext) -> object:
        self.exts.append(ext)
        return self

    def set_no_ext(self, ext: Ext) -> object:
        self.no_exts.append(ext)
        return self

    def set_no_exts(self, exts: Iterable[Ext]) -> object:
        for ext in exts:
            self.set_no_ext(ext)
        return self

    @property
    def args(self) -> List[Text]:

        arguments = ["pandoc", "--from"]

        from_fmt = self.from_fmt._name_.lower()
        if len(self.exts) > 0:
            for ext in self.exts:
                from_fmt += f"+{ext._name_.lower()}"
        if len(self.no_exts) > 0:
            for ext in self.no_exts:
                from_fmt += f"-{ext._name_.lower()}"

        arguments.append(from_fmt)

        arguments.extend(["--to", self.to_fmt._name_.lower()])

        for opt in self.long_opts.keys():
            maybe_val: Optional[Text] = self.long_opts[opt]
            opt_name: Text = opt._name_.lower().replace("_", "-")
            if maybe_val:
                arguments.append(f"--{opt_name}={maybe_val}")
            else:
                arguments.append(f"--{opt_name}")
        log.debug(f"args: {arguments}")
        return arguments

    def before(self, text: Text) -> Text:
        """Fix badly formatted markdown where heading marker `#` is not
        followed by space.

        NOTE: This method is pure.

        :param text: input text before transformations
        :return: output text after transformations
        """
        log.debug("preprocessing [before hook]")
        return re.sub(r"(#+)([A-Z])", "\1 \2", text, re.MULTILINE)

    def after(self, text: Text) -> Text:
        """Transform relative links and references, Inject JavaScript.

        NOTE: This method is pure.

        Match on either src or href e.g.:

            `src="./script.js"` and `href="styles.css"`

        skip over whitespace e.g.:

            `src="    address/file.png"`

        match if relative e.g.:

            `./`
        or match if not an external link with a protocol e.g.:

            `https://stackoverflow.com`

        or match if not a valid directory reference e.g.:

            `/srv/log/log.txt` and `~/file.txt`

        :param text: input text
        :return: output after transformations
        """
        pat = re.compile(r'(href|src)="\s*(\./|(?![a-z]{2,10}://|~|\#|/))')
        d: Text = dirname(self.input_file)
        with open(self.javascript) as f:
            log.debug("postprocessing [after hook]")
            return re.sub(pat, f'\\1="{d}/', text).replace(
                "", f""
            )

    def execute(self) -> Text:
        log.debug("executing")
        with open(self.input_file, encoding="utf-8") as input:
            return self.after(
                run(
                    self.args,
                    encoding="utf-8",
                    input=self.before(input.read()),
                    stderr=DEVNULL,
                    stdout=PIPE,
                ).stdout
            )

if __name__ == "__main__":

    INPUT_FILE = sys.argv[1]

    log.debug(f"input file: {INPUT_FILE}")

    OUTPUT_FILE: Text = os.path.join(
        "/tmp/vim",
        basename(dirname(INPUT_FILE)),
        re.sub(
            r"^(.*)\.(?:r?md|m(?:ark)?down)$",
            r"\1.html",
            basename(INPUT_FILE),
            re.IGNORECASE | re.MULTILINE,
        ),
    )

    log.debug(f"output file: {OUTPUT_FILE}")

    ensure_exists(OUTPUT_FILE)

    with open(OUTPUT_FILE, "w", encoding="utf-8") as output:
        cmd = PandocCmd(INPUT_FILE)
        output.write(cmd.execute())
        print(f"Cmd: {' '.join(cmd.args)}")
        print(f'Output: {output.name}')

# vim:foldmethod=manual:


import logging
from typing import Any, Dict, List, Optional

from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse
from starlette.routing import Mount, Route

from pait.api_doc.html import get_redoc_html as _get_redoc_html
from pait.api_doc.html import get_swagger_ui_html as _get_swagger_ui_html
from pait.api_doc.open_api import PaitOpenApi
from pait.field import Depends, Query
from pait.g import config
from pait.model.core import PaitCoreModel
from pait.model.status import PaitStatus

from ._load_app import load_app
from ._pait import Pait

def add_doc_route(
    app: Starlette,
    scheme: Optional[str] = None,
    prefix: str = "/",
    pin_code: str = "",
    title: str = "Pait Doc",
    open_api_tag_list: Optional[List[Dict[str, Any]]] = None,
) -> None:
    if pin_code:
        logging.info(f"doc route start pin code:{pin_code}")

    doc_pait: Pait = Pait(
        author=config.author or ("so1n",),
        status=config.status or PaitStatus.release,
        tag=("pait_doc",),
        group="pait_doc",
    )

    def _get_request_pin_code(r_pin_code: str = Query.i("", alias="pin_code")) -> Optional[str]:
        if pin_code:
            if r_pin_code != pin_code:
                raise HTTPException(
                    status_code=404,
                    detail=(
                        "The requested URL was not found on the server. If you entered"
                        " the URL manually please check your spelling and try again."
                    ),
                )
        return r_pin_code

    def _get_open_json_url(request: Request, r_pin_code: str) -> str:
        openapi_json_url: str = f"{'/'.join(request.url.path.split('/')[:-1])}/openapi.json"
        if r_pin_code:
            openapi_json_url += f"?pin_code={r_pin_code}"
        return openapi_json_url

    @doc_pait()
    def get_redoc_html(request: Request, r_pin_code: str = Depends.i(_get_request_pin_code)) -> HTMLResponse:
        return HTMLResponse(_get_redoc_html(_get_open_json_url(request, r_pin_code), title))

    @doc_pait()
    def get_swagger_ui_html(request: Request, r_pin_code: str = Depends.i(_get_request_pin_code)) -> HTMLResponse:
        return HTMLResponse(_get_swagger_ui_html(_get_open_json_url(request, r_pin_code), title))

    @doc_pait(pre_depend_list=[_get_request_pin_code])
    def openapi_route(request: Request) -> JSONResponse:
        pait_dict: Dict[str, PaitCoreModel] = load_app(request.app)
        _scheme: str = scheme or request.url.scheme
        pait_openapi: PaitOpenApi = PaitOpenApi(
            pait_dict,
            title=title,
            open_api_server_list=[{"url": f"{_scheme}://{request.url.hostname}:{request.url.port}", "description": ""}],
            open_api_tag_list=open_api_tag_list,
        )
        return JSONResponse(pait_openapi.open_api_dict)

    route: Mount = Mount(
        prefix,
        name="api doc",
        routes=[
            Route("/redoc", get_redoc_html, methods=["GET"]),
            Route("/swagger", get_swagger_ui_html, methods=["GET"]),
            Route("/openapi.json", openapi_route, methods=["GET"]),
        ],
    )
    app.routes.append(route)