max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
7
115
max_stars_count
int64
101
368k
id
stringlengths
2
8
content
stringlengths
6
1.03M
setup.py
liudongliangHI/ProLIF
123
11122489
<filename>setup.py from setuptools import setup import versioneer import re # manually check RDKit version try: from rdkit import __version__ as rdkit_version except ImportError: raise ImportError("ProLIF requires RDKit but it is not installed") else: if re.match(r"^20[0-1][0-9]\.", rdkit_version): raise ValueError("ProLIF requires a version of RDKit >= 2020") setup(version=versioneer.get_version())
DQM/RPCMonitorClient/python/RPCEventSummary_cfi.py
ckamtsikis/cmssw
852
11122541
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester rpcEventSummary = DQMEDHarvester("RPCEventSummary", EventInfoPath = cms.untracked.string('RPC/EventInfo'), PrescaleFactor = cms.untracked.int32(5), MinimumRPCEvents = cms.untracked.int32(10000), NumberOfEndcapDisks = cms.untracked.int32(4), EnableEndcapSummary = cms.untracked.bool(True), OfflineDQM = cms.untracked.bool(True), RecHitTypeFolder = cms.untracked.string("AllHits") )
yabgp/message/attribute/nlri/ipv6_flowspec.py
mengjunyi/yabgp
203
11122561
# Copyright 2015 Cisco Systems, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """IPv6 Flowspec NLRI """ from __future__ import division from builtins import range import binascii import math import struct import netaddr from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI class IPv6FlowSpec(NLRI): """ipv6 flow nlri process """ @classmethod def parse(cls, value): """ parse IPv6 flowspec NLRI :param value: :return: """ # +------------------------------+ # | length (0xnn or 0xfn nn) | # +------------------------------+ # | NLRI value (variable) | # +------------------------------+ nlri_dict = {} while value: offset = 0 flowspec_type = ord(value[0:1]) offset += 1 # decode all kinds of flow spec if flowspec_type in [bgp_cons.BGPNLRI_FSPEC_DST_PFIX, bgp_cons.BGPNLRI_FSPEC_SRC_PFIX]: prefix, offset_tmp = cls.parse_prefix(value[offset:]) offset += offset_tmp nlri_dict[flowspec_type] = prefix value = value[offset:] elif flowspec_type in [bgp_cons.BGPNLRI_FSPEC_IP_PROTO, bgp_cons.BGPNLRI_FSPEC_DST_PORT, bgp_cons.BGPNLRI_FSPEC_SRC_PORT, bgp_cons.BGPNLRI_FSPEC_ICMP_TP, bgp_cons.BGPNLRI_FSPEC_ICMP_CD, bgp_cons.BGPNLRI_FSPEC_DSCP, bgp_cons.BGPNLRI_FSPEC_PCK_LEN]: operator_list, offset = cls.parse_operators(value[offset:]) nlri_dict[flowspec_type] = cls.operator_dict_to_str(operator_list) value = value[offset:] else: operator_list, offset = cls.parse_operators(value[offset:]) nlri_dict[flowspec_type] = cls.operator_dict_to_str(operator_list) value = value[offset:] return nlri_dict @classmethod def construct(cls, value): nlri_hex = b'' for nlri in value: nlri_hex += cls.construct_nlri(nlri) return nlri_hex @classmethod def construct_nlri(cls, data): """ Construct NLRI """ # there may have many filters in each nlri data = dict([(int(l), r) for (l, r) in data.items()]) nlri_tmp = b'' for type_tmp in [bgp_cons.BGPNLRI_IPV6_FSPEC_DST_PFIX, bgp_cons.BGPNLRI_IPV6_FSPEC_SRC_PFIX]: if data.get(type_tmp): nlri_tmp += struct.pack('!B', type_tmp) + cls.construct_prefix(data[type_tmp]) for type_tmp in [bgp_cons.BGPNLRI_IPV6_FSPEC_NEXT_HEADER, bgp_cons.BGPNLRI_IPV6_FSPEC_PORT, bgp_cons.BGPNLRI_IPV6_FSPEC_DST_PORT, bgp_cons.BGPNLRI_IPV6_FSPEC_SRC_PORT, bgp_cons.BGPNLRI_IPV6_FSPEC_ICMP_TP, bgp_cons.BGPNLRI_IPV6_FSPEC_ICMP_CD, bgp_cons.BGPNLRI_IPV6_FSPEC_TCP_FLAGS, bgp_cons.BGPNLRI_IPV6_FSPEC_PCK_LEN, bgp_cons.BGPNLRI_IPV6_FSPEC_DSCP, bgp_cons.BGPNLRI_IPV6_FSPEC_FRAGMENT, bgp_cons.BGPNLRI_IPV6_FSPEC_FLOW_LABLE]: if not data.get(type_tmp): continue # translate from expression to binary nlri_tmp += struct.pack('!B', type_tmp) + cls.construct_operators(data[type_tmp]) if len(nlri_tmp) >= 240: return struct.pack('!H', len(nlri_tmp)) + nlri_tmp elif nlri_tmp: return struct.pack('!B', len(nlri_tmp)) + nlri_tmp @staticmethod def parse_prefix(data): """ Prefixes are encoded as in BGP UPDATE messages, a length in bits is followed by enough octets to contain the prefix information. Encoding: <prefix-length (1 octet), prefix> """ prefix_len = ord(data[0:1]) octet_len = int(math.ceil(prefix_len / 8)) tmp = data[1:octet_len + 1] if isinstance(tmp[0], int): prefix_data = [i for i in tmp] else: prefix_data = [ord(i) for i in tmp] prefix_data = prefix_data + list(str(0)) * 4 prefix = "%s.%s.%s.%s" % (tuple(prefix_data[0:4])) + '/' + str(prefix_len) return prefix, octet_len + 1 @classmethod def construct_prefix(cls, prefix): """ construct a prefix string from '1.1.1.0/24' to '\x18\x01\x01\x01' """ prefix_value = prefix.get('prefix') ip, masklen = prefix_value.split('/') ip_hex = netaddr.IPAddress(ip).packed offset = prefix.get('offset') masklen = int(masklen) # lenght ip_hex = ip_hex[: math.ceil(masklen / 8)] # offset ip_hex = ip_hex[math.floor(offset / 8):] # ip_hex = ip_hex[] return struct.pack('!B', masklen) + struct.pack('!B', offset) + ip_hex @classmethod def parse_operators(cls, data): offset = 0 parse_operator_list = [] while data: operator = cls.parse_operator_flag(ord(data[0:1])) # print(operator) offset += 1 operator_value = int(binascii.b2a_hex(data[1:1 + operator['LEN']]), 16) offset += operator['LEN'] parse_operator_list.append([operator, operator_value]) # the end of the list data = data[1 + operator['LEN']:] if operator['EOL']: break return parse_operator_list, offset + 1 @staticmethod def parse_operator_flag(data): """ The operator byte is encoded as: 0 1 2 3 4 5 6 7 +---+---+---+---+---+---+---+---+ |EOL|AND| LEN |RES|LT |GT |EQ | +---+---+---+---+---+---+---+---+ """ bit_list = [] for i in range(8): bit_list.append((data >> i) & 1) bit_list.reverse() result = { 'EOL': bit_list[0], 'AND': bit_list[1], 'LEN': 1 << (bit_list[2] * 2 + bit_list[3]), 'LT': bit_list[5], 'GT': bit_list[6], 'EQ': bit_list[7] } return result @staticmethod def construct_operator_flag(data): """construct operator flag from dict to binary """ opt_dict = { 'EOL': 0x80, 'AND': 0x40, 'LEN': { 1: 0x00, 2: 0x10, 4: 0x20, 6: 0x30 }, 'RES': 0x00, 'LT': 0x04, 'GT': 0x02, 'EQ': 0x01 } b_data = 0x00 for opt in opt_dict: if opt in data and opt != 'LEN': if data[opt] == 1: b_data += opt_dict[opt] elif opt == 'LEN' and data[opt]: b_data += opt_dict['LEN'][data['LEN']] return b_data @staticmethod def operator_dict_to_str(data): """ from [ [ {'AND': 0, 'GT': 0, 'LEN': 1, 'EOL': 0, 'LT': 0, 'EQ': 1}, 254 ], [ {'AND': 0, 'GT': 1, 'LEN': 1, 'EOL': 0, 'LT': 0, 'EQ': 1}, 254 ], [ {'AND': 1, 'GT': 0, 'LEN': 2, 'EOL': 1, 'LT': 1, 'EQ': 1}, 300 ] ] to =254|>=254&<=300 :param data: dict :return: string format """ return_str = '' for item in data: operator_dict, value = item if operator_dict['AND']: return_str += '&' else: if return_str != '': return_str += '|' if operator_dict['GT']: return_str += '>' if operator_dict['LT']: return_str += '<' if operator_dict['EQ']: return_str += '=' return_str += str(value) return return_str @classmethod def construct_operators(cls, data): """ from "=254|>=254&<=300" to binary data :param data: :return: """ data_bin = b'' data_list = data.split('|') eol = 0 for i, data in enumerate(data_list): if i == len(data_list) - 1: eol = 1 if '&' not in data: flag_dict = {'EOL': eol} if data[0] == '=': off_set = 1 flag_dict['EQ'] = 1 elif '>=' in data: off_set = 2 flag_dict['EQ'] = 1 flag_dict['GT'] = 1 elif '<=' in data: off_set = 2 flag_dict['EQ'] = 1 flag_dict['LT'] = 1 elif '>' in data: off_set = 1 flag_dict['GT'] = 1 elif '<' in data: off_set = 1 flag_dict['LT'] = 1 hex_str = hex(int(data[off_set:]))[2:] if len(hex_str) % 2 == 1: hex_str = '0' + hex_str value_hex = bytearray.fromhex(hex_str) flag_dict['LEN'] = len(value_hex) opt_flag_bin = cls.construct_operator_flag(flag_dict) data_bin += struct.pack('!B', opt_flag_bin) data_bin += value_hex return data_bin
hata/discord/activity/activity_types.py
Multiface24111/hata
173
11122592
<reponame>Multiface24111/hata<filename>hata/discord/activity/activity_types.py __all__ = () __doc__ = """ A module, which contains the activity types' discord side value. +-----------+-------+ | Name | Value | +===========+=======+ | game | 0 | +-----------+-------+ | stream | 1 | +-----------+-------+ | spotify | 2 | +-----------+-------+ | watching | 3 | +-----------+-------+ | custom | 4 | +-----------+-------+ | competing | 5 | +-----------+-------+ """ game = 0 stream = 1 spotify = 2 watching = 3 custom = 4 competing = 5
Python/orangeHello.py
saurabhcommand/Hello-world
1,428
11122602
def helloName(name): print ("Hello " + name) helloName("John")
evalml/utils/update_checker.py
Mahesh1822/evalml
454
11122603
<reponame>Mahesh1822/evalml<filename>evalml/utils/update_checker.py """Check if EvalML has updated since the user installed.""" from pkg_resources import iter_entry_points for entry_point in iter_entry_points("alteryx_open_src_initialize"): try: method = entry_point.load() if callable(method): method("evalml") except Exception: pass
grove/alpha/fermion_transforms/tests/test_bravyi_kitaev.py
mkeshita/grove
229
11122635
import numpy as np import pytest from grove.alpha.fermion_transforms.bktransform import BKTransform from grove.alpha.fermion_transforms.jwtransform import JWTransform """ Some tests inspired by: https://github.com/ProjectQ-Framework/FermiLib/blob/develop/src/fermilib/transforms/_bravyi_kitaev_test.py """ def test_hardcoded_transform(): n_qubits = 16 bkt = BKTransform(n_qubits) x = bkt.kill(9) y = bkt.create(9) assert str(x) == '(0.5+0j)*X9*Z7*Z8*X11*X15 + 0.5j*Y9*X11*X15*Z7' assert str(y) == '(0.5+0j)*X9*Z7*Z8*X11*X15 + -0.5j*Y9*X11*X15*Z7' def test_term_length(): # create/kill operators are two-term n_qubits = 16 bkt = BKTransform(n_qubits) assert len(bkt.create(3)) == 2 assert len(bkt.kill(3)) == 2 n_qubits = 7 bkt = BKTransform(n_qubits) assert len(bkt.create(3)) == 2 assert len(bkt.kill(3)) == 2 def test_throw_errors(): # throw error when creation outside qubit range n_qubits = 16 bkt = BKTransform(n_qubits) with pytest.raises(IndexError): bkt.kill(-1) with pytest.raises(IndexError): bkt.kill(16) with pytest.raises(IndexError): bkt.kill(17) def test_locality_invariant(): # for n_qubits = 2**d, c_j Majorana is always log2(N) + 1 local n_qubits = 16 bkt = BKTransform(n_qubits) invariant = np.log2(n_qubits) + 1 for index in range(n_qubits): op = bkt.kill(index) op_terms = op.terms for term in op_terms: coeff = term.coefficient # Identify the c Majorana terms by real # coefficients and check their length. if not isinstance(coeff, complex): assert len(term) == invariant @pytest.mark.skip(reason="pyQuil Pauli needs matrix operator / eigenspectrum " "functionality") def test_eigenspectrum(): # Jordan-Wigner and Bravyi-Kitaev operators should give same eigenspectrum # single number operator n_qubits = 16 bkt = BKTransform(n_qubits) op_BK = bkt.create(3) * bkt.kill(3) jwt = JWTransform() op_JW = jwt.create(3) * jwt.kill(3) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix())) # sum of number operators op_BK = 0 op_JW = 0 for i in [1, 3, 5]: op_BK += bkt.create(i) * bkt.kill(i) op_JW += jwt.create(i) * jwt.kill(i) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix())) # scaled number operator op_BK = 3 * bkt.create(3) * bkt.kill(3) op_JW = 3 * jwt.create(3) * jwt.kill(3) assert np.sort(np.linalg.eigvals(op_BK.matrix())) == \ np.sort(np.linalg.eigvals(op_JW.matrix()))
director/migrations/versions/05cf96d6fcae_add_task_result.py
apikay/celery-director
351
11122646
"""Add task result Revision ID: 05cf96d6fcae Revises: <PASSWORD> Create Date: 2020-03-20 19:16:48.520652 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "<KEY>e" down_revision = "<PASSWORD>" branch_labels = None depends_on = None def upgrade(): op.add_column("tasks", sa.Column("result", sa.PickleType(), nullable=True)) def downgrade(): op.drop_column("tasks", "result")
qtl/src/ase_aggregate_by_individual.py
richardslab/gtex-pipeline
247
11122769
# Author: <NAME> import numpy as np import scipy.stats import pandas as pd import argparse import pyBigWig import os import subprocess import io import gzip import pickle def padjust_bh(p): """ Benjamini-Hochberg ajdusted p-values Replicates p.adjust(p, method="BH") from R """ n = len(p) i = np.arange(n,0,-1) o = np.argsort(p)[::-1] ro = np.argsort(o) return np.minimum(1, np.minimum.accumulate(np.float(n)/i * np.array(p)[o]))[ro] parser = argparse.ArgumentParser(description='ASE') parser.add_argument('read_count_file_list', help='Read count file list (one per sample); [sample_id, tissue_site_detail, file_path]') parser.add_argument('het_vcf') parser.add_argument('vep_dict') parser.add_argument('simulation_bias_file', help='?') parser.add_argument('mappability_bigwig', help='Mappability track in bigWig format') parser.add_argument('tissue_abbreviations', help='File mapping tissue_site_detail to abbreviation') parser.add_argument('lamp_values', help='Table with foreign allele frequency per individual') parser.add_argument('individual_id', help='individual_id') parser.add_argument('--coverage_cutoff', default=8, type=int, help='') parser.add_argument('--other_ratio_cutoff', default=0.05, type=float, help='') parser.add_argument('--mono_cutoff', default=0.01, type=float, help='') parser.add_argument('-o', '--output_dir', default='.') args = parser.parse_args() print('Parsing inputs') tissue2abrv = pd.read_csv(args.tissue_abbreviations, sep='\t', index_col=0, squeeze=True).to_dict() readcount_file_df = pd.read_csv(args.read_count_file_list, sep='\t', index_col=0) df = pd.read_csv(args.simulation_bias_file, sep='\t', header=None, dtype=str) simulation_bias_set = set(df[0]+':'+df[1]) print('Parsing read count files') readcount_df_list = [] for i,rfile in enumerate(readcount_file_df['ase_readcount_file']): readcount_df = pd.read_csv(rfile, sep='\t', index_col=2) readcount_df = readcount_df[['contig', 'position', 'refAllele', 'altAllele', 'refCount', 'altCount', 'totalCount', 'otherBases']] readcount_df = readcount_df.rename(columns={'contig':'chr', 'position':'coord', 'refAllele':'ref', 'altAllele':'alt', 'refCount':'refcount', 'altCount':'altcount', 'totalCount':'totalcount', 'otherBases':'othercount'}) readcount_df = readcount_df[readcount_df['totalcount']>=args.coverage_cutoff] readcount_df['refratio'] = readcount_df['refcount']/readcount_df['totalcount'] readcount_df['otherratio'] = readcount_df['othercount'] / (readcount_df['othercount'] + readcount_df['totalcount']) readcount_df['otherflag'] = (readcount_df['otherratio']>=args.other_ratio_cutoff)*1 readcount_df['allcount'] = readcount_df['totalcount'] + readcount_df['othercount'] sample_id = readcount_file_df.index[i] readcount_df['sampid'] = sample_id readcount_df['subjid'] = '-'.join(sample_id.split('-')[:2]) readcount_df['tissue'] = readcount_file_df.loc[sample_id, 'tissue_site_detail'] readcount_df['tissueabrv'] = tissue2abrv[readcount_file_df.loc[sample_id, 'tissue_site_detail']] readcount_df['covflag'] = 0 # covflag is never 1, since filtered above (coverage_cutoff) readcount_df_list.append(readcount_df) print('Loading VCF') vcf_df = pd.read_csv(args.het_vcf, sep='\t', comment='#', header=None, names=['chr', 'pos', 'id', 'ref', 'alt', 'qual', 'filter', 'info', 'format', 'genotype'], dtype=str, usecols=['chr', 'pos', 'id', 'info','format', 'genotype'], index_col=2) vcf_snp_id_df = pd.DataFrame(index=vcf_df.index, columns=['chr', 'coord', 'genotype', 'ensg', 'vtype', 'mapbias', 'mapflag', 'monoflag', 'mono_refcount', 'mono_altcount', 'mono_totalcount', 'mono_othercount']) vcf_snp_id_df[['chr', 'coord']] = vcf_df[['chr', 'pos']] vcf_snp_id_df['genotype'] = vcf_df['format']+';'+vcf_df['genotype'] print('Adding VEP annotation') with open(args.vep_dict, 'rb') as f: vep_dict = pickle.load(f) ensg = [] vtype = [] for i in vcf_df.index: gene_name, vep = vep_dict.get(i, ('NA','NA')) ensg.append(gene_name) vtype.append(vep) vcf_snp_id_df['ensg'] = ensg vcf_snp_id_df['vtype'] = vtype vep_dict = None print('Adding mappability') mp = [] bw = pyBigWig.open(args.mappability_bigwig) for c,p in zip(vcf_df['chr'], vcf_df['pos']): mp.append((bw.stats(c, int(p)-1, int(p), exact=True)[0]!=1) * 1) # BED coordinates, 0-indexed; input must be int (not numpy) bw.close() vcf_snp_id_df['mapbias'] = [1 if i in simulation_bias_set else 0 for i in vcf_snp_id_df['chr']+':'+vcf_snp_id_df['coord']] vcf_snp_id_df['mapflag'] = mp vcf_snp_id_df['monoflag'] = 0 vcf_snp_id_df['mono_refcount'] = 0 vcf_snp_id_df['mono_altcount'] = 0 vcf_snp_id_df['mono_totalcount'] = 0 vcf_snp_id_df['mono_othercount'] = 0 for readcount_df in readcount_df_list: # combine read counts for each variant vcf_snp_id_df.loc[readcount_df.index, 'mono_refcount'] += readcount_df['refcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_altcount'] += readcount_df['altcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_totalcount'] += readcount_df['totalcount'] vcf_snp_id_df.loc[readcount_df.index, 'mono_othercount'] += readcount_df['othercount'] print('Calculating statistics') lamp = pd.read_csv(args.lamp_values, sep='\t', index_col=0, squeeze=True).median() ref = vcf_snp_id_df['mono_refcount'] tot = vcf_snp_id_df['mono_totalcount'] monop_list = scipy.stats.binom.cdf(tot-ref, tot, 1-lamp) + scipy.stats.binom.cdf(ref, tot, 1-lamp) # monoallelic_p monop_adj_list = padjust_bh(monop_list) vcf_snp_id_df['monoflag'] = (monop_adj_list > args.mono_cutoff) * 1 indiv_cov75_counts = [] for readcount_df in readcount_df_list: readcount_df['GENOTYPE_WARNING'] = vcf_snp_id_df.loc[readcount_df.index, 'monoflag'] idx = (vcf_snp_id_df.loc[readcount_df.index, ['monoflag', 'mapbias', 'mapflag']].sum(axis=1)==0) & (readcount_df['otherflag']==0) indiv_cov75_counts.extend(list(readcount_df.loc[idx, 'totalcount'])) cov75 = np.percentile(indiv_cov75_counts, 75) print('Calculating bias') genomewide_bias = [0.0, 0.0, 0] for readcount_df in readcount_df_list: idx = (readcount_df[['covflag', 'otherflag']].sum(axis=1) + vcf_snp_id_df.loc[readcount_df.index, ['mapbias', 'mapflag', 'monoflag']].sum(axis=1)) == 0 refcountcov = readcount_df.loc[idx, 'refcount'] altcountcov = readcount_df.loc[idx, 'altcount'] totcountcov = refcountcov + altcountcov bias_keys = readcount_df.loc[idx, 'ref']+'/'+readcount_df.loc[idx, 'alt'] idx2 = (refcountcov+altcountcov) > cov75 refcountcov[idx2] = cov75*(refcountcov[idx2]/totcountcov[idx2]) altcountcov[idx2] = cov75 - refcountcov[idx2] totcountcov[idx2] = cov75 genomewide_bias[0] += refcountcov.sum() genomewide_bias[1] += totcountcov.sum() genomewide_bias[2] += refcountcov.shape[0] genomewide_bias_value = float(genomewide_bias[0]) / genomewide_bias[1] print('Calculating binomial tests, adjusted p-values') for readcount_df in readcount_df_list: readcount_df['binom_p'] = [scipy.stats.binom_test(i, j, genomewide_bias_value) for i,j in zip(readcount_df['refcount'], readcount_df['totalcount'])] readcount_df['nullratio'] = genomewide_bias_value idx = (readcount_df[['covflag', 'otherflag']].sum(axis=1) + vcf_snp_id_df.loc[readcount_df.index, ['mapbias', 'mapflag', 'monoflag']].sum(axis=1))==0 readcount_df.loc[idx, 'binom_p_adj'] = padjust_bh(readcount_df.loc[idx, 'binom_p']) readcount_df.loc[~idx, 'binom_p_adj'] = 'NA' print('Writing output') with gzip.open(os.path.join(args.output_dir, args.individual_id+'.ase_table.tsv.gz'), 'wt') as f: f.write('\t'.join([ 'CHR', 'POS', 'VARIANT_ID', 'REF_ALLELE', 'ALT_ALLELE', 'SAMPLE_ID', 'SUBJECT_ID', 'TISSUE_ID', 'REF_COUNT', 'ALT_COUNT', 'TOTAL_COUNT', 'REF_RATIO', 'OTHER_ALLELE_COUNT', 'NULL_RATIO', 'BINOM_P', 'BINOM_P_ADJUSTED', 'MAMBA_POST_SINGLETIS', 'MAMBA_POST_MULTITIS', 'GENOTYPE', 'VARIANT_ANNOTATION', 'GENE_ID', 'LOW_MAPABILITY', 'MAPPING_BIAS_SIM', 'GENOTYPE_WARNING'])+'\n') merged_df = [] for readcount_df in readcount_df_list: readcount_df['id'] = readcount_df.index readcount_df['blank'] = 'NA' out_df = readcount_df[['chr', 'coord', 'id', 'ref', 'alt', 'sampid', 'subjid', 'tissueabrv', 'refcount', 'altcount', 'totalcount', 'refratio', 'othercount', 'nullratio', 'binom_p', 'binom_p_adj', 'blank', 'blank']] merged_df.append(pd.concat([out_df, vcf_snp_id_df.loc[readcount_df.index, ['genotype', 'vtype', 'ensg', 'mapflag', 'mapbias']], readcount_df['GENOTYPE_WARNING']], axis=1)) merged_df = pd.concat(merged_df, axis=0) merged_df = merged_df.sort_values(['chr', 'coord', 'tissueabrv']) merged_df.to_csv(f, sep='\t', index=False, header=False, float_format='%.6g') print('Done')
tests/functional/api/views/route_by_content_test.py
hypothesis/via
113
11122864
<gh_stars>100-1000 from urllib.parse import quote_plus import httpretty import pytest from h_matchers import Any from tests.conftest import assert_cache_control class TestRouteByContent: DEFAULT_OPTIONS = { "via.client.ignoreOtherConfiguration": "1", "via.client.openSidebar": "1", "via.external_link_mode": "new-tab", } @pytest.mark.usefixtures("html_response", "checkmate_pass") def test_proxy_html(self, test_app): target_url = "http://example.com" response = test_app.get(f"/route?url={target_url}") assert response.status_code == 302 query = dict(self.DEFAULT_OPTIONS) assert response.location == Any.url.matching( f"https://viahtml.hypothes.is/proxy/{target_url}/" ).with_query(query) @pytest.mark.usefixtures("pdf_response", "checkmate_pass") def test_proxy_pdf(self, test_app): target_url = "http://example.com" response = test_app.get(f"/route?url={target_url}") assert response.status_code == 302 query = dict(self.DEFAULT_OPTIONS) query["via.sec"] = Any.string() query["url"] = target_url assert response.location == Any.url.matching( f"http://localhost/pdf?url={quote_plus(target_url)}" ).with_query(query) assert_cache_control( response.headers, ["public", "max-age=300", "stale-while-revalidate=86400"] ) @pytest.fixture def html_response(self): httpretty.register_uri( httpretty.GET, "http://example.com", status=204, adding_headers={"Content-Type": "text/html"}, ) @pytest.fixture def pdf_response(self): httpretty.register_uri( httpretty.GET, "http://example.com", status=204, adding_headers={"Content-Type": "application/pdf"}, )
observations/r/wong.py
hajime9652/observations
199
11122869
<gh_stars>100-1000 # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def wong(path): """Post-Coma Recovery of IQ The `Wong` data frame has 331 row and 7 columns. The observations are longitudinal data on recovery of IQ after comas of varying duration for 200 subjects. This data frame contains the following columns: `id` patient ID number. `days` number of days post coma at which IQs were measured. `duration` duration of the coma in days. `sex` a factor with levels `Female` and `Male`. `age` in years at the time of injury. `piq` performance (i.e., mathematical) IQ. `viq` verbal IQ. <NAME>., <NAME>., and <NAME>. (2001) Mathematical models of cognitive recovery. *Brain Injury*, **15**, 519–530. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `wong.csv`. Returns: Tuple of np.ndarray `x_train` with 331 rows and 7 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'wong.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/car/Wong.csv' maybe_download_and_extract(path, url, save_file_name='wong.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
fastapi_contrib/auth/permissions.py
mumtozvalijonov/fastapi_contrib
504
11122882
<reponame>mumtozvalijonov/fastapi_contrib<filename>fastapi_contrib/auth/permissions.py<gh_stars>100-1000 from starlette.requests import Request from starlette import status from fastapi_contrib.permissions import BasePermission class IsAuthenticated(BasePermission): """ Permission that checks if the user has been authenticated (by middleware) Use it as an argument to `PermissionsDependency` as follows: .. code-block:: python app = FastAPI() @app.get( "/user/", dependencies=[Depends(PermissionsDependency([IsAuthenticated]))] ) async def user(request: Request) -> dict: return request.scope["user"].dict() """ error_msg = "Not authenticated." status_code = status.HTTP_401_UNAUTHORIZED error_code = status.HTTP_401_UNAUTHORIZED def has_required_permissions(self, request: Request) -> bool: return request.user is not None
messaging/api/views.py
maznu/peering-manager
127
11122891
<gh_stars>100-1000 from rest_framework.routers import APIRootView from messaging.api.serializers import ( ContactAssignmentSerializer, ContactRoleSerializer, ContactSerializer, EmailSerializer, ) from messaging.filters import ( ContactAssignmentFilterSet, ContactFilterSet, ContactRoleFilterSet, EmailFilterSet, ) from messaging.models import Contact, ContactAssignment, ContactRole, Email from peering_manager.api.views import ModelViewSet class MessagingRootView(APIRootView): def get_view_name(self): return "Messaging" class ContactRoleViewSet(ModelViewSet): queryset = ContactRole.objects.all() serializer_class = ContactRoleSerializer filterset_class = ContactRoleFilterSet class ContactViewSet(ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer filterset_class = ContactFilterSet class ContactAssignmentViewSet(ModelViewSet): queryset = ContactAssignment.objects.prefetch_related("object", "contact", "role") serializer_class = ContactAssignmentSerializer filterset_class = ContactAssignmentFilterSet class EmailViewSet(ModelViewSet): queryset = Email.objects.all() serializer_class = EmailSerializer filterset_class = EmailFilterSet
skidl/libs/xilinx_sklib.py
arjenroodselaar/skidl
700
11122908
<filename>skidl/libs/xilinx_sklib.py from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib SKIDL_lib_version = '0.0.1' xilinx = SchLib(tool=SKIDL).add_parts(*[ Part(name='4003APG120',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['4003PG120']), Part(name='4003HPQ208',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='4005HMQ240',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='4013PQ240',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC1736APD8',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC18V01SO20',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='D0',func=Pin.OUTPUT,do_erc=True), Pin(num='2',name='D2',func=Pin.OUTPUT,do_erc=True), Pin(num='3',name='CLK',do_erc=True), Pin(num='4',name='TDI',do_erc=True), Pin(num='5',name='TMS',do_erc=True), Pin(num='6',name='TCK',do_erc=True), Pin(num='7',name='D4/CF',func=Pin.OPENCOLL,do_erc=True), Pin(num='8',name='OE/RESET',do_erc=True), Pin(num='9',name='D6',func=Pin.OUTPUT,do_erc=True), Pin(num='10',name='CE',do_erc=True), Pin(num='20',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='D7',func=Pin.OUTPUT,do_erc=True), Pin(num='13',name='CEO',func=Pin.OUTPUT,do_erc=True), Pin(num='14',name='D5',func=Pin.OUTPUT,do_erc=True), Pin(num='15',name='D3',func=Pin.OUTPUT,do_erc=True), Pin(num='16',name='D1',func=Pin.OUTPUT,do_erc=True), Pin(num='17',name='TDO',func=Pin.OPENCOLL,do_erc=True), Pin(num='18',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='19',name='VCCO',func=Pin.PWRIN,do_erc=True)]), Part(name='XC2018-PC68',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['XC2064-PC68']), Part(name='XC2018-PC84',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC2C256-TQ144',dest=TEMPLATE,tool=SKIDL,keywords='CPLD',description='CoolRunner-II CPLD, 256 macrocells',ref_prefix='U',num_units=1,fplist=['TQFP*20x20mm*Pitch0.5mm*'],do_erc=True,pins=[ Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='GTS3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='P4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='GTS0',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='9',name='P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='GCK0',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='P50',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='P80',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='P31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='P51',func=Pin.BIDIR,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='P91',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='P12',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='72',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='P92',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='TDI',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='VCCIO1',func=Pin.PWRIN,do_erc=True), Pin(num='83',name='P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='VCCIO1',func=Pin.PWRIN,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='P24',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='P64',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='94',name='P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='P25',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='CDRST',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='P45',func=Pin.BIDIR,do_erc=True), Pin(num='55',name='VCCIO1',func=Pin.PWRIN,do_erc=True), Pin(num='65',name='TMS',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='P75',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='P85',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='P26',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='46',name='P46',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='P76',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='VCCIO1',func=Pin.PWRIN,do_erc=True), Pin(num='37',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='47',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='57',name='P57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='TCK',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='P77',func=Pin.BIDIR,do_erc=True), Pin(num='87',name='P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='P28',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='48',name='P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='P78',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='P98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='P19',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='39',name='DGE',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='P59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='99',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='100',name='P100',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='P110',func=Pin.BIDIR,do_erc=True), Pin(num='120',name='P120',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='P130',func=Pin.BIDIR,do_erc=True), Pin(num='140',name='P140',func=Pin.BIDIR,do_erc=True), Pin(num='101',name='P101',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='P111',func=Pin.BIDIR,do_erc=True), Pin(num='121',name='P121',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='P131',func=Pin.BIDIR,do_erc=True), Pin(num='141',name='VCCIO2',func=Pin.PWRIN,do_erc=True), Pin(num='102',name='P102',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='P112',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='TDO',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='P132',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='P142',func=Pin.BIDIR,do_erc=True), Pin(num='103',name='P103',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='P113',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='133',name='P133',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='GSR',func=Pin.BIDIR,do_erc=True), Pin(num='104',name='P104',func=Pin.BIDIR,do_erc=True), Pin(num='114',name='P114',func=Pin.BIDIR,do_erc=True), Pin(num='124',name='P124',func=Pin.BIDIR,do_erc=True), Pin(num='134',name='P134',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='105',name='P105',func=Pin.BIDIR,do_erc=True), Pin(num='115',name='P115',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='P125',func=Pin.BIDIR,do_erc=True), Pin(num='135',name='P135',func=Pin.BIDIR,do_erc=True), Pin(num='106',name='P106',func=Pin.BIDIR,do_erc=True), Pin(num='116',name='P116',func=Pin.BIDIR,do_erc=True), Pin(num='126',name='P126',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='P136',func=Pin.BIDIR,do_erc=True), Pin(num='107',name='P107',func=Pin.BIDIR,do_erc=True), Pin(num='117',name='P117',func=Pin.BIDIR,do_erc=True), Pin(num='127',name='VCCIO2',func=Pin.PWRIN,do_erc=True), Pin(num='137',name='P137',func=Pin.BIDIR,do_erc=True), Pin(num='108',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='118',name='P118',func=Pin.BIDIR,do_erc=True), Pin(num='128',name='P128',func=Pin.BIDIR,do_erc=True), Pin(num='138',name='P138',func=Pin.BIDIR,do_erc=True), Pin(num='109',name='VCCIO2',func=Pin.PWRIN,do_erc=True), Pin(num='119',name='P119',func=Pin.BIDIR,do_erc=True), Pin(num='129',name='P129',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='P139',func=Pin.BIDIR,do_erc=True)]), Part(name='XC2C256-VQ100',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC2S100TQ144',dest=TEMPLATE,tool=SKIDL,keywords='FPGA',description='spartan 2',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='TCK',do_erc=True), Pin(num='3',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='10',name='IO7P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='/WR',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='IO/D5',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='80',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='/CS',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='IO/IRDY',func=Pin.BIDIR,do_erc=True), Pin(num='61',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='71',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='81',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='91',name='I/GCK1',do_erc=True), Pin(num='12',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='TDI',do_erc=True), Pin(num='42',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='62',name='IO/D6',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='DONE',func=Pin.OPENCOLL,do_erc=True), Pin(num='82',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='13',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='43',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='63',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='83',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='24',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='34',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='44',name='IO/D1',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='IO/TRDY',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='94',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='I/GCK3',do_erc=True), Pin(num='25',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='35',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='45',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='65',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='26',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='46',name='IO/D2',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='27',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='CCLK',do_erc=True), Pin(num='47',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='IO/D4',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='IO/D7',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='87',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='I/GCK2',do_erc=True), Pin(num='28',name='IO/REF',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='BUSY/DOUT',func=Pin.OUTPUT,do_erc=True), Pin(num='48',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='INIT/IO',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='I/CCK0',do_erc=True), Pin(num='98',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='19',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='D0/DIN',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='IO/D3',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='PROG',do_erc=True), Pin(num='79',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='99',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='120',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='140',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='101',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='M1',do_erc=True), Pin(num='121',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='141',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='102',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='TMS',do_erc=True), Pin(num='103',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='133',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='114',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='124',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='134',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='115',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='135',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='106',name='M2',do_erc=True), Pin(num='116',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='126',name='IO/TRDY',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='107',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='117',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='127',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='137',name='139/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='108',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='118',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='128',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='138',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='109',name='M0',do_erc=True), Pin(num='119',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='129',name='IO/IRDY',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='IO/VREF',func=Pin.BIDIR,do_erc=True)]), Part(name='XC2S150PQ208',dest=TEMPLATE,tool=SKIDL,keywords='FPGA',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='TMS',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='IO7P3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='IO7P4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='IO7P5',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='IO7VRP6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='IO7P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='IO7P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='IO7P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='IO7P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='IO7VRP20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='IO6P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='50',name='M1',do_erc=True), Pin(num='60',name='IO5P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='IO5P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='GCK0',do_erc=True), Pin(num='90',name='IO4P90',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='21',name='IO7P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='IO6VRP31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='IO6P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='IO5P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='IO5P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='IO4P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='22',name='IO7P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='42',name='IO6P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='M0',do_erc=True), Pin(num='62',name='IO5P62',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='82',name='IO4P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='13',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='23',name='IO7P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='IO6P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='IO6P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='63',name='IO5P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='IO5VRP73',func=Pin.BIDIR,do_erc=True), Pin(num='83',name='IO4P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='14',name='IO7P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='IRDY7',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='IO6P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='IO6P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='M2',do_erc=True), Pin(num='64',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='74',name='IO5P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='IO4VRP84',func=Pin.BIDIR,do_erc=True), Pin(num='94',name='IO4P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='IO7P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='35',name='IO6P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='IO6VRP45',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='85',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='95',name='IO4P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='IO7P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='IO6P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='IO6P46',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='76',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='86',name='IO4P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='IO4P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='IO7P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='TRDY6',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='IO6P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='IO6P47',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='IO5P57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='IO5P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='GCK1',do_erc=True), Pin(num='87',name='IO4P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='IO4P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='IO7P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='38',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='IO6P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='IO5P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='IO5P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='88',name='IO4P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='IO4VRP98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='29',name='IO6P29',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='49',name='IO6P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='IO5VRP59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='IO5P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='89',name='IO4P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='IO4P99',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='IO4P100',func=Pin.BIDIR,do_erc=True), Pin(num='200',name='IO0P200',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='IO3P110',func=Pin.BIDIR,do_erc=True), Pin(num='120',name='IO3P120',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='140',name='IO2P140',func=Pin.BIDIR,do_erc=True), Pin(num='150',name='IO2VRP150',func=Pin.BIDIR,do_erc=True), Pin(num='160',name='/CS',func=Pin.BIDIR,do_erc=True), Pin(num='170',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='180',name='IO1P180',func=Pin.BIDIR,do_erc=True), Pin(num='190',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='101',name='IO4P101',func=Pin.BIDIR,do_erc=True), Pin(num='201',name='IO0P201',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='IO3VRP111',func=Pin.BIDIR,do_erc=True), Pin(num='121',name='IO3P121',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='141',name='IO2P141',func=Pin.BIDIR,do_erc=True), Pin(num='151',name='IO2P151',func=Pin.BIDIR,do_erc=True), Pin(num='161',name='/WR',func=Pin.BIDIR,do_erc=True), Pin(num='171',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='181',name='IO1P181',func=Pin.BIDIR,do_erc=True), Pin(num='191',name='IO0P191',func=Pin.BIDIR,do_erc=True), Pin(num='102',name='IO4P102',func=Pin.BIDIR,do_erc=True), Pin(num='202',name='IO0P202',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='IO3P112',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='IO3P122',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='IRDY2',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='IO2/D2P142',func=Pin.BIDIR,do_erc=True), Pin(num='152',name='IO2P152',func=Pin.BIDIR,do_erc=True), Pin(num='162',name='IO1P162',func=Pin.BIDIR,do_erc=True), Pin(num='172',name='IO1P172',func=Pin.BIDIR,do_erc=True), Pin(num='182',name='GCK2',do_erc=True), Pin(num='192',name='IO0P192',func=Pin.BIDIR,do_erc=True), Pin(num='103',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='203',name='IO0VRP203',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='IO3P113',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='IO3P123',func=Pin.BIDIR,do_erc=True), Pin(num='133',name='IO2P133',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='153',name='D0/DIN',func=Pin.BIDIR,do_erc=True), Pin(num='163',name='IO1P163',func=Pin.BIDIR,do_erc=True), Pin(num='173',name='IO1P173',func=Pin.BIDIR,do_erc=True), Pin(num='183',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='193',name='IO0P193',func=Pin.BIDIR,do_erc=True), Pin(num='104',name='DONE',func=Pin.BIDIR,do_erc=True), Pin(num='204',name='IO0P204',func=Pin.BIDIR,do_erc=True), Pin(num='114',name='IO3P114',func=Pin.BIDIR,do_erc=True), Pin(num='124',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='134',name='IO2P134',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='154',name='BUSY/DOUT',func=Pin.BIDIR,do_erc=True), Pin(num='164',name='IO1VRP164',func=Pin.BIDIR,do_erc=True), Pin(num='174',name='IO1P174',func=Pin.BIDIR,do_erc=True), Pin(num='184',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='194',name='IO0P194',func=Pin.BIDIR,do_erc=True), Pin(num='105',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='205',name='IO0P205',func=Pin.BIDIR,do_erc=True), Pin(num='115',name='IO3/D6P115',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='IO3VRP125',func=Pin.BIDIR,do_erc=True), Pin(num='135',name='IO2/D3P135',func=Pin.BIDIR,do_erc=True), Pin(num='145',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='155',name='CCLK',func=Pin.BIDIR,do_erc=True), Pin(num='165',name='IO1P165',func=Pin.BIDIR,do_erc=True), Pin(num='175',name='IO1P175',func=Pin.BIDIR,do_erc=True), Pin(num='185',name='GCK3',do_erc=True), Pin(num='195',name='IO0P195',func=Pin.BIDIR,do_erc=True), Pin(num='106',name='/PROG',do_erc=True), Pin(num='206',name='IO0P206',func=Pin.BIDIR,do_erc=True), Pin(num='116',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='126',name='IO3/D4P126',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='IO2VRP136',func=Pin.BIDIR,do_erc=True), Pin(num='146',name='IO2/D1P46',func=Pin.BIDIR,do_erc=True), Pin(num='156',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='166',name='IO1P166',func=Pin.BIDIR,do_erc=True), Pin(num='176',name='IO1P176',func=Pin.BIDIR,do_erc=True), Pin(num='186',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='196',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='107',name='/INIT',func=Pin.BIDIR,do_erc=True), Pin(num='207',name='TCK',func=Pin.BIDIR,do_erc=True), Pin(num='117',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='127',name='IO3P127',func=Pin.BIDIR,do_erc=True), Pin(num='137',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='147',name='IO2P147',func=Pin.BIDIR,do_erc=True), Pin(num='157',name='TDO',func=Pin.BIDIR,do_erc=True), Pin(num='167',name='IO1P167',func=Pin.BIDIR,do_erc=True), Pin(num='177',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='187',name='IO0P187',func=Pin.BIDIR,do_erc=True), Pin(num='197',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='108',name='IO3/D7P108',func=Pin.BIDIR,do_erc=True), Pin(num='208',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='118',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='128',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='138',name='IO2P138',func=Pin.BIDIR,do_erc=True), Pin(num='148',name='IO2P148',func=Pin.BIDIR,do_erc=True), Pin(num='158',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='168',name='IO1P168',func=Pin.BIDIR,do_erc=True), Pin(num='178',name='IO1VRP178',func=Pin.BIDIR,do_erc=True), Pin(num='188',name='IO0P188',func=Pin.BIDIR,do_erc=True), Pin(num='198',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='109',name='IO3P109',func=Pin.BIDIR,do_erc=True), Pin(num='119',name='IO3/D5P119',func=Pin.BIDIR,do_erc=True), Pin(num='129',name='TRDY3',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='IO2P139',func=Pin.BIDIR,do_erc=True), Pin(num='149',name='IO2P149',func=Pin.BIDIR,do_erc=True), Pin(num='159',name='TDI',func=Pin.BIDIR,do_erc=True), Pin(num='169',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='179',name='IO1P179',func=Pin.BIDIR,do_erc=True), Pin(num='189',name='IO0VRP189',func=Pin.BIDIR,do_erc=True), Pin(num='199',name='IO0P199',func=Pin.BIDIR,do_erc=True)]), Part(name='XC2S200PQ208',dest=TEMPLATE,tool=SKIDL,keywords='FPGA',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='2',name='TMS',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='IO7P3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='IO7VRP4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='IO7P5',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='IO7VRP6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='IO7P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='IO7P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='IO7VRP9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='IO7P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='IO7VRP20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='IO6P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='50',name='M1',do_erc=True), Pin(num='60',name='IO5P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='IO5P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='GCK0',do_erc=True), Pin(num='90',name='IO4P90',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='21',name='IO7P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='IO6VRP31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='IO6P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='61',name='IO5P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='IO5P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='IO4P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='12',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='22',name='IO7P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='42',name='IO6VRP42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='M0',do_erc=True), Pin(num='62',name='IO5VRP62',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='82',name='IO4P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='13',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='23',name='IO7P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='IO6P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='IO6P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='63',name='IO5P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='IO5VRP73',func=Pin.BIDIR,do_erc=True), Pin(num='83',name='IO4P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='14',name='IO7P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='IRDY7',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='IO6P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='IO6P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='M2',do_erc=True), Pin(num='64',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='74',name='IO5P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='IO4VRP84',func=Pin.BIDIR,do_erc=True), Pin(num='94',name='IO4P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='IO7P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='35',name='IO6P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='IO6VRP45',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='75',name='IO5P75',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='95',name='IO4VRP95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='IO7P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='36',name='IO6P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='IO6P46',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='76',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='86',name='IO4P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='IO4P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='IO7P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='TRDY6',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='IO6P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='IO6VRP47',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='IO5VRP57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='IO5P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='GCK1',do_erc=True), Pin(num='87',name='IO4P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='IO4P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='IO7P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='38',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='48',name='IO6P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='IO5P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='IO5P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='88',name='IO4P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='IO4VRP98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='29',name='IO6P29',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='49',name='IO6P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='IO5VRP59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='IO5P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='89',name='IO4P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='IO4P99',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='IO4VRP100',func=Pin.BIDIR,do_erc=True), Pin(num='200',name='IO0VRP200',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='IO3P110',func=Pin.BIDIR,do_erc=True), Pin(num='120',name='IO3P120',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='140',name='IO2P140',func=Pin.BIDIR,do_erc=True), Pin(num='150',name='IO2VRP150',func=Pin.BIDIR,do_erc=True), Pin(num='160',name='/CS',func=Pin.BIDIR,do_erc=True), Pin(num='170',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='180',name='IO1P180',func=Pin.BIDIR,do_erc=True), Pin(num='190',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='101',name='IO4P101',func=Pin.BIDIR,do_erc=True), Pin(num='201',name='IO0P201',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='IO3VRP111',func=Pin.BIDIR,do_erc=True), Pin(num='121',name='IO3P121',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='141',name='IO2P141',func=Pin.BIDIR,do_erc=True), Pin(num='151',name='IO2P151',func=Pin.BIDIR,do_erc=True), Pin(num='161',name='/WR',func=Pin.BIDIR,do_erc=True), Pin(num='171',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='181',name='IO1P181',func=Pin.BIDIR,do_erc=True), Pin(num='191',name='IO0P191',func=Pin.BIDIR,do_erc=True), Pin(num='102',name='IO4P102',func=Pin.BIDIR,do_erc=True), Pin(num='202',name='IO0P202',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='IO3P112',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='IO3P122',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='IRDY2',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='IO2/D2P142',func=Pin.BIDIR,do_erc=True), Pin(num='152',name='IO2VRP152',func=Pin.BIDIR,do_erc=True), Pin(num='162',name='IO1VRP162',func=Pin.BIDIR,do_erc=True), Pin(num='172',name='IO1P172',func=Pin.BIDIR,do_erc=True), Pin(num='182',name='GCK2',do_erc=True), Pin(num='192',name='IO0P192',func=Pin.BIDIR,do_erc=True), Pin(num='103',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='203',name='IO0VRP203',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='IO3P113',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='IO3P123',func=Pin.BIDIR,do_erc=True), Pin(num='133',name='IO2P133',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='153',name='D0/DIN',func=Pin.BIDIR,do_erc=True), Pin(num='163',name='IO1P163',func=Pin.BIDIR,do_erc=True), Pin(num='173',name='IO1P173',func=Pin.BIDIR,do_erc=True), Pin(num='183',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='193',name='IO0P193',func=Pin.BIDIR,do_erc=True), Pin(num='104',name='DONE',func=Pin.BIDIR,do_erc=True), Pin(num='204',name='IO0P204',func=Pin.BIDIR,do_erc=True), Pin(num='114',name='IO3VRP114',func=Pin.BIDIR,do_erc=True), Pin(num='124',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='134',name='IO2P134',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='154',name='BUSY/DOUT',func=Pin.BIDIR,do_erc=True), Pin(num='164',name='IO1VRP164',func=Pin.BIDIR,do_erc=True), Pin(num='174',name='IO1P174',func=Pin.BIDIR,do_erc=True), Pin(num='184',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='194',name='IO0P194',func=Pin.BIDIR,do_erc=True), Pin(num='105',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='205',name='IO0VRP205',func=Pin.BIDIR,do_erc=True), Pin(num='115',name='IO3/D6P115',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='IO3VRP125',func=Pin.BIDIR,do_erc=True), Pin(num='135',name='IO2/D3P135',func=Pin.BIDIR,do_erc=True), Pin(num='145',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='155',name='CCLK',func=Pin.BIDIR,do_erc=True), Pin(num='165',name='IO1P165',func=Pin.BIDIR,do_erc=True), Pin(num='175',name='IO1P175',func=Pin.BIDIR,do_erc=True), Pin(num='185',name='GCK3',do_erc=True), Pin(num='195',name='IO0P195',func=Pin.BIDIR,do_erc=True), Pin(num='106',name='/PROG',do_erc=True), Pin(num='206',name='IO0P206',func=Pin.BIDIR,do_erc=True), Pin(num='116',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='126',name='IO3/D4P126',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='IO2VRP136',func=Pin.BIDIR,do_erc=True), Pin(num='146',name='IO2/D1P46',func=Pin.BIDIR,do_erc=True), Pin(num='156',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='166',name='IO1P166',func=Pin.BIDIR,do_erc=True), Pin(num='176',name='IO1P176',func=Pin.BIDIR,do_erc=True), Pin(num='186',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='196',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='107',name='/INIT',func=Pin.BIDIR,do_erc=True), Pin(num='207',name='TCK',func=Pin.BIDIR,do_erc=True), Pin(num='117',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='127',name='IO3P127',func=Pin.BIDIR,do_erc=True), Pin(num='137',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='147',name='IO2VRP147',func=Pin.BIDIR,do_erc=True), Pin(num='157',name='TDO',func=Pin.BIDIR,do_erc=True), Pin(num='167',name='IO1VRP167',func=Pin.BIDIR,do_erc=True), Pin(num='177',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='187',name='IO0P187',func=Pin.BIDIR,do_erc=True), Pin(num='197',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='108',name='IO3/D7P108',func=Pin.BIDIR,do_erc=True), Pin(num='208',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='118',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='128',name='VCCINT',func=Pin.PASSIVE,do_erc=True), Pin(num='138',name='IO2P138',func=Pin.BIDIR,do_erc=True), Pin(num='148',name='IO2P148',func=Pin.BIDIR,do_erc=True), Pin(num='158',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='168',name='IO1P168',func=Pin.BIDIR,do_erc=True), Pin(num='178',name='IO1VRP178',func=Pin.BIDIR,do_erc=True), Pin(num='188',name='IO0P188',func=Pin.BIDIR,do_erc=True), Pin(num='198',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='109',name='IO3VRP109',func=Pin.BIDIR,do_erc=True), Pin(num='119',name='IO3/D5P119',func=Pin.BIDIR,do_erc=True), Pin(num='129',name='TRDY3',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='IO2P139',func=Pin.BIDIR,do_erc=True), Pin(num='149',name='IO2P149',func=Pin.BIDIR,do_erc=True), Pin(num='159',name='TDI',func=Pin.BIDIR,do_erc=True), Pin(num='169',name='GND',func=Pin.PASSIVE,do_erc=True), Pin(num='179',name='IO1P179',func=Pin.BIDIR,do_erc=True), Pin(num='189',name='IO0VRP189',func=Pin.BIDIR,do_erc=True), Pin(num='199',name='IO0P199',func=Pin.BIDIR,do_erc=True)]), Part(name='XC2S300PQ208',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='TMS',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='IO7P3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='IO7VRP4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='IO7P5',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='IO7VRP6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='IO7P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='IO7P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='IO7VRP9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='IO7VRP10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='IO7VRP20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='IO6P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='IO6P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='M1',do_erc=True), Pin(num='60',name='IO5P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='IO5P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='GCK0',do_erc=True), Pin(num='90',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='IO7P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='IO7P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='IO6VRP31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='IO6VRP41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='IO5P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='IO5P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='IO4P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='22',name='IO7P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='42',name='IO6P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='M0',do_erc=True), Pin(num='62',name='IO5P62',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='82',name='IO4P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='13',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='23',name='IO7P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='IO6P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='IO6P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='63',name='IO5VRP63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='IO5VRP73',func=Pin.BIDIR,do_erc=True), Pin(num='83',name='IO4P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='IO4P93',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='24',name='IRDY7',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='IO6P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='IO6P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='M2',do_erc=True), Pin(num='64',name='IO5P64',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='IO5P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='IO4VRP84',func=Pin.BIDIR,do_erc=True), Pin(num='94',name='IO4VRP94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='IO7P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='35',name='IO6P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='IO6VRP45',func=Pin.BIDIR,do_erc=True), Pin(num='55',name='IO5P55',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='75',name='IO5P75',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='95',name='IO4P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='IO7P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='IO6P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='IO6P46',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='IO5P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='76',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='86',name='IO4P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='IO4P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='IO7P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='TRDY6',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='47',name='IO6VRP47',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='IO5VRP57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='77',name='GCK1',do_erc=True), Pin(num='87',name='IO4P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='IO4P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='IO7P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='38',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='IO6P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='IO5P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='IO5P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='88',name='IO4P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='IO4VRP98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='29',name='IO6P29',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='49',name='IO6P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='IO5VRP59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='IO5P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='89',name='IO4P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='IO4P99',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='IO4VRP100',func=Pin.BIDIR,do_erc=True), Pin(num='200',name='IO0P200',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='IO3P110',func=Pin.BIDIR,do_erc=True), Pin(num='120',name='IO3/D5P120',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='140',name='IO2P140',func=Pin.BIDIR,do_erc=True), Pin(num='150',name='IO2VRP150',func=Pin.BIDIR,do_erc=True), Pin(num='160',name='/CS',func=Pin.BIDIR,do_erc=True), Pin(num='170',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='180',name='IO1P180',func=Pin.BIDIR,do_erc=True), Pin(num='190',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='101',name='IO4P101',func=Pin.BIDIR,do_erc=True), Pin(num='201',name='IO0P201',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='IO3VRP111',func=Pin.BIDIR,do_erc=True), Pin(num='121',name='IO3P121',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='141',name='IO2/D2P141',func=Pin.BIDIR,do_erc=True), Pin(num='151',name='IO2P151',func=Pin.BIDIR,do_erc=True), Pin(num='161',name='/WR',func=Pin.BIDIR,do_erc=True), Pin(num='171',name='VCCO',func=Pin.PASSIVE,do_erc=True), Pin(num='181',name='IO1P181',func=Pin.BIDIR,do_erc=True), Pin(num='191',name='IO0P191',func=Pin.BIDIR,do_erc=True), Pin(num='102',name='IO4P102',func=Pin.BIDIR,do_erc=True), Pin(num='202',name='IO0P202',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='IO3P112',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='IO3P122',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='IRDY2',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='152',name='IO2VRP152',func=Pin.BIDIR,do_erc=True), Pin(num='162',name='IO1VRP162',func=Pin.BIDIR,do_erc=True), Pin(num='172',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='182',name='GCK2',do_erc=True), Pin(num='192',name='IO0P192',func=Pin.BIDIR,do_erc=True), Pin(num='103',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='203',name='IO0VRP203',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='IO3P113',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='IO3P123',func=Pin.BIDIR,do_erc=True), Pin(num='133',name='IO2P133',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='153',name='D0/DIN',func=Pin.BIDIR,do_erc=True), Pin(num='163',name='IO1P163',func=Pin.BIDIR,do_erc=True), Pin(num='173',name='IO1P173',func=Pin.BIDIR,do_erc=True), Pin(num='183',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='193',name='IO0P193',func=Pin.BIDIR,do_erc=True), Pin(num='104',name='DONE',func=Pin.BIDIR,do_erc=True), Pin(num='204',name='IO0P204',func=Pin.BIDIR,do_erc=True), Pin(num='114',name='IO3P114',func=Pin.BIDIR,do_erc=True), Pin(num='124',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='134',name='IO2P134',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='154',name='BUSY/DOUT',func=Pin.BIDIR,do_erc=True), Pin(num='164',name='IO1VRP164',func=Pin.BIDIR,do_erc=True), Pin(num='174',name='IO1P174',func=Pin.BIDIR,do_erc=True), Pin(num='184',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='194',name='IO0P194',func=Pin.BIDIR,do_erc=True), Pin(num='105',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='205',name='IO0VRP205',func=Pin.BIDIR,do_erc=True), Pin(num='115',name='IO3VRP115',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='IO3VRP125',func=Pin.BIDIR,do_erc=True), Pin(num='135',name='IO2/D3P135',func=Pin.BIDIR,do_erc=True), Pin(num='145',name='IO2/D1P145',func=Pin.BIDIR,do_erc=True), Pin(num='155',name='CCLK',func=Pin.BIDIR,do_erc=True), Pin(num='165',name='IO1P165',func=Pin.BIDIR,do_erc=True), Pin(num='175',name='IO1P175',func=Pin.BIDIR,do_erc=True), Pin(num='185',name='GCK3',do_erc=True), Pin(num='195',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='106',name='/PROG',do_erc=True), Pin(num='206',name='IO0P206',func=Pin.BIDIR,do_erc=True), Pin(num='116',name='IO3/D6P116',func=Pin.BIDIR,do_erc=True), Pin(num='126',name='IO3/D4P126',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='IO2VRP136',func=Pin.BIDIR,do_erc=True), Pin(num='146',name='IO2VRP146',func=Pin.BIDIR,do_erc=True), Pin(num='156',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='166',name='IO1P166',func=Pin.BIDIR,do_erc=True), Pin(num='176',name='IO1P176',func=Pin.BIDIR,do_erc=True), Pin(num='186',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='196',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='107',name='/INIT',func=Pin.BIDIR,do_erc=True), Pin(num='207',name='TCK',func=Pin.BIDIR,do_erc=True), Pin(num='117',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='127',name='IO3P127',func=Pin.BIDIR,do_erc=True), Pin(num='137',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='147',name='IO2P147',func=Pin.BIDIR,do_erc=True), Pin(num='157',name='TDO',func=Pin.BIDIR,do_erc=True), Pin(num='167',name='IO1P167',func=Pin.BIDIR,do_erc=True), Pin(num='177',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='187',name='IO0P187',func=Pin.BIDIR,do_erc=True), Pin(num='197',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='108',name='IO3/D7P108',func=Pin.BIDIR,do_erc=True), Pin(num='208',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='118',name='VCCO',func=Pin.PWRIN,do_erc=True), Pin(num='128',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='138',name='IO2P138',func=Pin.BIDIR,do_erc=True), Pin(num='148',name='IO2P148',func=Pin.BIDIR,do_erc=True), Pin(num='158',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='168',name='IO1VRP168',func=Pin.BIDIR,do_erc=True), Pin(num='178',name='IO1VRP178',func=Pin.BIDIR,do_erc=True), Pin(num='188',name='IO0P188',func=Pin.BIDIR,do_erc=True), Pin(num='198',name='IO0P198',func=Pin.BIDIR,do_erc=True), Pin(num='109',name='IO3VRP109',func=Pin.BIDIR,do_erc=True), Pin(num='119',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='129',name='TRDY3',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='IO2P139',func=Pin.BIDIR,do_erc=True), Pin(num='149',name='IO2P149',func=Pin.BIDIR,do_erc=True), Pin(num='159',name='TDI',func=Pin.BIDIR,do_erc=True), Pin(num='169',name='IO1P169',func=Pin.BIDIR,do_erc=True), Pin(num='179',name='IO1P179',func=Pin.BIDIR,do_erc=True), Pin(num='189',name='IO0VRP189',func=Pin.BIDIR,do_erc=True), Pin(num='199',name='IO0VRP199',func=Pin.BIDIR,do_erc=True)]), Part(name='XC2S400FT256',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC2S50-PQ208',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC2S64A-xQFG48',dest=TEMPLATE,tool=SKIDL,description='Xilinx CoolRunner',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='GTS0',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='VCCjtag',func=Pin.PWRIN,do_erc=True), Pin(num='4',name='A3',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='A2',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='B1',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='B2',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='B3',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='B4',func=Pin.PASSIVE,do_erc=True), Pin(num='10',name='B5',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='D7',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='D16',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='11',name='GCK0',func=Pin.PASSIVE,do_erc=True), Pin(num='21',name='TDI',do_erc=True), Pin(num='31',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='41',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='TMS',do_erc=True), Pin(num='32',name='C15',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='VCCio2',func=Pin.PWRIN,do_erc=True), Pin(num='13',name='GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='TCK',do_erc=True), Pin(num='33',name='C14',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='C3',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='B12',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='D10',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='C12',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='C2',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='B13',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='D11',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='C11',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='C1',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='26',name='D12',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='C10',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='GSR',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='D1',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='D13',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='C9',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='D2',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='D13',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='C6',func=Pin.BIDIR,do_erc=True), Pin(num='48',name='GTS3',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='VCCio1',func=Pin.PWRIN,do_erc=True), Pin(num='29',name='VCCint',func=Pin.PWRIN,do_erc=True), Pin(num='39',name='C5',func=Pin.BIDIR,do_erc=True)]), Part(name='XC3020-PC68',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['XC3030-PC68']), Part(name='XC3030-PC44',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3030-PC84',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['XC3042-PC84']), Part(name='XC3030-VQ100',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3042-VQ100',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3S1400A/FG484',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3S200AN/FT256',dest=TEMPLATE,tool=SKIDL,description='BGA256/1mm',ref_prefix='U',num_units=1,fplist=['BGA256'],do_erc=True,pins=[ Pin(num='A1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B1',name='TDI',do_erc=True), Pin(num='C1',name='IO_L01N_3',func=Pin.BIDIR,do_erc=True), Pin(num='D1',name='IO_L03P_3',func=Pin.BIDIR,do_erc=True), Pin(num='E1',name='IO_L03N_3',func=Pin.BIDIR,do_erc=True), Pin(num='F1',name='IO_L08P_3',func=Pin.BIDIR,do_erc=True), Pin(num='G1',name='IO_L08N_3/VREF_3',func=Pin.BIDIR,do_erc=True), Pin(num='H1',name='IO_L11N_3/LHCLK1',func=Pin.BIDIR,do_erc=True), Pin(num='J1',name='IO_L14N_3/LHCLK5',func=Pin.BIDIR,do_erc=True), Pin(num='K1',name='IO_L15N_3/LHCLK7',func=Pin.BIDIR,do_erc=True), Pin(num='L1',name='IO_L16P_3/VREF_3',func=Pin.BIDIR,do_erc=True), Pin(num='M1',name='IO_L20P_3',func=Pin.BIDIR,do_erc=True), Pin(num='N1',name='IO_L20N_3',func=Pin.BIDIR,do_erc=True), Pin(num='P1',name='IO_L22N_3',func=Pin.BIDIR,do_erc=True), Pin(num='R1',name='IO_L23P_3',func=Pin.BIDIR,do_erc=True), Pin(num='T1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='A2',name='/PROG',func=Pin.BIDIR,do_erc=True), Pin(num='B2',name='TMS',do_erc=True), Pin(num='C2',name='IO_L01P_3',func=Pin.BIDIR,do_erc=True), Pin(num='D2',name='VCCO3',func=Pin.PASSIVE,do_erc=True), Pin(num='E2',name='IO_L05N_3',func=Pin.BIDIR,do_erc=True), Pin(num='F2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='G2',name='IO_L11P_3/LHCLK0',func=Pin.BIDIR,do_erc=True), Pin(num='H2',name='VCCO3',func=Pin.PWRIN,do_erc=True), Pin(num='J2',name='IO_L14P_3/LHCLK4',func=Pin.BIDIR,do_erc=True), Pin(num='K2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L2',name='IO_L16N_3',func=Pin.BIDIR,do_erc=True), Pin(num='M2',name='VCCO3',func=Pin.PWRIN,do_erc=True), Pin(num='N2',name='IO_L22P_3',func=Pin.BIDIR,do_erc=True), Pin(num='P2',name='IO_L23N_3',func=Pin.BIDIR,do_erc=True), Pin(num='R2',name='IO_L02P_2/M2',func=Pin.BIDIR,do_erc=True), Pin(num='T2',name='IO_L02N_2/CSO_B',func=Pin.BIDIR,do_erc=True), Pin(num='A3',name='IO_L19P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B3',name='IO_L19N_0',func=Pin.BIDIR,do_erc=True), Pin(num='C3',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='D3',name='IO_L02N_3',func=Pin.BIDIR,do_erc=True), Pin(num='E3',name='IO_L05P_3',func=Pin.BIDIR,do_erc=True), Pin(num='F3',name='IO_L07P_3',func=Pin.BIDIR,do_erc=True), Pin(num='G3',name='IO_L09P_3',func=Pin.BIDIR,do_erc=True), Pin(num='H3',name='IO_L12P_3/LHCLK2',func=Pin.BIDIR,do_erc=True), Pin(num='J3',name='IO_L12N_3/IRDY2/LHCLK3',func=Pin.BIDIR,do_erc=True), Pin(num='K3',name='IO_L15P_3/TRDY2/LHCLK6',func=Pin.BIDIR,do_erc=True), Pin(num='L3',name='IO_L18N_3',func=Pin.BIDIR,do_erc=True), Pin(num='M3',name='IO_L19P_3',func=Pin.BIDIR,do_erc=True), Pin(num='N3',name='IO_L24P_3',func=Pin.BIDIR,do_erc=True), Pin(num='P3',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R3',name='IO_L03P_2/RDWR_B',func=Pin.BIDIR,do_erc=True), Pin(num='T3',name='IO_L03N_2/VS2',func=Pin.BIDIR,do_erc=True), Pin(num='A4',name='IO_L18P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B4',name='IO_L18N_0',func=Pin.BIDIR,do_erc=True), Pin(num='C4',name='IO_L20P_0/VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='D4',name='IO_L02P_3',func=Pin.BIDIR,do_erc=True), Pin(num='E4',name='IP_L04P_3',do_erc=True), Pin(num='F4',name='IP_L04N_3/VREF_3',do_erc=True), Pin(num='G4',name='IO_L07N_3',func=Pin.BIDIR,do_erc=True), Pin(num='H4',name='IO_L09N_3',func=Pin.BIDIR,do_erc=True), Pin(num='J4',name='IO_L17P_3',func=Pin.BIDIR,do_erc=True), Pin(num='K4',name='IO_L18P_3',func=Pin.BIDIR,do_erc=True), Pin(num='L4',name='IO_L19N_3',func=Pin.BIDIR,do_erc=True), Pin(num='M4',name='IO_L24N_3',func=Pin.BIDIR,do_erc=True), Pin(num='N4',name='IO_L01P_2/M1',func=Pin.BIDIR,do_erc=True), Pin(num='P4',name='IO_L01N_2/M0',func=Pin.BIDIR,do_erc=True), Pin(num='R4',name='VCCO2',func=Pin.PWRIN,do_erc=True), Pin(num='T4',name='IO_L05P_2',func=Pin.BIDIR,do_erc=True), Pin(num='A5',name='IO_L17P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B5',name='VCCO0',func=Pin.PWRIN,do_erc=True), Pin(num='C5',name='IO_L17N_0',func=Pin.BIDIR,do_erc=True), Pin(num='D5',name='IO_L20N_0/PUDC_B',func=Pin.BIDIR,do_erc=True), Pin(num='E5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='F5',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='G5',name='IP_L06N_3/VREF_3',do_erc=True), Pin(num='H5',name='IO_L10N_3',func=Pin.BIDIR,do_erc=True), Pin(num='J5',name='VCCO3',func=Pin.PWRIN,do_erc=True), Pin(num='K5',name='IP_L21P_3',do_erc=True), Pin(num='L5',name='IP_L25P_3',do_erc=True), Pin(num='M5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N5',name='IP_2/VREF_2',do_erc=True), Pin(num='P5',name='IO_L04N_2/VS0',func=Pin.BIDIR,do_erc=True), Pin(num='R5',name='IO_L05N_2',func=Pin.BIDIR,do_erc=True), Pin(num='T5',name='IO_L06P_2/D7',func=Pin.BIDIR,do_erc=True), Pin(num='A6',name='IO_L15P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B6',name='IO_L15N_0',func=Pin.BIDIR,do_erc=True), Pin(num='C6',name='IO_L16N_0',func=Pin.BIDIR,do_erc=True), Pin(num='D6',name='IP_0',do_erc=True), Pin(num='E6',name='IP_0',do_erc=True), Pin(num='F6',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='G6',name='IP_L06P_3',do_erc=True), Pin(num='H6',name='IO_L10P_3',func=Pin.BIDIR,do_erc=True), Pin(num='J6',name='IO_L17N_3',func=Pin.BIDIR,do_erc=True), Pin(num='K6',name='IP_L21N_3',do_erc=True), Pin(num='L6',name='IP_L25N_3/VREF_3',do_erc=True), Pin(num='M6',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='N6',name='IO_L04P_2/VS1',func=Pin.BIDIR,do_erc=True), Pin(num='P6',name='IO_L07N_2',func=Pin.BIDIR,do_erc=True), Pin(num='R6',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='T6',name='IO_L06N_2/D6',func=Pin.BIDIR,do_erc=True), Pin(num='A7',name='IO_L13P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C7',name='IO_L13N_0',func=Pin.BIDIR,do_erc=True), Pin(num='D7',name='IO_L16P_0',func=Pin.BIDIR,do_erc=True), Pin(num='E7',name='IO_L14N_0/VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='F7',name='IP_0',do_erc=True), Pin(num='G7',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='H7',name='IP_L13P_3',do_erc=True), Pin(num='J7',name='IP_L13N_3',do_erc=True), Pin(num='K7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L7',name='IP_2',do_erc=True), Pin(num='M7',name='IP_2/VREF_2',do_erc=True), Pin(num='N7',name='IO_L07P_2',func=Pin.BIDIR,do_erc=True), Pin(num='P7',name='IO_L08P_2/D5',func=Pin.BIDIR,do_erc=True), Pin(num='R7',name='IO_L09P_2/GCLK12',func=Pin.BIDIR,do_erc=True), Pin(num='T7',name='IO_L09N_2/GCLK13',func=Pin.BIDIR,do_erc=True), Pin(num='A8',name='IO_L12P_0/GCLK10',func=Pin.BIDIR,do_erc=True), Pin(num='B8',name='IO_L12N_0/GCLK11',func=Pin.BIDIR,do_erc=True), Pin(num='C8',name='IO_L11P_0/GCLK8',func=Pin.BIDIR,do_erc=True), Pin(num='D8',name='IO_L11N_0/GCLK9',func=Pin.BIDIR,do_erc=True), Pin(num='E8',name='VCCO0',func=Pin.PWRIN,do_erc=True), Pin(num='F8',name='IO_L14P_0',func=Pin.BIDIR,do_erc=True), Pin(num='G8',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H8',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='J8',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='K8',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L8',name='IP_2',do_erc=True), Pin(num='M8',name='IP_2/VREF_2',do_erc=True), Pin(num='N8',name='IO_L08N_2/D4',func=Pin.BIDIR,do_erc=True), Pin(num='P8',name='IO_L10P_2/GCLK14',func=Pin.BIDIR,do_erc=True), Pin(num='R8',name='VCCO2',func=Pin.PWRIN,do_erc=True), Pin(num='T8',name='IO_L10N_2/GCLK15',func=Pin.BIDIR,do_erc=True), Pin(num='A9',name='IO_L10N_0/GCLK7',func=Pin.BIDIR,do_erc=True), Pin(num='B9',name='VCCO0',func=Pin.PWRIN,do_erc=True), Pin(num='C9',name='IO_L10P_0/GCLK6',func=Pin.BIDIR,do_erc=True), Pin(num='D9',name='IO_L09N_0/GCLK5',func=Pin.BIDIR,do_erc=True), Pin(num='E9',name='IP_0/VREF_0',do_erc=True), Pin(num='F9',name='IP_0',do_erc=True), Pin(num='G9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='H9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='K9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L9',name='IP_2/VREF_2',do_erc=True), Pin(num='M9',name='VCCO2',func=Pin.PWRIN,do_erc=True), Pin(num='N9',name='IO_L11P_2/GCLK0',func=Pin.BIDIR,do_erc=True), Pin(num='P9',name='IO_L11N_2/GCLK1',func=Pin.BIDIR,do_erc=True), Pin(num='R9',name='IO_L12P_2/GCLK2',func=Pin.BIDIR,do_erc=True), Pin(num='T9',name='IO_L12N_2/GCLK3',func=Pin.BIDIR,do_erc=True), Pin(num='A10',name='IO_L08N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B10',name='IO_L08P_0',func=Pin.BIDIR,do_erc=True), Pin(num='C10',name='IO_L09P_0/GCLK4',func=Pin.BIDIR,do_erc=True), Pin(num='D10',name='IO_L06P_0',func=Pin.BIDIR,do_erc=True), Pin(num='E10',name='IO_L06N_0/VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='F10',name='IP_0',do_erc=True), Pin(num='G10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H10',name='IP_L13P_1',do_erc=True), Pin(num='J10',name='IP_L09P_1/VREF_1',do_erc=True), Pin(num='K10',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L10',name='IP_2/VREF_2',do_erc=True), Pin(num='M10',name='IO_L13N_2',func=Pin.BIDIR,do_erc=True), Pin(num='N10',name='IO_L13P_2',func=Pin.BIDIR,do_erc=True), Pin(num='P10',name='IO_L14N_2/MOSI/CSI_B',func=Pin.BIDIR,do_erc=True), Pin(num='R10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='T10',name='IO_L14P_2',func=Pin.BIDIR,do_erc=True), Pin(num='A11',name='IO_L07N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C11',name='IO_L07P_0',func=Pin.BIDIR,do_erc=True), Pin(num='D11',name='IO_L03N_0',func=Pin.BIDIR,do_erc=True), Pin(num='E11',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='F11',name='IP_L25N_1',do_erc=True), Pin(num='G11',name='IP_L21N_1',do_erc=True), Pin(num='H11',name='IP_L13N_1',do_erc=True), Pin(num='J11',name='IP_L09N_1',do_erc=True), Pin(num='K11',name='IP_L04P_1',do_erc=True), Pin(num='L11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='M11',name='IP_2/VREF_2',do_erc=True), Pin(num='N11',name='IO_L16N_2',func=Pin.BIDIR,do_erc=True), Pin(num='P11',name='IO_L16P_2',func=Pin.BIDIR,do_erc=True), Pin(num='R11',name='IO_L15N_2/DOUT',func=Pin.BIDIR,do_erc=True), Pin(num='T11',name='IO_L15P_2/AWAKE',func=Pin.BIDIR,do_erc=True), Pin(num='A12',name='IO_L05N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B12',name='IO_L05P_0',func=Pin.BIDIR,do_erc=True), Pin(num='C12',name='IO_L03P_0',func=Pin.BIDIR,do_erc=True), Pin(num='D12',name='IP_0',do_erc=True), Pin(num='E12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='F12',name='IP_L25P_1/VREF_1',do_erc=True), Pin(num='G12',name='IP_L21P_1/VREF_1',do_erc=True), Pin(num='H12',name='VCCO1',func=Pin.PWRIN,do_erc=True), Pin(num='J12',name='IO_L10P_1/A8',func=Pin.BIDIR,do_erc=True), Pin(num='K12',name='IP_L04N_1/VREF_1',do_erc=True), Pin(num='L12',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='M12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N12',name='IO_L19P_2',func=Pin.BIDIR,do_erc=True), Pin(num='P12',name='IO_L17N_2/D3',func=Pin.BIDIR,do_erc=True), Pin(num='R12',name='VCCO2',func=Pin.PWRIN,do_erc=True), Pin(num='T12',name='IO_L17P_2/INIT_B',func=Pin.BIDIR,do_erc=True), Pin(num='A13',name='IO_L04N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B13',name='VCCO0',func=Pin.PWRIN,do_erc=True), Pin(num='C13',name='IO_L01N_0',func=Pin.BIDIR,do_erc=True), Pin(num='D13',name='IO_L01P_0',func=Pin.BIDIR,do_erc=True), Pin(num='E13',name='IO_L23P_1/A22',func=Pin.BIDIR,do_erc=True), Pin(num='F13',name='IO_L20N_1/A19',func=Pin.BIDIR,do_erc=True), Pin(num='G13',name='IO_L19P_1/A16',func=Pin.BIDIR,do_erc=True), Pin(num='H13',name='IO_L17P_1/A12',func=Pin.BIDIR,do_erc=True), Pin(num='J13',name='IO_L10N_1/A9',func=Pin.BIDIR,do_erc=True), Pin(num='K13',name='IO_L06N_1/A3',func=Pin.BIDIR,do_erc=True), Pin(num='L13',name='IO_L06P_1/A2',func=Pin.BIDIR,do_erc=True), Pin(num='M13',name='IO_L05P_1',func=Pin.BIDIR,do_erc=True), Pin(num='N13',name='IO_L01P_1/HDC',func=Pin.BIDIR,do_erc=True), Pin(num='P13',name='IO_L19N_2',func=Pin.BIDIR,do_erc=True), Pin(num='R13',name='IO_L18N_2/D1',func=Pin.BIDIR,do_erc=True), Pin(num='T13',name='IO_L18P_2/D2',func=Pin.BIDIR,do_erc=True), Pin(num='A14',name='IO_L04P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B14',name='IO_L02N_0',func=Pin.BIDIR,do_erc=True), Pin(num='C14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='D14',name='IO_L23N_1/A23',func=Pin.BIDIR,do_erc=True), Pin(num='E14',name='IO_L20P_1/A18',func=Pin.BIDIR,do_erc=True), Pin(num='F14',name='IO_L19N_1/A17',func=Pin.BIDIR,do_erc=True), Pin(num='G14',name='IO_L17N_1/A13',func=Pin.BIDIR,do_erc=True), Pin(num='H14',name='IO_L14N_1/RHCLK5',func=Pin.BIDIR,do_erc=True), Pin(num='J14',name='IO_L14P_1/RHCLK4',func=Pin.BIDIR,do_erc=True), Pin(num='K14',name='IO_L11N_1/RHCLK1',func=Pin.BIDIR,do_erc=True), Pin(num='L14',name='IO_L08P_1/A6',func=Pin.BIDIR,do_erc=True), Pin(num='M14',name='IO_L05N_1/VREF_1',func=Pin.BIDIR,do_erc=True), Pin(num='N14',name='IO_L01N_1/LDC2',func=Pin.BIDIR,do_erc=True), Pin(num='P14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R14',name='IO_L20N_2/CCLK',func=Pin.BIDIR,do_erc=True), Pin(num='T14',name='IO_L20P_2/D0/DIN/MISO',func=Pin.BIDIR,do_erc=True), Pin(num='A15',name='TCK',do_erc=True), Pin(num='B15',name='IO_L02P_0/VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='C15',name='IO_L24N_1/A25',func=Pin.BIDIR,do_erc=True), Pin(num='D15',name='IO_L22N_1/A21',func=Pin.BIDIR,do_erc=True), Pin(num='E15',name='VCCO1',func=Pin.PWRIN,do_erc=True), Pin(num='F15',name='IO_L18N_1/A15',func=Pin.BIDIR,do_erc=True), Pin(num='G15',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H15',name='IO_L15P_1/IRDY1/RHCLK6',func=Pin.BIDIR,do_erc=True), Pin(num='J15',name='VCCO1',func=Pin.PWRIN,do_erc=True), Pin(num='K15',name='IO_L11P_1/RHCLK0',func=Pin.BIDIR,do_erc=True), Pin(num='L15',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='M15',name='IO_L07P_1/A4',func=Pin.BIDIR,do_erc=True), Pin(num='N15',name='VCCO1',func=Pin.PWRIN,do_erc=True), Pin(num='P15',name='IO_L02N_1/LDC0',func=Pin.BIDIR,do_erc=True), Pin(num='R15',name='IO_L02P_1/LDC1',func=Pin.BIDIR,do_erc=True), Pin(num='T15',name='DONE',func=Pin.BIDIR,do_erc=True), Pin(num='A16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B16',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='C16',name='IO_L24P_1/A24',func=Pin.BIDIR,do_erc=True), Pin(num='D16',name='IO_L22P_1/A20',func=Pin.BIDIR,do_erc=True), Pin(num='E16',name='IO_L18P_1/A14',func=Pin.BIDIR,do_erc=True), Pin(num='F16',name='IO_L16N_1/A11',func=Pin.BIDIR,do_erc=True), Pin(num='G16',name='IO_L16P_1/A10',func=Pin.BIDIR,do_erc=True), Pin(num='H16',name='IO_L15N_1/RHCLK7',func=Pin.BIDIR,do_erc=True), Pin(num='J16',name='IO_L12N_1/TRDY1/RHCLK3',func=Pin.BIDIR,do_erc=True), Pin(num='K16',name='IO_L12P_1/RHCLK2',func=Pin.BIDIR,do_erc=True), Pin(num='L16',name='IO_L08N_1/A7',func=Pin.BIDIR,do_erc=True), Pin(num='M16',name='IO_L07N_1/A5',func=Pin.BIDIR,do_erc=True), Pin(num='N16',name='IO_L03N_1/A1',func=Pin.BIDIR,do_erc=True), Pin(num='P16',name='IO_L03P_1/A0',func=Pin.BIDIR,do_erc=True), Pin(num='R16',name='SUSPEND',do_erc=True), Pin(num='T16',name='GND',func=Pin.PWRIN,do_erc=True)]), Part(name='XC3S400-FG320',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3S400-PQ208',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC3S50-VQ100',dest=TEMPLATE,tool=SKIDL,keywords='FPGA',description='spartan 2',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='4',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='VCCO_7',func=Pin.PWRIN,do_erc=True), Pin(num='7',name='VCCAUX(2.5V)',func=Pin.PWRIN,do_erc=True), Pin(num='8',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='20',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='30',name='IO/D7',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='IO/DOUT/BUSY',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='80',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='IO/GCK7',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='VCCO_5',func=Pin.PWRIN,do_erc=True), Pin(num='41',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='51',name='DONE',func=Pin.OPENCOLL,do_erc=True), Pin(num='61',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='IO/D6',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='IO/INIT',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='CCLK',do_erc=True), Pin(num='62',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='82',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='92',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='IO-VREF',do_erc=True), Pin(num='23',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='VCCAUX(2.5V)',func=Pin.PWRIN,do_erc=True), Pin(num='43',name='IO/D3',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='83',name='VCCO_1',func=Pin.PASSIVE,do_erc=True), Pin(num='93',name='VCCINT(1.2V)',func=Pin.PWRIN,do_erc=True), Pin(num='14',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='M1',do_erc=True), Pin(num='34',name='IO/D5',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='IO/D2',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='VCCAUX(2.5V)',func=Pin.PWRIN,do_erc=True), Pin(num='94',name='VCCO_0',func=Pin.PASSIVE,do_erc=True), Pin(num='15',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='M0',do_erc=True), Pin(num='35',name='IO/D4',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='VCCINT(1.2V)',func=Pin.PWRIN,do_erc=True), Pin(num='55',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='16',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='M2',do_erc=True), Pin(num='36',name='IO/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='VCCO_4',func=Pin.PWRIN,do_erc=True), Pin(num='66',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='76',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='86',name='IO/VREF',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='IO/CS',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='IO/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='IO/D1',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='67',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='TCK',do_erc=True), Pin(num='87',name='IO/GCLK4',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='IO-VRP',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='VCCINT(1.2V)',func=Pin.PWRIN,do_erc=True), Pin(num='28',name='IO/RDWR',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='IO/GCK0',func=Pin.BIDIR,do_erc=True), Pin(num='48',name='IO/D0/DIN',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='VCCAUX(2.5V)',func=Pin.PWRIN,do_erc=True), Pin(num='68',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='TMS',do_erc=True), Pin(num='88',name='IO/GCLK5',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='HSWAP_EN',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='VCCO_6',func=Pin.PWRIN,do_erc=True), Pin(num='29',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='39',name='IO/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='IO',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='VCCINT(1.2V)',func=Pin.PWRIN,do_erc=True), Pin(num='79',name='IO-VRN',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='IO/GCK6',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='PROG',do_erc=True), Pin(num='100',name='TDI',do_erc=True)]), Part(name='XC3S50AN/TQG144',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC4003-PC84',dest=TEMPLATE,tool=SKIDL,do_erc=True,aliases=['XC4005-PC84']), Part(name='XC4003-VQ100',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='PGCK1',func=Pin.PASSIVE,do_erc=True), Pin(num='3',name='P/A17',func=Pin.PASSIVE,do_erc=True), Pin(num='4',name='P/TDI',func=Pin.PASSIVE,do_erc=True), Pin(num='5',name='P/TCK',func=Pin.PASSIVE,do_erc=True), Pin(num='6',name='P/A3',func=Pin.PASSIVE,do_erc=True), Pin(num='7',name='P7',func=Pin.PASSIVE,do_erc=True), Pin(num='8',name='P8',func=Pin.PASSIVE,do_erc=True), Pin(num='9',name='P/A15',func=Pin.PASSIVE,do_erc=True), Pin(num='10',name='P/A4',func=Pin.PASSIVE,do_erc=True), Pin(num='20',name='P20',func=Pin.PASSIVE,do_erc=True), Pin(num='30',name='P/LDC',func=Pin.PASSIVE,do_erc=True), Pin(num='40',name='P40',func=Pin.PASSIVE,do_erc=True), Pin(num='50',name='DONE',func=Pin.OPENCOLL,do_erc=True), Pin(num='60',name='P60',func=Pin.PASSIVE,do_erc=True), Pin(num='70',name='P70',func=Pin.PASSIVE,do_erc=True), Pin(num='80',name='P80',func=Pin.PASSIVE,do_erc=True), Pin(num='90',name='P90',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='21',name='SGCK2',func=Pin.PASSIVE,do_erc=True), Pin(num='31',name='P31',func=Pin.PASSIVE,do_erc=True), Pin(num='41',name='P41',func=Pin.PASSIVE,do_erc=True), Pin(num='51',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='P61',func=Pin.PASSIVE,do_erc=True), Pin(num='71',name='P71/RDY',func=Pin.PASSIVE,do_erc=True), Pin(num='81',name='P81',func=Pin.PASSIVE,do_erc=True), Pin(num='91',name='P91',func=Pin.PASSIVE,do_erc=True), Pin(num='12',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='22',name='M1/RD',do_erc=True), Pin(num='32',name='P32',func=Pin.PASSIVE,do_erc=True), Pin(num='42',name='P42',func=Pin.PASSIVE,do_erc=True), Pin(num='52',name='PROG',do_erc=True), Pin(num='62',name='P62',func=Pin.PASSIVE,do_erc=True), Pin(num='72',name='DIN',func=Pin.PASSIVE,do_erc=True), Pin(num='82',name='P82',func=Pin.PASSIVE,do_erc=True), Pin(num='92',name='P92',func=Pin.PASSIVE,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='33',name='P33',func=Pin.PASSIVE,do_erc=True), Pin(num='43',name='P43',func=Pin.PASSIVE,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='73',name='DOUT/SGCK4',func=Pin.PASSIVE,do_erc=True), Pin(num='83',name='P83',func=Pin.PASSIVE,do_erc=True), Pin(num='93',name='P93',func=Pin.PASSIVE,do_erc=True), Pin(num='14',name='P14',func=Pin.PASSIVE,do_erc=True), Pin(num='24',name='M0/RT',do_erc=True), Pin(num='34',name='P34',func=Pin.PASSIVE,do_erc=True), Pin(num='44',name='P44',func=Pin.PASSIVE,do_erc=True), Pin(num='54',name='PGCK3',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='74',name='CCLK',do_erc=True), Pin(num='84',name='P84',func=Pin.PASSIVE,do_erc=True), Pin(num='94',name='P94',func=Pin.PASSIVE,do_erc=True), Pin(num='15',name='P15',func=Pin.PASSIVE,do_erc=True), Pin(num='25',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='35',name='P35',func=Pin.PASSIVE,do_erc=True), Pin(num='45',name='P45',func=Pin.PASSIVE,do_erc=True), Pin(num='55',name='P55',func=Pin.PASSIVE,do_erc=True), Pin(num='65',name='P65',func=Pin.PASSIVE,do_erc=True), Pin(num='75',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='85',name='P85',func=Pin.PASSIVE,do_erc=True), Pin(num='95',name='P91',func=Pin.PASSIVE,do_erc=True), Pin(num='16',name='P16',func=Pin.PASSIVE,do_erc=True), Pin(num='26',name='M2',func=Pin.PASSIVE,do_erc=True), Pin(num='36',name='P36/INIT',func=Pin.PASSIVE,do_erc=True), Pin(num='46',name='P46',func=Pin.PASSIVE,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.PASSIVE,do_erc=True), Pin(num='76',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='86',name='P86',func=Pin.PASSIVE,do_erc=True), Pin(num='96',name='P96',func=Pin.PASSIVE,do_erc=True), Pin(num='17',name='P17',func=Pin.PASSIVE,do_erc=True), Pin(num='27',name='PGCK2',func=Pin.PASSIVE,do_erc=True), Pin(num='37',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='47',name='P47',func=Pin.PASSIVE,do_erc=True), Pin(num='57',name='P57',func=Pin.PASSIVE,do_erc=True), Pin(num='67',name='P67',func=Pin.PASSIVE,do_erc=True), Pin(num='77',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='87',name='P87',func=Pin.PASSIVE,do_erc=True), Pin(num='97',name='P97',func=Pin.PASSIVE,do_erc=True), Pin(num='18',name='P18',func=Pin.PASSIVE,do_erc=True), Pin(num='28',name='P/HDC',func=Pin.PASSIVE,do_erc=True), Pin(num='38',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='SGCK3',func=Pin.PASSIVE,do_erc=True), Pin(num='58',name='P58',func=Pin.PASSIVE,do_erc=True), Pin(num='68',name='P68',func=Pin.PASSIVE,do_erc=True), Pin(num='78',name='P78',func=Pin.PASSIVE,do_erc=True), Pin(num='88',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='98',name='P98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='P19',func=Pin.PASSIVE,do_erc=True), Pin(num='29',name='P29',func=Pin.PASSIVE,do_erc=True), Pin(num='39',name='P39',func=Pin.PASSIVE,do_erc=True), Pin(num='49',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='59',name='P59',func=Pin.PASSIVE,do_erc=True), Pin(num='69',name='P69',func=Pin.PASSIVE,do_erc=True), Pin(num='79',name='PGCK4',func=Pin.PASSIVE,do_erc=True), Pin(num='89',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='99',name='SGCK1',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='VCC',func=Pin.PWRIN,do_erc=True)]), Part(name='XC4004-PQ160',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC4005-PG156',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC4005-PQ100',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC4005-PQ160',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC6SLX25T-BG484',dest=TEMPLATE,tool=SKIDL,description='SPARTAN-6 FG484',ref_prefix='U',num_units=3,do_erc=True,pins=[ Pin(num='A2',name='IO_L3N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B2',name='IO_L3P_0',func=Pin.BIDIR,do_erc=True), Pin(num='A3',name='IO_L5N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B3',name='IO_L5P_0',func=Pin.BIDIR,do_erc=True), Pin(num='C3',name='IO_L1P_HSWAPEN_0',func=Pin.BIDIR,do_erc=True), Pin(num='D3',name='IO_L1N_VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='A4',name='IO_L6N_0',func=Pin.BIDIR,do_erc=True), Pin(num='B4',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='C4',name='IO_L6P_0',func=Pin.BIDIR,do_erc=True), Pin(num='D4',name='IO_L2P_0',func=Pin.BIDIR,do_erc=True), Pin(num='A5',name='IO_L8N_VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='C5',name='IO_L8P_0',func=Pin.BIDIR,do_erc=True), Pin(num='D5',name='IO_L2N_0',func=Pin.BIDIR,do_erc=True), Pin(num='E5',name='IO_L4P_0',func=Pin.BIDIR,do_erc=True), Pin(num='A6',name='MGTTXN0_101',func=Pin.OUTPUT,do_erc=True), Pin(num='B6',name='MGTTXP0_101',func=Pin.OUTPUT,do_erc=True), Pin(num='E6',name='IO_L4N_0',func=Pin.BIDIR,do_erc=True), Pin(num='F6',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='A7',name='MGTAVTTTX_101',func=Pin.PASSIVE,do_erc=True), Pin(num='C7',name='MGTRXN0_101',do_erc=True), Pin(num='D7',name='MGTRXP0_101',do_erc=True), Pin(num='F7',name='IO_L7P_0',func=Pin.BIDIR,do_erc=True), Pin(num='A8',name='MGTTXN1_101',func=Pin.OUTPUT,do_erc=True), Pin(num='B8',name='MGTTXP1_101',func=Pin.OUTPUT,do_erc=True), Pin(num='D8',name='MGTAVTTRX_101',func=Pin.PASSIVE,do_erc=True), Pin(num='E8',name='MGTAVTTRCAL_101',func=Pin.PASSIVE,do_erc=True), Pin(num='F8',name='IO_L7N_0',func=Pin.BIDIR,do_erc=True), Pin(num='G8',name='IO_L32P_0',func=Pin.BIDIR,do_erc=True), Pin(num='B9',name='MGTAVCCPLL0_101',func=Pin.PASSIVE,do_erc=True), Pin(num='C9',name='MGTRXN1_101',do_erc=True), Pin(num='D9',name='MGTRXP1_101',do_erc=True), Pin(num='E9',name='MGTRREF_101',do_erc=True), Pin(num='F9',name='IO_L32N_0',func=Pin.BIDIR,do_erc=True), Pin(num='G9',name='IO_L34P_GCLK19_0',func=Pin.BIDIR,do_erc=True), Pin(num='A10',name='MGTREFCLK0P_101',do_erc=True), Pin(num='B10',name='MGTREFCLK0N_101',do_erc=True), Pin(num='C10',name='MGTAVCC_101',func=Pin.PASSIVE,do_erc=True), Pin(num='F10',name='IO_L34N_GCLK18_0',func=Pin.BIDIR,do_erc=True), Pin(num='G10',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='H10',name='IO_L33P_0',func=Pin.BIDIR,do_erc=True), Pin(num='A20',name='IO_L65N_SCP2_0',func=Pin.BIDIR,do_erc=True), Pin(num='B20',name='IO_L65P_SCP3_0',func=Pin.BIDIR,do_erc=True), Pin(num='C20',name='IO_L20P_1',func=Pin.BIDIR,do_erc=True), Pin(num='D20',name='TMS',do_erc=True), Pin(num='E20',name='IO_L32P_A17_M1A8_1',func=Pin.BIDIR,do_erc=True), Pin(num='F20',name='IO_L29N_A22_M1A14_1',func=Pin.BIDIR,do_erc=True), Pin(num='G20',name='IO_L35P_A11_M1A7_1',func=Pin.BIDIR,do_erc=True), Pin(num='H20',name='IO_L33N_A14_M1A4_1',func=Pin.BIDIR,do_erc=True), Pin(num='J20',name='IO_L39P_M1A3_1',func=Pin.BIDIR,do_erc=True), Pin(num='K20',name='IO_L38P_A5_M1CLK_1',func=Pin.BIDIR,do_erc=True), Pin(num='L20',name='IO_L43P_GCLK5_M1DQ4_1',func=Pin.BIDIR,do_erc=True), Pin(num='M20',name='IO_L40P_GCLK11_M1A5_1',func=Pin.BIDIR,do_erc=True), Pin(num='N20',name='IO_L45P_A1_M1LDQS_1',func=Pin.BIDIR,do_erc=True), Pin(num='P20',name='IO_L42P_GCLK7_M1UDM_1',func=Pin.BIDIR,do_erc=True), Pin(num='R20',name='IO_L47P_FWE_B_M1DQ0_1',func=Pin.BIDIR,do_erc=True), Pin(num='T20',name='IO_L59N_1',func=Pin.BIDIR,do_erc=True), Pin(num='U20',name='IO_L49P_M1DQ10_1',func=Pin.BIDIR,do_erc=True), Pin(num='V20',name='IO_L74N_DOUT_BUSY_1',func=Pin.BIDIR,do_erc=True), Pin(num='W20',name='IO_L51P_M1DQ12_1',func=Pin.BIDIR,do_erc=True), Pin(num='C11',name='MGTREFCLK1P_101',do_erc=True), Pin(num='D11',name='MGTREFCLK1N_101',do_erc=True), Pin(num='G11',name='IO_L35N_GCLK16_0',func=Pin.BIDIR,do_erc=True), Pin(num='H11',name='IO_L33N_0',func=Pin.BIDIR,do_erc=True), Pin(num='A21',name='TCK',do_erc=True), Pin(num='C21',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='F21',name='IO_L31P_A19_M1CKE_1',func=Pin.BIDIR,do_erc=True), Pin(num='G21',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='H21',name='IO_L37P_A7_M1A0_1',func=Pin.BIDIR,do_erc=True), Pin(num='K21',name='IO_L41P_GCLK9_IRDY1_M1RASN_1',func=Pin.BIDIR,do_erc=True), Pin(num='L21',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='M21',name='IO_L44P_A3_M1DQ6_1',func=Pin.BIDIR,do_erc=True), Pin(num='P21',name='IO_L46P_FCS_B_M1DQ2_1',func=Pin.BIDIR,do_erc=True), Pin(num='R21',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='T21',name='IO_L48P_HDC_M1DQ8_1',func=Pin.BIDIR,do_erc=True), Pin(num='V21',name='IO_L50P_M1UDQS_1',func=Pin.BIDIR,do_erc=True), Pin(num='W21',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='Y21',name='IO_L52P_M1DQ14_1',func=Pin.BIDIR,do_erc=True), Pin(num='D12',name='MGTAVCCPLL1_101',func=Pin.PASSIVE,do_erc=True), Pin(num='H12',name='IO_L35P_GCLK17_0',func=Pin.BIDIR,do_erc=True), Pin(num='C22',name='IO_L20N_1',func=Pin.BIDIR,do_erc=True), Pin(num='E22',name='IO_L32N_A16_M1A9_1',func=Pin.BIDIR,do_erc=True), Pin(num='F22',name='IO_L31N_A18_M1A12_1',func=Pin.BIDIR,do_erc=True), Pin(num='G22',name='IO_L35N_A10_M1A2_1',func=Pin.BIDIR,do_erc=True), Pin(num='H22',name='IO_L37N_A6_M1A1_1',func=Pin.BIDIR,do_erc=True), Pin(num='J22',name='IO_L39N_M1ODT_1',func=Pin.BIDIR,do_erc=True), Pin(num='K22',name='IO_L41N_GCLK8_M1CASN_1',func=Pin.BIDIR,do_erc=True), Pin(num='L22',name='IO_L43N_CLK4_M1DQ5_1',func=Pin.BIDIR,do_erc=True), Pin(num='M22',name='IO_L44N_A2_M1DQ7_1',func=Pin.BIDIR,do_erc=True), Pin(num='N22',name='IO_L45N_A0_M1LDQSN_1',func=Pin.BIDIR,do_erc=True), Pin(num='P22',name='IO_L46N_FOE_B_M1DQ3_1',func=Pin.BIDIR,do_erc=True), Pin(num='R22',name='IO_L47N_LDC_M1DQ1_1',func=Pin.BIDIR,do_erc=True), Pin(num='T22',name='IO_L48N_M1DQ9_1',func=Pin.BIDIR,do_erc=True), Pin(num='U22',name='IO_L49N_M1DQ11_1',func=Pin.BIDIR,do_erc=True), Pin(num='V22',name='IO_L50N_M1UDQSN_1',func=Pin.BIDIR,do_erc=True), Pin(num='W22',name='IO_L51N_M1DQ13_1',func=Pin.BIDIR,do_erc=True), Pin(num='Y22',name='IO_L52N_M1DQ15_1',func=Pin.BIDIR,do_erc=True), Pin(num='G13',name='IO_L38N_VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='H13',name='IO_L38P_0',func=Pin.BIDIR,do_erc=True), Pin(num='F14',name='IO_L36P_GCLK15_0',func=Pin.BIDIR,do_erc=True), Pin(num='G14',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='H14',name='IO_L49P_0',func=Pin.BIDIR,do_erc=True), Pin(num='F15',name='IO_L36N_GCLK14_0',func=Pin.BIDIR,do_erc=True), Pin(num='G15',name='IO_L49N_0',func=Pin.BIDIR,do_erc=True), Pin(num='E16',name='IO_L37P_GCLK13_0',func=Pin.BIDIR,do_erc=True), Pin(num='F16',name='IO_L37N_GCLK12_0',func=Pin.BIDIR,do_erc=True), Pin(num='G16',name='IO_L51P_0',func=Pin.BIDIR,do_erc=True), Pin(num='J16',name='IO_L19P_1',func=Pin.BIDIR,do_erc=True), Pin(num='L16',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='N16',name='IO_L60P_1',func=Pin.BIDIR,do_erc=True), Pin(num='P16',name='IO_L60N_1',func=Pin.BIDIR,do_erc=True), Pin(num='A17',name='IO_L50N_0',func=Pin.BIDIR,do_erc=True), Pin(num='C17',name='IO_L50P_0',func=Pin.BIDIR,do_erc=True), Pin(num='D17',name='IO_L66P_SCP1_0',func=Pin.BIDIR,do_erc=True), Pin(num='E17',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='F17',name='IO_L51N_0',func=Pin.BIDIR,do_erc=True), Pin(num='G17',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='J17',name='IO_L19N_1',func=Pin.BIDIR,do_erc=True), Pin(num='K17',name='IO_L36P_A9_M1BA0_1',do_erc=True), Pin(num='L17',name='IO_L36N_A8_M1BA1_1',func=Pin.BIDIR,do_erc=True), Pin(num='M17',name='IO_L61P_1',func=Pin.BIDIR,do_erc=True), Pin(num='A18',name='IO_L63N_SCP6_0',func=Pin.BIDIR,do_erc=True), Pin(num='B18',name='IO_L63P_SCP7_0',func=Pin.BIDIR,do_erc=True), Pin(num='C18',name='IO_L66N_SCP0_0',func=Pin.BIDIR,do_erc=True), Pin(num='D18',name='IO_L62P_0',func=Pin.BIDIR,do_erc=True), Pin(num='E18',name='TDI',do_erc=True), Pin(num='F18',name='IO_L1P_A25_1',func=Pin.BIDIR,do_erc=True), Pin(num='H18',name='IO_L30P_A21_M1RESET_1',func=Pin.BIDIR,do_erc=True), Pin(num='J18',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='K18',name='IO_L34N_A12_M1BA2_1',func=Pin.BIDIR,do_erc=True), Pin(num='M18',name='IO_L61N_1',func=Pin.BIDIR,do_erc=True), Pin(num='N18',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='U18',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='A19',name='IO_L46N_SCP4_0',func=Pin.BIDIR,do_erc=True), Pin(num='B19',name='VCCO_0',func=Pin.PWRIN,do_erc=True), Pin(num='C19',name='IO_L64P_SCP5_0',func=Pin.BIDIR,do_erc=True), Pin(num='D19',name='IO_L62N_VREF_0',func=Pin.BIDIR,do_erc=True), Pin(num='E19',name='VCCO_1',func=Pin.PWRIN,do_erc=True), Pin(num='F19',name='IO_L1N_A24_VREF_1',func=Pin.BIDIR,do_erc=True), Pin(num='G19',name='IO_L29P_A23_M1A13_1',func=Pin.BIDIR,do_erc=True), Pin(num='H19',name='IO_L30N_A20_M1A11_1',func=Pin.BIDIR,do_erc=True), Pin(num='J19',name='IO_L33P_A15_M1A10_1',func=Pin.BIDIR,do_erc=True), Pin(num='K19',name='IO_L34P_A13_M1WE_1',func=Pin.BIDIR,do_erc=True), Pin(num='L19',name='IO_L38N_A4_M1CLKN_1',func=Pin.BIDIR,do_erc=True), Pin(num='M19',name='IO_L40N_GCLK10_M1A6_1',func=Pin.BIDIR,do_erc=True), Pin(num='N19',name='IO_L42N_GCLK6_TRDY1_M1LDM_1',func=Pin.BIDIR,do_erc=True), Pin(num='P19',name='IO_L53P_1',func=Pin.BIDIR,do_erc=True), Pin(num='R19',name='IO_L53N_VREF_1',func=Pin.BIDIR,do_erc=True), Pin(num='U19',name='IO_L59P_1',func=Pin.BIDIR,do_erc=True), Pin(num='V19',name='IO_L74P_AWAKE_1',func=Pin.BIDIR,do_erc=True), Pin(num='B1',name='IO_L83N_VREF_3',func=Pin.BIDIR,do_erc=True), Pin(num='C1',name='IO_L83P_3',func=Pin.BIDIR,do_erc=True), Pin(num='D1',name='IO_L59N_3',func=Pin.BIDIR,do_erc=True), Pin(num='E1',name='IO_L54N_M3A11_3',func=Pin.BIDIR,do_erc=True), Pin(num='F1',name='IO_L53N_M3A12_3',func=Pin.BIDIR,do_erc=True), Pin(num='G1',name='IO_L52N_M3A9_3',func=Pin.BIDIR,do_erc=True), Pin(num='H1',name='IO_L50N_M3BA2_3',func=Pin.BIDIR,do_erc=True), Pin(num='J1',name='IO_L48N_M3BA1_3',func=Pin.BIDIR,do_erc=True), Pin(num='K1',name='IO_L47N_M3A1_3',func=Pin.BIDIR,do_erc=True), Pin(num='L1',name='IO_L41N_GCLK26_M3DQ5_3',func=Pin.BIDIR,do_erc=True), Pin(num='M1',name='IO_L40N_M3DQ7_3',func=Pin.BIDIR,do_erc=True), Pin(num='N1',name='IO_L39N_M3LDQSN_3',func=Pin.BIDIR,do_erc=True), Pin(num='P1',name='IO_L38N_M3DQ3_3',func=Pin.BIDIR,do_erc=True), Pin(num='R1',name='IO_L37N_M3DQ1_3',func=Pin.BIDIR,do_erc=True), Pin(num='T1',name='IO_L36N_M3DQ9_3',func=Pin.BIDIR,do_erc=True), Pin(num='U1',name='IO_L35N_M3DQ11_3',func=Pin.BIDIR,do_erc=True), Pin(num='V1',name='IO_L34N_M3UDQSN_3',func=Pin.BIDIR,do_erc=True), Pin(num='W1',name='IO_L33N_M3DQ13_3',func=Pin.BIDIR,do_erc=True), Pin(num='Y1',name='IO_L32N_M3DQ15_3',func=Pin.BIDIR,do_erc=True), Pin(num='C2',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='D2',name='IO_L59P_3',func=Pin.BIDIR,do_erc=True), Pin(num='F2',name='IO_L53P_M3CKE_3',func=Pin.BIDIR,do_erc=True), Pin(num='G2',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='H2',name='IO_L50P_M3WE_3',func=Pin.BIDIR,do_erc=True), Pin(num='K2',name='IO_L47P_M3A0_3',func=Pin.BIDIR,do_erc=True), Pin(num='L2',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='M2',name='IO_L40P_M3DQ6_3',func=Pin.BIDIR,do_erc=True), Pin(num='P2',name='IO_L38P_M3DQ2_3',func=Pin.BIDIR,do_erc=True), Pin(num='R2',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='T2',name='IO_L36P_M3DQ8_3',func=Pin.BIDIR,do_erc=True), Pin(num='V2',name='IO_L34P_M3UDQS_3',func=Pin.BIDIR,do_erc=True), Pin(num='W2',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='Y2',name='IO_L32P_M3DQ14_3',func=Pin.BIDIR,do_erc=True), Pin(num='E3',name='IO_L54P_M3RESET_3',func=Pin.BIDIR,do_erc=True), Pin(num='F3',name='IO_L60P_3',func=Pin.BIDIR,do_erc=True), Pin(num='G3',name='IO_L52P_M3A8_3',func=Pin.BIDIR,do_erc=True), Pin(num='H3',name='IO_L51N_M3A4_3',func=Pin.BIDIR,do_erc=True), Pin(num='J3',name='IO_L48P_M3BA0_3',func=Pin.BIDIR,do_erc=True), Pin(num='K3',name='IO_L46N_M3CLKN_3',func=Pin.BIDIR,do_erc=True), Pin(num='L3',name='IO_L41P_GCLK27_M3DQ4_3',func=Pin.BIDIR,do_erc=True), Pin(num='M3',name='IO_L44P_GCLK21_M3A5_3',func=Pin.BIDIR,do_erc=True), Pin(num='N3',name='IO_L39P_M3LDQS_3',func=Pin.BIDIR,do_erc=True), Pin(num='P3',name='IO_L42P_GCLK25_TRDY2_M3UDM_3',func=Pin.BIDIR,do_erc=True), Pin(num='R3',name='IO_L37P_M3DQ0_3',func=Pin.BIDIR,do_erc=True), Pin(num='U3',name='IO_L35P_M3DQ10_3',func=Pin.BIDIR,do_erc=True), Pin(num='W3',name='IO_L33P_M3DQ12_3',func=Pin.BIDIR,do_erc=True), Pin(num='Y3',name='IO_L2N_3',func=Pin.BIDIR,do_erc=True), Pin(num='E4',name='IO_L60N_3',func=Pin.BIDIR,do_erc=True), Pin(num='F4',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='J4',name='IO_L51P_M3A10_3',func=Pin.BIDIR,do_erc=True), Pin(num='K4',name='IO_L46P_M3CLK_3',func=Pin.BIDIR,do_erc=True), Pin(num='L4',name='IO_L44N_GCLK207_M3A6_3',func=Pin.BIDIR,do_erc=True), Pin(num='M4',name='IO_L43N_GCLK22_TRDY2_M3CASN_3',func=Pin.BIDIR,do_erc=True), Pin(num='N4',name='IO_L42N_GCLK24_M3LDM_3',func=Pin.BIDIR,do_erc=True), Pin(num='P4',name='IO_L9N_3',func=Pin.BIDIR,do_erc=True), Pin(num='W4',name='IO_L2P_3',func=Pin.BIDIR,do_erc=True), Pin(num='Y4',name='IO_L65P_INIT_B_2',func=Pin.BIDIR,do_erc=True), Pin(num='H5',name='IO_L55N_M3A14_3',func=Pin.BIDIR,do_erc=True), Pin(num='J5',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='K5',name='IO_L49N_M3A2_3',func=Pin.BIDIR,do_erc=True), Pin(num='M5',name='IO_L43P_GCLK23_M3RASN_3',func=Pin.BIDIR,do_erc=True), Pin(num='N5',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='P5',name='IO_L9P_3',func=Pin.BIDIR,do_erc=True), Pin(num='U5',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='W5',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='Y5',name='IO_L62P_D5_2',func=Pin.BIDIR,do_erc=True), Pin(num='J6',name='IO_L55P_M3A13_3',func=Pin.BIDIR,do_erc=True), Pin(num='K6',name='IO_L49P_M3A7_3',func=Pin.BIDIR,do_erc=True), Pin(num='L6',name='IO_L45N_M3ODT_3',func=Pin.BIDIR,do_erc=True), Pin(num='M6',name='IO_L45P_M3A3_3',func=Pin.BIDIR,do_erc=True), Pin(num='U6',name='IO_L64N_D9_2',func=Pin.BIDIR,do_erc=True), Pin(num='W6',name='IO_L60P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y6',name='IO_L60N_2',func=Pin.BIDIR,do_erc=True), Pin(num='L7',name='VCCO_3',func=Pin.PWRIN,do_erc=True), Pin(num='M7',name='IO_L31P_3',func=Pin.BIDIR,do_erc=True), Pin(num='R7',name='IO_L1P_3',func=Pin.BIDIR,do_erc=True), Pin(num='T7',name='IO_L64P_D8_2',func=Pin.BIDIR,do_erc=True), Pin(num='V7',name='IO_L58P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y7',name='IO_L47P_2',func=Pin.BIDIR,do_erc=True), Pin(num='M8',name='IO_L31N_VREF_3',func=Pin.BIDIR,do_erc=True), Pin(num='P8',name='IO_L1N_VREF_3',func=Pin.BIDIR,do_erc=True), Pin(num='R8',name='IO_L59N_2',func=Pin.BIDIR,do_erc=True), Pin(num='T8',name='IO_L57P_2',func=Pin.BIDIR,do_erc=True), Pin(num='U8',name='IO_L57N_2',func=Pin.BIDIR,do_erc=True), Pin(num='V8',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='W8',name='IO_L58N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y8',name='IO_L48N_RDWR_B_VREF_2',func=Pin.BIDIR,do_erc=True), Pin(num='R9',name='IO_L59P_2',func=Pin.BIDIR,do_erc=True), Pin(num='T9',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='U9',name='IO_L50P_2',func=Pin.BIDIR,do_erc=True), Pin(num='V9',name='IO_L50N_2',func=Pin.BIDIR,do_erc=True), Pin(num='W9',name='IO_L48P_D7_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y9',name='IO_L43P_2',func=Pin.BIDIR,do_erc=True), Pin(num='T10',name='IO_L46P_2',func=Pin.BIDIR,do_erc=True), Pin(num='U10',name='IO_L46N_2',func=Pin.BIDIR,do_erc=True), Pin(num='W10',name='IO_L44P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y10',name='IO_L44N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y20',name='IO_L1P_CCLK_2',func=Pin.BIDIR,do_erc=True), Pin(num='V11',name='IO_L42P_2',func=Pin.BIDIR,do_erc=True), Pin(num='W11',name='IO_L42N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y11',name='IO_L32P_GCLK29_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA1',name='IO_L10N_3',func=Pin.BIDIR,do_erc=True), Pin(num='T12',name='IO_L29P_GCLK3_2',func=Pin.BIDIR,do_erc=True), Pin(num='U12',name='IO_L29N_GCLK2_2',func=Pin.BIDIR,do_erc=True), Pin(num='V12',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='W12',name='IO_L40P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y12',name='IO_L40N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA2',name='IO_L10P_3',func=Pin.BIDIR,do_erc=True), Pin(num='AB2',name='PROGRAM_B_2',do_erc=True), Pin(num='R13',name='IO_L12P_D1_MISO2_2',func=Pin.BIDIR,do_erc=True), Pin(num='T13',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='U13',name='IO_L16N_VREF_2',func=Pin.BIDIR,do_erc=True), Pin(num='V13',name='IO_L18P_2',func=Pin.BIDIR,do_erc=True), Pin(num='W13',name='IO_L18N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y13',name='IO_L30P_GCLK1_D13_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA3',name='IO_L65N_CSO_B_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB3',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='T14',name='IO_L12N_D2_MISO3_2',func=Pin.BIDIR,do_erc=True), Pin(num='U14',name='IO_L16P_2',func=Pin.BIDIR,do_erc=True), Pin(num='W14',name='IO_L20P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y14',name='IO_L20N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA4',name='IO_L63P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB4',name='IO_L63N_2',func=Pin.BIDIR,do_erc=True), Pin(num='W15',name='IO_L17N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y15',name='IO_L21P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB5',name='IO_L62N_D6_2',func=Pin.BIDIR,do_erc=True), Pin(num='V16',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='Y16',name='IO_L17P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA6',name='IO_L49P_D3_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB6',name='IO_L49N_D4_2',func=Pin.BIDIR,do_erc=True), Pin(num='V17',name='IO_L2P_CMPCLK_2',func=Pin.BIDIR,do_erc=True), Pin(num='W17',name='IO_L5P_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y17',name='IO_L15P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA7',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='AB7',name='IO_L47N_2',func=Pin.BIDIR,do_erc=True), Pin(num='V18',name='CMPCS_B_2',do_erc=True), Pin(num='W18',name='IO_L2N_CMPMOSI_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y18',name='IO_L5N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA8',name='IO_L45P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB8',name='IO_L45N_2',func=Pin.BIDIR,do_erc=True), Pin(num='Y19',name='IO_L13P_M1_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB9',name='IO_L43N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA10',name='IO_L41P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB10',name='IO_L41N_VREF_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA20',name='IO_L3P_D0_DIN_MISO_MISO1_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB20',name='IO_L3N_MOSI_CSI_B_MISO0_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA11',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='AB11',name='IO_L32N_GCLK28_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA21',name='IO_L1N_M0_CMPMISO_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB21',name='DONE_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA12',name='IO_L31P_GCLK31_D14_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB12',name='IO_L31N_GCLK30_D15_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA22',name='SUSPEND',do_erc=True), Pin(num='AB13',name='IO_L30N_GCLK0_USERCCLK_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA14',name='IO_L6P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB14',name='IO_L6N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA15',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='AB15',name='IO_L21N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA16',name='IO_L19P_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB16',name='IO_L19N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB17',name='IO_L15N_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA18',name='IO_L14P_D11_2',func=Pin.BIDIR,do_erc=True), Pin(num='AB18',name='IO_L14N_D12_2',func=Pin.BIDIR,do_erc=True), Pin(num='AA19',name='VCCO_2',func=Pin.PWRIN,do_erc=True), Pin(num='AB19',name='IO_L13N_D10_2',func=Pin.BIDIR,do_erc=True), Pin(num='A1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='E2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='U2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='V4',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='G5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C6',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='D6',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R6',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='V6',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='B7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='E7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='U7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='W7',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C8',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J8',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L8',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='N8',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='A9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H9',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='J9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='K9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='M9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='N9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='P9',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='D10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J10',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='K10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L10',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='M10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N10',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='P10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R10',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='V10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='A11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='E11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='F11',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='J11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='K11',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='M11',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='N11',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='P11',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='U11',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='E21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='U21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='AB1',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='G12',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='J12',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='K12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L12',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='M12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N12',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='P12',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R12',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='A22',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='A13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='F13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='K13',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='L13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='M13',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='N13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='P13',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='C14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='E14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='J14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='K14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='M14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='P14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R14',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='V14',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B15',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='E15',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='H15',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='J15',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='K15',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='M15',name='VCCAUX',func=Pin.PWRIN,do_erc=True), Pin(num='AA5',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='C16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='D16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='W16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='B17',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='N17',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='G18',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='L18',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='R18',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='W19',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='AA9',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='AB22',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='AA13',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='AA17',name='GND',func=Pin.PWRIN,do_erc=True)]), Part(name='XC7336',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC95108PC84',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='P1',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='P2',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='P3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='P4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='P5',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='P6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='9',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='TCK',do_erc=True), Pin(num='40',name='P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='P50',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='P80',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='P31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='P51',func=Pin.BIDIR,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='32',name='P32',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='P62',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='P72',func=Pin.BIDIR,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='83',name='P83',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='P24',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='74',name='I/O/GSR',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='P84',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='P25',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='P45',func=Pin.BIDIR,do_erc=True), Pin(num='55',name='P55',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='P65',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='P75',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='26',name='P26',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='P46',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='37',name='P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='P47',func=Pin.BIDIR,do_erc=True), Pin(num='57',name='P57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='TDI',do_erc=True), Pin(num='38',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='19',name='P19',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='TMS',do_erc=True), Pin(num='39',name='P39',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='59',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='69',name='P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True)]), Part(name='XC95108PQ100',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='I/O/GSR',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='3',name='P3',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='P4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='8',name='P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='50',name='TCK',do_erc=True), Pin(num='60',name='P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='P80',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='P31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='P51',func=Pin.BIDIR,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='P91',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='P12',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='P32',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='P62',func=Pin.BIDIR,do_erc=True), Pin(num='72',name='P72',func=Pin.BIDIR,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='P92',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='33',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='43',name='P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='63',name='P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='P73',func=Pin.BIDIR,do_erc=True), Pin(num='83',name='P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='P93',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='74',name='P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='P84',func=Pin.BIDIR,do_erc=True), Pin(num='94',name='P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='P45',func=Pin.BIDIR,do_erc=True), Pin(num='55',name='P55',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='P65',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='P75',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='95',name='P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='P26',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='P76',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='96',name='P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='P27',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='TDI',do_erc=True), Pin(num='57',name='P57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='87',name='P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='38',name='P38',func=Pin.BIDIR,do_erc=True), Pin(num='48',name='P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='P78',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='P98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='P19',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='P39',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='TMS',do_erc=True), Pin(num='59',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='69',name='P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='P99',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='VCC',func=Pin.PWRIN,do_erc=True)]), Part(name='XC95144PQ100',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XC95144XL-TQ100',dest=TEMPLATE,tool=SKIDL,keywords='CPLD',description='CPLD, 144 macrocells, 3200 usable gates',ref_prefix='U',num_units=1,fplist=['TQFP*14x14mm*Pitch0.5mm*'],do_erc=True,pins=[ Pin(num='1',name='I/O/GTS3',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='I/O/GTS4',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='6',name='P6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='P50',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='P80',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='P90',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='31',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='P91',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='P12',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='P32',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='72',name='P72',func=Pin.BIDIR,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='P92',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='P73',func=Pin.BIDIR,do_erc=True), Pin(num='83',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='93',name='P93',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='P24',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='P64',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='94',name='P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='P25',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='TDI',do_erc=True), Pin(num='55',name='P55',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='P65',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='85',name='P85',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='P46',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='P76',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='TMS',do_erc=True), Pin(num='57',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='67',name='P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='P77',func=Pin.BIDIR,do_erc=True), Pin(num='87',name='P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='P28',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='TCK',do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='P78',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='98',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='19',name='P19',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='P29',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='P39',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='P59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='I/O/GSR',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='GND',func=Pin.PWRIN,do_erc=True)]), Part(name='XC95144XL-TQ144',dest=TEMPLATE,tool=SKIDL,keywords='CPLD',description='CPLD, 144 macrocells, 3200 usable gates',ref_prefix='U',num_units=1,fplist=['TQFP*20x20mm*Pitch0.5mm*'],do_erc=True,pins=[ Pin(num='1',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='2',name='I/O/GTS3',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='I/O/GTS4',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='P4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='P7',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='9',name='P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='P50',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='P80',func=Pin.BIDIR,do_erc=True), Pin(num='90',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='P21',func=Pin.BIDIR,do_erc=True), Pin(num='31',name='P31',func=Pin.BIDIR,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='P51',func=Pin.BIDIR,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='P91',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='P12',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='P22',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='72',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='P92',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='P23',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='P43',func=Pin.BIDIR,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='TDI',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='83',name='P83',func=Pin.BIDIR,do_erc=True), Pin(num='93',name='P93',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='P24',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='P34',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='P44',func=Pin.BIDIR,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='P64',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='94',name='P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='P25',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='P45',func=Pin.BIDIR,do_erc=True), Pin(num='55',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='65',name='TMS',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='P75',func=Pin.BIDIR,do_erc=True), Pin(num='85',name='P85',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='P26',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='46',name='P46',func=Pin.BIDIR,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='P76',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='P27',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='47',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='57',name='P57',func=Pin.BIDIR,do_erc=True), Pin(num='67',name='TCK',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='P77',func=Pin.BIDIR,do_erc=True), Pin(num='87',name='P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='28',name='P28',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='48',name='P48',func=Pin.BIDIR,do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='P78',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='P88',func=Pin.BIDIR,do_erc=True), Pin(num='98',name='P98',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='P19',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='39',name='P39',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='P59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='P69',func=Pin.BIDIR,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='99',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='100',name='P100',func=Pin.BIDIR,do_erc=True), Pin(num='110',name='P110',func=Pin.BIDIR,do_erc=True), Pin(num='120',name='P120',func=Pin.BIDIR,do_erc=True), Pin(num='130',name='P130',func=Pin.BIDIR,do_erc=True), Pin(num='140',name='P140',func=Pin.BIDIR,do_erc=True), Pin(num='101',name='P101',func=Pin.BIDIR,do_erc=True), Pin(num='111',name='P111',func=Pin.BIDIR,do_erc=True), Pin(num='121',name='P121',func=Pin.BIDIR,do_erc=True), Pin(num='131',name='P131',func=Pin.BIDIR,do_erc=True), Pin(num='141',name='VCCINT',func=Pin.PWRIN,do_erc=True), Pin(num='102',name='P102',func=Pin.BIDIR,do_erc=True), Pin(num='112',name='P112',func=Pin.BIDIR,do_erc=True), Pin(num='122',name='TDO',func=Pin.BIDIR,do_erc=True), Pin(num='132',name='P132',func=Pin.BIDIR,do_erc=True), Pin(num='142',name='P142',func=Pin.BIDIR,do_erc=True), Pin(num='103',name='P103',func=Pin.BIDIR,do_erc=True), Pin(num='113',name='P113',func=Pin.BIDIR,do_erc=True), Pin(num='123',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='133',name='P133',func=Pin.BIDIR,do_erc=True), Pin(num='143',name='I/O/GSR',func=Pin.BIDIR,do_erc=True), Pin(num='104',name='P104',func=Pin.BIDIR,do_erc=True), Pin(num='114',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='124',name='P124',func=Pin.BIDIR,do_erc=True), Pin(num='134',name='P134',func=Pin.BIDIR,do_erc=True), Pin(num='144',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='105',name='P105',func=Pin.BIDIR,do_erc=True), Pin(num='115',name='P115',func=Pin.BIDIR,do_erc=True), Pin(num='125',name='P125',func=Pin.BIDIR,do_erc=True), Pin(num='135',name='P135',func=Pin.BIDIR,do_erc=True), Pin(num='106',name='P106',func=Pin.BIDIR,do_erc=True), Pin(num='116',name='P116',func=Pin.BIDIR,do_erc=True), Pin(num='126',name='P126',func=Pin.BIDIR,do_erc=True), Pin(num='136',name='P136',func=Pin.BIDIR,do_erc=True), Pin(num='107',name='P107',func=Pin.BIDIR,do_erc=True), Pin(num='117',name='P117',func=Pin.BIDIR,do_erc=True), Pin(num='127',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='137',name='P137',func=Pin.BIDIR,do_erc=True), Pin(num='108',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='118',name='P118',func=Pin.BIDIR,do_erc=True), Pin(num='128',name='P128',func=Pin.BIDIR,do_erc=True), Pin(num='138',name='P138',func=Pin.BIDIR,do_erc=True), Pin(num='109',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='119',name='P119',func=Pin.BIDIR,do_erc=True), Pin(num='129',name='P129',func=Pin.BIDIR,do_erc=True), Pin(num='139',name='P139',func=Pin.BIDIR,do_erc=True)]), Part(name='XC9536PC44',dest=TEMPLATE,tool=SKIDL,ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='M1',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='M1',func=Pin.BIDIR,do_erc=True), Pin(num='3',name='M2',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='M4',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='6',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='8',name='M6',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='M8',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='20',name='M15',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='40',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='M9',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='31',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='41',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='M10',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='M16',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='42',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='M11',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='33',name='M12',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='M4',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='M12',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='M17',func=Pin.BIDIR,do_erc=True), Pin(num='34',name='M11',func=Pin.BIDIR,do_erc=True), Pin(num='44',name='M2',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='TDI',do_erc=True), Pin(num='25',name='M17',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='M10',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='TMS',do_erc=True), Pin(num='26',name='M16',func=Pin.BIDIR,do_erc=True), Pin(num='36',name='M9',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='TCK',do_erc=True), Pin(num='27',name='M15',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='M8',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='M13',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='M14',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='M7',func=Pin.BIDIR,do_erc=True), Pin(num='19',name='M14',func=Pin.BIDIR,do_erc=True), Pin(num='29',name='M13',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='I/O/GSR',func=Pin.BIDIR,do_erc=True)]), Part(name='XC9572XL-TQ100',dest=TEMPLATE,tool=SKIDL,keywords='CPLD',description='CPLD, 72 macrocells, 1600 usable gates',ref_prefix='U',num_units=1,fplist=['TQFP*14x14mm*Pitch0.5mm*'],do_erc=True,pins=[ Pin(num='1',name='I/O/GTS3',func=Pin.BIDIR,do_erc=True), Pin(num='2',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='3',name='I/O/GTS1',func=Pin.BIDIR,do_erc=True), Pin(num='4',name='I/O/GTS2',func=Pin.BIDIR,do_erc=True), Pin(num='5',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='6',name='P6',func=Pin.BIDIR,do_erc=True), Pin(num='7',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='8',name='P8',func=Pin.BIDIR,do_erc=True), Pin(num='9',name='P9',func=Pin.BIDIR,do_erc=True), Pin(num='10',name='P10',func=Pin.BIDIR,do_erc=True), Pin(num='20',name='P20',func=Pin.BIDIR,do_erc=True), Pin(num='30',name='P30',func=Pin.BIDIR,do_erc=True), Pin(num='40',name='P40',func=Pin.BIDIR,do_erc=True), Pin(num='50',name='P50',func=Pin.BIDIR,do_erc=True), Pin(num='60',name='P60',func=Pin.BIDIR,do_erc=True), Pin(num='70',name='P70',func=Pin.BIDIR,do_erc=True), Pin(num='80',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='90',name='P90',func=Pin.BIDIR,do_erc=True), Pin(num='11',name='P11',func=Pin.BIDIR,do_erc=True), Pin(num='21',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='31',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='41',name='P41',func=Pin.BIDIR,do_erc=True), Pin(num='51',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='P61',func=Pin.BIDIR,do_erc=True), Pin(num='71',name='P71',func=Pin.BIDIR,do_erc=True), Pin(num='81',name='P81',func=Pin.BIDIR,do_erc=True), Pin(num='91',name='P91',func=Pin.BIDIR,do_erc=True), Pin(num='12',name='P12',func=Pin.BIDIR,do_erc=True), Pin(num='22',name='I/O/GCK1',func=Pin.BIDIR,do_erc=True), Pin(num='32',name='P32',func=Pin.BIDIR,do_erc=True), Pin(num='42',name='P42',func=Pin.BIDIR,do_erc=True), Pin(num='52',name='P52',func=Pin.BIDIR,do_erc=True), Pin(num='62',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='72',name='P72',func=Pin.BIDIR,do_erc=True), Pin(num='82',name='P82',func=Pin.BIDIR,do_erc=True), Pin(num='92',name='P92',func=Pin.BIDIR,do_erc=True), Pin(num='13',name='P13',func=Pin.BIDIR,do_erc=True), Pin(num='23',name='I/O/GCK2',func=Pin.BIDIR,do_erc=True), Pin(num='33',name='P33',func=Pin.BIDIR,do_erc=True), Pin(num='43',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='53',name='P53',func=Pin.BIDIR,do_erc=True), Pin(num='63',name='P63',func=Pin.BIDIR,do_erc=True), Pin(num='73',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='83',name='TDO',func=Pin.OUTPUT,do_erc=True), Pin(num='93',name='P93',func=Pin.BIDIR,do_erc=True), Pin(num='14',name='P14',func=Pin.BIDIR,do_erc=True), Pin(num='24',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='34',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='44',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='54',name='P54',func=Pin.BIDIR,do_erc=True), Pin(num='64',name='P64',func=Pin.BIDIR,do_erc=True), Pin(num='74',name='P74',func=Pin.BIDIR,do_erc=True), Pin(num='84',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='94',name='P94',func=Pin.BIDIR,do_erc=True), Pin(num='15',name='P15',func=Pin.BIDIR,do_erc=True), Pin(num='25',name='P25',func=Pin.BIDIR,do_erc=True), Pin(num='35',name='P35',func=Pin.BIDIR,do_erc=True), Pin(num='45',name='TDI',do_erc=True), Pin(num='55',name='P55',func=Pin.BIDIR,do_erc=True), Pin(num='65',name='P65',func=Pin.BIDIR,do_erc=True), Pin(num='75',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='85',name='P85',func=Pin.BIDIR,do_erc=True), Pin(num='95',name='P95',func=Pin.BIDIR,do_erc=True), Pin(num='16',name='P16',func=Pin.BIDIR,do_erc=True), Pin(num='26',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='P36',func=Pin.BIDIR,do_erc=True), Pin(num='46',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='56',name='P56',func=Pin.BIDIR,do_erc=True), Pin(num='66',name='P66',func=Pin.BIDIR,do_erc=True), Pin(num='76',name='P76',func=Pin.BIDIR,do_erc=True), Pin(num='86',name='P86',func=Pin.BIDIR,do_erc=True), Pin(num='96',name='P96',func=Pin.BIDIR,do_erc=True), Pin(num='17',name='P17',func=Pin.BIDIR,do_erc=True), Pin(num='27',name='I/O/GCK3',func=Pin.BIDIR,do_erc=True), Pin(num='37',name='P37',func=Pin.BIDIR,do_erc=True), Pin(num='47',name='TMS',do_erc=True), Pin(num='57',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='67',name='P67',func=Pin.BIDIR,do_erc=True), Pin(num='77',name='P77',func=Pin.BIDIR,do_erc=True), Pin(num='87',name='P87',func=Pin.BIDIR,do_erc=True), Pin(num='97',name='P97',func=Pin.BIDIR,do_erc=True), Pin(num='18',name='P18',func=Pin.BIDIR,do_erc=True), Pin(num='28',name='P28',func=Pin.BIDIR,do_erc=True), Pin(num='38',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='TCK',do_erc=True), Pin(num='58',name='P58',func=Pin.BIDIR,do_erc=True), Pin(num='68',name='P68',func=Pin.BIDIR,do_erc=True), Pin(num='78',name='P78',func=Pin.BIDIR,do_erc=True), Pin(num='88',name='VCCIO',func=Pin.PWRIN,do_erc=True), Pin(num='98',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='19',name='NC',func=Pin.NOCONNECT,do_erc=True), Pin(num='29',name='P29',func=Pin.BIDIR,do_erc=True), Pin(num='39',name='P39',func=Pin.BIDIR,do_erc=True), Pin(num='49',name='P49',func=Pin.BIDIR,do_erc=True), Pin(num='59',name='P59',func=Pin.BIDIR,do_erc=True), Pin(num='69',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='79',name='P79',func=Pin.BIDIR,do_erc=True), Pin(num='89',name='P89',func=Pin.BIDIR,do_erc=True), Pin(num='99',name='I/O/GSR',func=Pin.BIDIR,do_erc=True), Pin(num='100',name='GND',func=Pin.PWRIN,do_erc=True)]), Part(name='XCF08P',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XCR3064-VQ100',dest=TEMPLATE,tool=SKIDL,description='Xilinx CoolRunner',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='3',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='4',name='B8/TDI',func=Pin.PASSIVE,do_erc=True), Pin(num='6',name='B9',func=Pin.PASSIVE,do_erc=True), Pin(num='8',name='B10',func=Pin.PASSIVE,do_erc=True), Pin(num='9',name='B11',func=Pin.PASSIVE,do_erc=True), Pin(num='10',name='B12',func=Pin.PASSIVE,do_erc=True), Pin(num='20',name='D4',func=Pin.PASSIVE,do_erc=True), Pin(num='30',name='D9',func=Pin.PASSIVE,do_erc=True), Pin(num='40',name='C15',func=Pin.PASSIVE,do_erc=True), Pin(num='60',name='C2',func=Pin.PASSIVE,do_erc=True), Pin(num='80',name='A4',func=Pin.PASSIVE,do_erc=True), Pin(num='90',name='CLK0/IN0',do_erc=True), Pin(num='11',name='PORT_EN',func=Pin.PASSIVE,do_erc=True), Pin(num='21',name='D5',func=Pin.PASSIVE,do_erc=True), Pin(num='31',name='D10',func=Pin.PASSIVE,do_erc=True), Pin(num='41',name='C14',func=Pin.PASSIVE,do_erc=True), Pin(num='51',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='C1',func=Pin.PASSIVE,do_erc=True), Pin(num='71',name='A9',func=Pin.PASSIVE,do_erc=True), Pin(num='81',name='A3',func=Pin.PASSIVE,do_erc=True), Pin(num='91',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='B13',func=Pin.PASSIVE,do_erc=True), Pin(num='32',name='D11',func=Pin.PASSIVE,do_erc=True), Pin(num='42',name='C13',func=Pin.PASSIVE,do_erc=True), Pin(num='52',name='C7',func=Pin.PASSIVE,do_erc=True), Pin(num='62',name='C0/TCK',func=Pin.PASSIVE,do_erc=True), Pin(num='82',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='92',name='B0',func=Pin.PASSIVE,do_erc=True), Pin(num='13',name='B14',func=Pin.PASSIVE,do_erc=True), Pin(num='23',name='D6',func=Pin.PASSIVE,do_erc=True), Pin(num='33',name='D12',func=Pin.PASSIVE,do_erc=True), Pin(num='43',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='63',name='A15',func=Pin.PASSIVE,do_erc=True), Pin(num='73',name='A8/TDO',func=Pin.PASSIVE,do_erc=True), Pin(num='83',name='A2',func=Pin.PASSIVE,do_erc=True), Pin(num='93',name='B1',func=Pin.PASSIVE,do_erc=True), Pin(num='14',name='B15',func=Pin.PASSIVE,do_erc=True), Pin(num='34',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='44',name='C12',func=Pin.PASSIVE,do_erc=True), Pin(num='54',name='C6',func=Pin.PASSIVE,do_erc=True), Pin(num='64',name='A14',func=Pin.PASSIVE,do_erc=True), Pin(num='74',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='84',name='A1',func=Pin.PASSIVE,do_erc=True), Pin(num='94',name='B2',func=Pin.PASSIVE,do_erc=True), Pin(num='15',name='D0/TMS',func=Pin.PASSIVE,do_erc=True), Pin(num='25',name='D7',func=Pin.PASSIVE,do_erc=True), Pin(num='35',name='D13',func=Pin.PASSIVE,do_erc=True), Pin(num='45',name='C11',func=Pin.PASSIVE,do_erc=True), Pin(num='65',name='A13',func=Pin.PASSIVE,do_erc=True), Pin(num='75',name='A7',func=Pin.PASSIVE,do_erc=True), Pin(num='85',name='A0',func=Pin.PASSIVE,do_erc=True), Pin(num='95',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='16',name='D1',func=Pin.PASSIVE,do_erc=True), Pin(num='26',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='D14',func=Pin.PASSIVE,do_erc=True), Pin(num='46',name='C10',func=Pin.PASSIVE,do_erc=True), Pin(num='56',name='C5',func=Pin.PASSIVE,do_erc=True), Pin(num='66',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='76',name='A6',func=Pin.PASSIVE,do_erc=True), Pin(num='86',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='96',name='B3',func=Pin.PASSIVE,do_erc=True), Pin(num='17',name='D2',func=Pin.PASSIVE,do_erc=True), Pin(num='37',name='D15',func=Pin.PASSIVE,do_erc=True), Pin(num='47',name='C9',func=Pin.PASSIVE,do_erc=True), Pin(num='57',name='C4',func=Pin.PASSIVE,do_erc=True), Pin(num='67',name='A12',func=Pin.PASSIVE,do_erc=True), Pin(num='87',name='CLK3/IN3',do_erc=True), Pin(num='97',name='B4',func=Pin.PASSIVE,do_erc=True), Pin(num='18',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='38',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='C8',func=Pin.PASSIVE,do_erc=True), Pin(num='58',name='C3',func=Pin.PASSIVE,do_erc=True), Pin(num='68',name='A11',func=Pin.PASSIVE,do_erc=True), Pin(num='88',name='CLK2/IN2',do_erc=True), Pin(num='98',name='B5',func=Pin.PASSIVE,do_erc=True), Pin(num='19',name='D3',func=Pin.PASSIVE,do_erc=True), Pin(num='29',name='D8',func=Pin.PASSIVE,do_erc=True), Pin(num='39',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='59',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='69',name='A10',func=Pin.PASSIVE,do_erc=True), Pin(num='79',name='A5',func=Pin.PASSIVE,do_erc=True), Pin(num='89',name='CLK1/IN1',do_erc=True), Pin(num='99',name='B6',func=Pin.PASSIVE,do_erc=True), Pin(num='100',name='B7',func=Pin.PASSIVE,do_erc=True)]), Part(name='XCR3064-VQ44',dest=TEMPLATE,tool=SKIDL,description='Xilinx CoolRunner',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='TDI',func=Pin.PASSIVE,do_erc=True), Pin(num='2',name='B9',func=Pin.PASSIVE,do_erc=True), Pin(num='3',name='B10',func=Pin.PASSIVE,do_erc=True), Pin(num='4',name='PORT_EN',func=Pin.PASSIVE,do_erc=True), Pin(num='5',name='B13',func=Pin.PASSIVE,do_erc=True), Pin(num='6',name='B14',func=Pin.PASSIVE,do_erc=True), Pin(num='7',name='TMS',func=Pin.PASSIVE,do_erc=True), Pin(num='8',name='D1',func=Pin.PASSIVE,do_erc=True), Pin(num='9',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='10',name='D3',func=Pin.PASSIVE,do_erc=True), Pin(num='20',name='C10',func=Pin.PASSIVE,do_erc=True), Pin(num='30',name='A10',func=Pin.PASSIVE,do_erc=True), Pin(num='40',name='CLC0/IN0',do_erc=True), Pin(num='11',name='D4',func=Pin.PASSIVE,do_erc=True), Pin(num='21',name='C9',func=Pin.PASSIVE,do_erc=True), Pin(num='31',name='A9',func=Pin.PASSIVE,do_erc=True), Pin(num='41',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='D8',func=Pin.PASSIVE,do_erc=True), Pin(num='22',name='C8',func=Pin.PASSIVE,do_erc=True), Pin(num='32',name='TDO',func=Pin.PASSIVE,do_erc=True), Pin(num='42',name='B0',func=Pin.PASSIVE,do_erc=True), Pin(num='13',name='D9',func=Pin.PASSIVE,do_erc=True), Pin(num='23',name='C3',func=Pin.PASSIVE,do_erc=True), Pin(num='33',name='A7',func=Pin.PASSIVE,do_erc=True), Pin(num='43',name='B1',func=Pin.PASSIVE,do_erc=True), Pin(num='14',name='D10',func=Pin.PASSIVE,do_erc=True), Pin(num='24',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='34',name='A1',func=Pin.PASSIVE,do_erc=True), Pin(num='44',name='B2',func=Pin.PASSIVE,do_erc=True), Pin(num='15',name='D11',func=Pin.PASSIVE,do_erc=True), Pin(num='25',name='C1',func=Pin.PASSIVE,do_erc=True), Pin(num='35',name='A0',func=Pin.PASSIVE,do_erc=True), Pin(num='16',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='26',name='TCK',func=Pin.PASSIVE,do_erc=True), Pin(num='36',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='17',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='27',name='A14',func=Pin.PASSIVE,do_erc=True), Pin(num='37',name='CLK3/IN3',do_erc=True), Pin(num='18',name='C12',func=Pin.PASSIVE,do_erc=True), Pin(num='28',name='A13',func=Pin.PASSIVE,do_erc=True), Pin(num='38',name='CLK2/IN2',do_erc=True), Pin(num='19',name='C11',func=Pin.PASSIVE,do_erc=True), Pin(num='29',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='39',name='CLK1/IN1',do_erc=True)]), Part(name='XCR3128-VQ100',dest=TEMPLATE,tool=SKIDL,description='Xilinx CoolRunner',ref_prefix='U',num_units=1,do_erc=True,pins=[ Pin(num='1',name='E1',func=Pin.PASSIVE,do_erc=True), Pin(num='2',name='E0',func=Pin.PASSIVE,do_erc=True), Pin(num='3',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='4',name='F1/TDI',func=Pin.PASSIVE,do_erc=True), Pin(num='5',name='F2',func=Pin.PASSIVE,do_erc=True), Pin(num='6',name='F3',func=Pin.PASSIVE,do_erc=True), Pin(num='7',name='F4',func=Pin.PASSIVE,do_erc=True), Pin(num='8',name='F5',func=Pin.PASSIVE,do_erc=True), Pin(num='9',name='F6',func=Pin.PASSIVE,do_erc=True), Pin(num='10',name='F10',func=Pin.PASSIVE,do_erc=True), Pin(num='20',name='H6',func=Pin.PASSIVE,do_erc=True), Pin(num='30',name='G10',func=Pin.PASSIVE,do_erc=True), Pin(num='40',name='D1',func=Pin.PASSIVE,do_erc=True), Pin(num='50',name='D13',func=Pin.PASSIVE,do_erc=True), Pin(num='60',name='C3',func=Pin.PASSIVE,do_erc=True), Pin(num='70',name='A4',func=Pin.PASSIVE,do_erc=True), Pin(num='80',name='B5',func=Pin.PASSIVE,do_erc=True), Pin(num='90',name='CLK0/IN0',do_erc=True), Pin(num='11',name='PORT_EN',func=Pin.PASSIVE,do_erc=True), Pin(num='21',name='H10',func=Pin.PASSIVE,do_erc=True), Pin(num='31',name='G6',func=Pin.PASSIVE,do_erc=True), Pin(num='41',name='D2',func=Pin.PASSIVE,do_erc=True), Pin(num='51',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='61',name='C2',func=Pin.PASSIVE,do_erc=True), Pin(num='71',name='A3',func=Pin.PASSIVE,do_erc=True), Pin(num='81',name='B6',func=Pin.PASSIVE,do_erc=True), Pin(num='91',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='12',name='F13',func=Pin.PASSIVE,do_erc=True), Pin(num='22',name='H11',func=Pin.PASSIVE,do_erc=True), Pin(num='32',name='G5',func=Pin.PASSIVE,do_erc=True), Pin(num='42',name='D3',func=Pin.PASSIVE,do_erc=True), Pin(num='52',name='C14',func=Pin.PASSIVE,do_erc=True), Pin(num='62',name='C1/TCK',func=Pin.PASSIVE,do_erc=True), Pin(num='72',name='A2',func=Pin.PASSIVE,do_erc=True), Pin(num='82',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='92',name='E14',func=Pin.PASSIVE,do_erc=True), Pin(num='13',name='F14',func=Pin.PASSIVE,do_erc=True), Pin(num='23',name='H12',func=Pin.PASSIVE,do_erc=True), Pin(num='33',name='G4',func=Pin.PASSIVE,do_erc=True), Pin(num='43',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='53',name='C13',func=Pin.PASSIVE,do_erc=True), Pin(num='63',name='A14',func=Pin.PASSIVE,do_erc=True), Pin(num='73',name='A1/TDO',func=Pin.PASSIVE,do_erc=True), Pin(num='83',name='B10',func=Pin.PASSIVE,do_erc=True), Pin(num='93',name='E13',func=Pin.PASSIVE,do_erc=True), Pin(num='14',name='F15',func=Pin.PASSIVE,do_erc=True), Pin(num='24',name='H13',func=Pin.PASSIVE,do_erc=True), Pin(num='34',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='44',name='D4',func=Pin.PASSIVE,do_erc=True), Pin(num='54',name='C12',func=Pin.PASSIVE,do_erc=True), Pin(num='64',name='A13',func=Pin.PASSIVE,do_erc=True), Pin(num='74',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='84',name='B11',func=Pin.PASSIVE,do_erc=True), Pin(num='94',name='E12',func=Pin.PASSIVE,do_erc=True), Pin(num='15',name='H1/TMS',func=Pin.PASSIVE,do_erc=True), Pin(num='25',name='H14',func=Pin.PASSIVE,do_erc=True), Pin(num='35',name='G3',func=Pin.PASSIVE,do_erc=True), Pin(num='45',name='D5',func=Pin.PASSIVE,do_erc=True), Pin(num='55',name='C11',func=Pin.PASSIVE,do_erc=True), Pin(num='65',name='A12',func=Pin.PASSIVE,do_erc=True), Pin(num='75',name='B0',func=Pin.PASSIVE,do_erc=True), Pin(num='85',name='B12',func=Pin.PASSIVE,do_erc=True), Pin(num='95',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='16',name='H2',func=Pin.PASSIVE,do_erc=True), Pin(num='26',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='36',name='G2',func=Pin.PASSIVE,do_erc=True), Pin(num='46',name='D6',func=Pin.PASSIVE,do_erc=True), Pin(num='56',name='C10',func=Pin.PASSIVE,do_erc=True), Pin(num='66',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='76',name='B1',func=Pin.PASSIVE,do_erc=True), Pin(num='86',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='96',name='E6',func=Pin.PASSIVE,do_erc=True), Pin(num='17',name='H3',func=Pin.PASSIVE,do_erc=True), Pin(num='27',name='G13',func=Pin.PASSIVE,do_erc=True), Pin(num='37',name='G1',func=Pin.PASSIVE,do_erc=True), Pin(num='47',name='D10',func=Pin.PASSIVE,do_erc=True), Pin(num='57',name='C6',func=Pin.PASSIVE,do_erc=True), Pin(num='67',name='A10',func=Pin.PASSIVE,do_erc=True), Pin(num='77',name='B2',func=Pin.PASSIVE,do_erc=True), Pin(num='87',name='CLK3/IN3',do_erc=True), Pin(num='97',name='E5',func=Pin.PASSIVE,do_erc=True), Pin(num='18',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='28',name='G12',func=Pin.PASSIVE,do_erc=True), Pin(num='38',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='48',name='D11',func=Pin.PASSIVE,do_erc=True), Pin(num='58',name='C5',func=Pin.PASSIVE,do_erc=True), Pin(num='68',name='A6',func=Pin.PASSIVE,do_erc=True), Pin(num='78',name='B3',func=Pin.PASSIVE,do_erc=True), Pin(num='88',name='CLK2/IN2',do_erc=True), Pin(num='98',name='E4',func=Pin.PASSIVE,do_erc=True), Pin(num='19',name='H5',func=Pin.PASSIVE,do_erc=True), Pin(num='29',name='G11',func=Pin.PASSIVE,do_erc=True), Pin(num='39',name='VCC',func=Pin.PWRIN,do_erc=True), Pin(num='49',name='D12',func=Pin.PASSIVE,do_erc=True), Pin(num='59',name='GND',func=Pin.PWRIN,do_erc=True), Pin(num='69',name='A5',func=Pin.PASSIVE,do_erc=True), Pin(num='79',name='B4',func=Pin.PASSIVE,do_erc=True), Pin(num='89',name='CLK1/IN1',do_erc=True), Pin(num='99',name='E3',func=Pin.PASSIVE,do_erc=True), Pin(num='100',name='E2',func=Pin.PASSIVE,do_erc=True)]), Part(name='XCR3256-TQ144',dest=TEMPLATE,tool=SKIDL,do_erc=True), Part(name='XCV150_BG352',dest=TEMPLATE,tool=SKIDL,do_erc=True)])
mpi4jax/_src/collective_ops/alltoall.py
Thenerdstation/mpi4jax
122
11122943
<filename>mpi4jax/_src/collective_ops/alltoall.py import numpy as _np from mpi4py import MPI as _MPI from jax import abstract_arrays, core from jax.core import Primitive from jax.interpreters import xla from jax.lax import create_token from jax.lib import xla_client from ..utils import ( HashableMPIType, default_primitive_impl, to_dtype_handle, to_mpi_handle, unpack_hashable, wrap_as_hashable, xla_constant_intc, xla_constant_uintptr, ) from ..decorators import translation_rule_cpu, translation_rule_gpu from ..validation import enforce_types from ..comm import get_default_comm from ..jax_compat import Tracer, Token # The Jax primitive mpi_alltoall_p = Primitive("alltoall_mpi") # Create the primitive mpi_alltoall_impl = default_primitive_impl(mpi_alltoall_p) # This function applies the primitive to an AST @enforce_types( comm=(type(None), _MPI.Intracomm, HashableMPIType), token=(type(None), Token, Tracer), ) def alltoall( x, *, comm=None, token=None, ): """Perform an alltoall operation. Arguments: x: Array input to send. First axis must have size ``nproc``. comm (mpi4py.MPI.Comm): The MPI communicator to use (defaults to a clone of :obj:`COMM_WORLD`). token (Token): XLA token to use to ensure correct execution order. If not given, a new token is generated. Returns: Tuple[DeviceArray, Token]: - Received data. - A new, modified token, that depends on this operation. """ if token is None: token = create_token(x) if comm is None: comm = get_default_comm() size = comm.Get_size() if x.shape[0] != size: raise ValueError("Alltoall input must have shape (nproc, ...)") comm = wrap_as_hashable(comm) return tuple( mpi_alltoall_p.bind( x, token, comm=comm, ) ) # This function compiles the operation @translation_rule_cpu def mpi_alltoall_xla_encode_cpu(c, x, token, comm): comm = unpack_hashable(comm) shape = c.GetShape(x) dtype = shape.element_type() dims = shape.dimensions() # compute total number of elements in array size = comm.Get_size() assert dims[0] == size nitems_per_proc = _np.prod(dims[1:], dtype=int) dtype_handle = to_dtype_handle(dtype) sh = xla_client.Shape.tuple_shape( [ xla_client.Shape.array_shape(dtype, dims), xla_client.Shape.token_shape(), ] ) operands = ( xla_constant_intc(c, nitems_per_proc), x, xla_constant_uintptr(c, dtype_handle), # we only support matching input and output arrays xla_constant_intc(c, nitems_per_proc), xla_constant_uintptr(c, dtype_handle), # xla_constant_uintptr(c, to_mpi_handle(comm)), token, ) return xla_client.ops.CustomCall( c, b"mpi_alltoall", operands=operands, shape=sh, has_side_effect=True, ) @translation_rule_gpu def mpi_alltoall_xla_encode_gpu(c, x, token, comm): from ..xla_bridge.mpi_xla_bridge_gpu import build_alltoall_descriptor comm = unpack_hashable(comm) shape = c.GetShape(x) dtype = shape.element_type() dims = shape.dimensions() # compute total number of elements in send array size = comm.Get_size() assert dims[0] == size nitems_per_proc = _np.prod(dims[1:], dtype=int) dtype_handle = to_dtype_handle(dtype) sh = xla_client.Shape.tuple_shape( [ xla_client.Shape.array_shape(dtype, dims), xla_client.Shape.token_shape(), ] ) descriptor = build_alltoall_descriptor( nitems_per_proc, dtype_handle, # we only support matching input and output arrays nitems_per_proc, dtype_handle, # to_mpi_handle(comm), ) return xla_client.ops.CustomCall( c, b"mpi_alltoall", operands=( x, token, ), shape=sh, opaque=descriptor, has_side_effect=True, ) # This function evaluates only the shapes during AST construction def mpi_alltoall_abstract_eval(xs, token, comm): return ( abstract_arrays.ShapedArray(xs.shape, xs.dtype), core.abstract_token, ) mpi_alltoall_p.multiple_results = True mpi_alltoall_p.def_impl(mpi_alltoall_impl) mpi_alltoall_p.def_abstract_eval(mpi_alltoall_abstract_eval) # assign to the primitive the correct encoder xla.backend_specific_translations["cpu"][mpi_alltoall_p] = mpi_alltoall_xla_encode_cpu xla.backend_specific_translations["gpu"][mpi_alltoall_p] = mpi_alltoall_xla_encode_gpu
test/e101_example.py
shardros/autopep8
3,459
11122971
<gh_stars>1000+ # -*- coding: utf-8 -*- # From https://github.com/coto/gae-boilerplate/blob/233a88c59e46bb10de7a901ef4e6a5b60d0006a5/web/handlers.py """ This example will take a long time if we don't filter innocuous E101 errors from pep8. """ import models.models as models from webapp2_extras.auth import InvalidAuthIdError from webapp2_extras.auth import InvalidPasswordError from webapp2_extras import security from lib import utils from lib import captcha from lib.basehandler import BaseHandler from lib.basehandler import user_required from google.appengine.api import taskqueue import logging import config import webapp2 import web.forms as forms from webapp2_extras.i18n import gettext as _ from webapp2_extras.appengine.auth.models import Unique from lib import twitter class LoginBaseHandler(BaseHandler): """ Base class for handlers with login form. """ @webapp2.cached_property def form(self): return forms.LoginForm(self) class RegisterBaseHandler(BaseHandler): """ Base class for handlers with registration and login forms. """ @webapp2.cached_property def form(self): if self.is_mobile: return forms.RegisterMobileForm(self) else: return forms.RegisterForm(self) @webapp2.cached_property def form_login(self): return forms.LoginForm(self) @webapp2.cached_property def forms(self): return {'form_login' : self.form_login, 'form' : self.form} class SendEmailHandler(BaseHandler): """ Handler for sending Emails Use with TaskQueue """ def post(self): to = self.request.get("to") subject = self.request.get("subject") body = self.request.get("body") sender = self.request.get("sender") utils.send_email(to, subject, body, sender) class LoginHandler(LoginBaseHandler): """ Handler for authentication """ def get(self): """ Returns a simple HTML form for login """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_login.html', **params) def post(self): """ username: Get the username from POST dict password: Get the password from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() try: if utils.is_email_valid(username): user = models.User.get_by_email(username) if user: auth_id = user.auth_ids[0] else: raise InvalidAuthIdError else: auth_id = "own:%s" % username user = models.User.get_by_auth_id(auth_id) password = self.form.password.data.strip() remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False # Password to <PASSWORD> password = utils.encrypt(password, config.salt) # Try to login user with password # Raises InvalidAuthIdError if user is not found # Raises InvalidPasswordError if provided password # doesn't match with specified user self.auth.get_user_by_password( auth_id, password, remember=remember_me) # if user account is not activated, logout and redirect to home if (user.activated == False): # logout self.auth.unset_session() # redirect to home with error message resend_email_uri = self.uri_for('resend-account-activation', encoded_email=utils.encode(user.email)) message = _('Sorry, your account') + ' <strong>{0:>s}</strong>'.format(username) + " " +\ _('has not been activated. Please check your email to activate your account') + ". " +\ _('Or click') + " <a href='"+resend_email_uri+"'>" + _('this') + "</a> " + _('to resend the email') self.add_message(message, 'error') return self.redirect_to('home') # check twitter association in session twitter_helper = twitter.TwitterAuth(self) twitter_association_data = twitter_helper.get_association_data() if twitter_association_data is not None: if models.SocialUser.check_unique(user.key, 'twitter', str(twitter_association_data['id'])): social_user = models.SocialUser( user = user.key, provider = 'twitter', uid = str(twitter_association_data['id']), extra_data = twitter_association_data ) social_user.put() logVisit = models.LogVisit( user=user.key, uastring=self.request.user_agent, ip=self.request.remote_addr, timestamp=utils.get_date_time() ) logVisit.put() self.redirect_to('home') except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Login invalid, Try again.") + "<br/>" + _("Don't have an account?") + \ ' <a href="' + self.uri_for('register') + '">' + _("Sign Up") + '</a>' self.add_message(message, 'error') return self.redirect_to('login') class SocialLoginHandler(BaseHandler): """ Handler for Social authentication """ def get(self, provider_name): provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label'] if not config.enable_federated_login: message = _('Federated login is disabled.') self.add_message(message,'warning') return self.redirect_to('login') callback_url = "%s/social_login/%s/complete" % (self.request.host_url, provider_name) if provider_name == "twitter": twitter_helper = twitter.TwitterAuth(self, redirect_uri=callback_url) self.redirect(twitter_helper.auth_url()) else: message = _('%s authentication is not implemented yet.') % provider_display_name self.add_message(message,'warning') self.redirect_to('edit-profile') class CallbackSocialLoginHandler(BaseHandler): """ Callback (Save Information) for Social Authentication """ def get(self, provider_name): if not config.enable_federated_login: message = _('Federated login is disabled.') self.add_message(message,'warning') return self.redirect_to('login') if provider_name == "twitter": oauth_token = self.request.get('oauth_token') oauth_verifier = self.request.get('oauth_verifier') twitter_helper = twitter.TwitterAuth(self) user_data = twitter_helper.auth_complete(oauth_token, oauth_verifier) if self.user: # new association with twitter user_info = models.User.get_by_id(long(self.user_id)) if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['id'])): social_user = models.SocialUser( user = user_info.key, provider = 'twitter', uid = str(user_data['id']), extra_data = user_data ) social_user.put() message = _('Twitter association added!') self.add_message(message,'success') else: message = _('This Twitter account is already in use!') self.add_message(message,'error') self.redirect_to('edit-profile') else: # login with twitter social_user = models.SocialUser.get_by_provider_and_uid('twitter', str(user_data['id'])) if social_user: # Social user exists. Need authenticate related site account user = social_user.user.get() self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') else: # Social user does not exists. Need show login and registration forms twitter_helper.save_association_data(user_data) message = _('Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.') self.add_message(message,'info') self.redirect_to('login') # Debug Callback information provided # for k,v in user_data.items(): # print(k +":"+ v ) # google, myopenid, yahoo OpenID Providers elif provider_name in models.SocialUser.open_id_providers(): provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label'] # get info passed from OpenId Provider from google.appengine.api import users current_user = users.get_current_user() if current_user: if current_user.federated_identity(): uid = current_user.federated_identity() else: uid = current_user.user_id() email = current_user.email() else: message = _('No user authentication information received from %s. Please ensure you are logging in from an authorized OpenID Provider (OP).' % provider_display_name) self.add_message(message,'error') return self.redirect_to('login') if self.user: # add social account to user user_info = models.User.get_by_id(long(self.user_id)) if models.SocialUser.check_unique(user_info.key, provider_name, uid): social_user = models.SocialUser( user = user_info.key, provider = provider_name, uid = uid ) social_user.put() message = provider_display_name + _(' association added!') self.add_message(message,'success') else: message = _('This %s account is already in use!' % provider_display_name) self.add_message(message,'error') self.redirect_to('edit-profile') else: # login with OpenId Provider social_user = models.SocialUser.get_by_provider_and_uid(provider_name, uid) if social_user: # Social user found. Authenticate the user user = social_user.user.get() self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') else: # Social user does not exist yet so create it with the federated identity provided (uid) # and create prerequisite user and log the user account in if models.SocialUser.check_unique_uid(provider_name, uid): # create user # Returns a tuple, where first value is BOOL. # If True ok, If False no new user is created # Assume provider has already verified email address # if email is provided so set activated to True auth_id = "%s:%s" % (provider_name, uid) if email: unique_properties = ['email'] user_info = self.auth.store.user_model.create_user( auth_id, unique_properties, email=email, activated=True ) else: user_info = self.auth.store.user_model.create_user( auth_id, activated=True ) if not user_info[0]: #user is a tuple message = _('This %s account is already in use!' % provider_display_name) self.add_message(message, 'error') return self.redirect_to('register') user = user_info[1] # create social user and associate with user social_user = models.SocialUser( user = user.key, provider = provider_name, uid = uid ) social_user.put() # authenticate user self.auth.set_session(self.auth.store.user_to_dict(user), remember=True) logVisit = models.LogVisit( user = user.key, uastring = self.request.user_agent, ip = self.request.remote_addr, timestamp = utils.get_date_time() ) logVisit.put() self.redirect_to('home') message = provider_display_name + _(' association added!') self.add_message(message,'success') self.redirect_to('home') else: message = _('This %s account is already in use!' % provider_display_name) self.add_message(message,'error') self.redirect_to('login') else: message = _('%s authentication is not implemented yet.') % provider_display_name self.add_message(message,'warning') self.redirect_to('login') class DeleteSocialProviderHandler(BaseHandler): """ Delete Social association with an account """ @user_required def get(self, provider_name): if self.user: user_info = models.User.get_by_id(long(self.user_id)) social_user = models.SocialUser.get_by_user_and_provider(user_info.key, provider_name) if social_user: social_user.key.delete() message = provider_name + _(' disassociated!') self.add_message(message,'success') else: message = _('Social account on ') + provider_name + _(' not found for this user!') self.add_message(message,'error') self.redirect_to('edit-profile') class LogoutHandler(BaseHandler): """ Destroy user session and redirect to login """ def get(self): if self.user: message = _("You've signed out successfully. Warning: Please clear all cookies and logout \ of OpenId providers too if you logged in on a public computer.") # Info message self.add_message(message, 'info') self.auth.unset_session() # User is logged out, let's try redirecting to login page try: self.redirect(self.auth_config['login_url']) except (AttributeError, KeyError), e: return _("User is logged out, but there was an error "\ "on the redirection.") class RegisterHandler(RegisterBaseHandler): """ Handler for Sign Up Users """ def get(self): """ Returns a simple HTML form for create a new user """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_register.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() name = self.form.name.data.strip() last_name = self.form.last_name.data.strip() email = self.form.email.data.lower() password = self.form.password.data.strip() country = self.form.country.data # Password to SHA512 password = utils.encrypt(password, config.salt) # Passing password_raw=password so password will be hashed # Returns a tuple, where first value is BOOL. # If True ok, If False no new user is created unique_properties = ['username', 'email'] auth_id = "own:%s" % username user = self.auth.store.user_model.create_user( auth_id, unique_properties, password_raw=password, username=username, name=name, last_name=last_name, email=email, country=country, activated=False ) if not user[0]: #user is a tuple message = _('Sorry, This user') + ' <strong>{0:>s}</strong>'.format(username) + " " +\ _('is already registered.') self.add_message(message, 'error') return self.redirect_to('register') else: # User registered successfully # But if the user registered using the form, the user has to check their email to activate the account ??? try: user_info = models.User.get_by_email(email) if (user_info.activated == False): # send email subject = config.app_name + " Account Verification Email" encoded_email = utils.encode(email) confirmation_url = self.uri_for("account-activation", encoded_email = encoded_email, _full = True) # load email's template template_val = { "app_name": config.app_name, "username": username, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } body_path = "emails/account_activation.txt" body = self.jinja2.render_template(body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': str(email), 'subject' : subject, 'body' : body, }) message = _('Congratulations') + ", " + str(username) + "! " + _('You are now registered') +\ ". " + _('Please check your email to activate your account') self.add_message(message, 'success') return self.redirect_to('home') # If the user didn't register using registration form ??? db_user = self.auth.get_user_by_password(user[1].auth_ids[0], password) # Check twitter association in session twitter_helper = twitter.TwitterAuth(self) twitter_association_data = twitter_helper.get_association_data() if twitter_association_data is not None: if models.SocialUser.check_unique(user[1].key, 'twitter', str(twitter_association_data['id'])): social_user = models.SocialUser( user = user[1].key, provider = 'twitter', uid = str(twitter_association_data['id']), extra_data = twitter_association_data ) social_user.put() message = _('Welcome') + " " + str(username) + ", " + _('you are now logged in.') self.add_message(message, 'success') return self.redirect_to('home') except (AttributeError, KeyError), e: message = _('Unexpected error creating '\ 'user') + " " + '{0:>s}.'.format(username) self.add_message(message, 'error') self.abort(403) class AccountActivationHandler(BaseHandler): """ Handler for account activation """ def get(self, encoded_email): try: email = utils.decode(encoded_email) user = models.User.get_by_email(email) # activate the user's account user.activated = True user.put() message = _('Congratulations') + "! " + _('Your account') + " (@" + user.username + ") " +\ _('has just been activated') + ". " + _('Please login to your account') self.add_message(message, "success") self.redirect_to('login') except (AttributeError, KeyError, InvalidAuthIdError), e: message = _('Unexpected error activating '\ 'account') + " " + '{0:>s}.'.format(user.username) self.add_message(message, 'error') self.abort(403) class ResendActivationEmailHandler(BaseHandler): """ Handler to resend activation email """ def get(self, encoded_email): try: email = utils.decode(encoded_email) user = models.User.get_by_email(email) if (user.activated == False): # send email subject = config.app_name + " Account Verification Email" encoded_email = utils.encode(email) confirmation_url = self.uri_for("account-activation", encoded_email = encoded_email, _full = True) # load email's template template_val = { "app_name": config.app_name, "username": user.username, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } body_path = "emails/account_activation.txt" body = self.jinja2.render_template(body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': str(email), 'subject' : subject, 'body' : body, }) message = _('The verification email has been resent to') + " " + str(email) + ". " +\ _('Please check your email to activate your account') self.add_message(message, "success") return self.redirect_to('home') else: message = _('Your account has been activated') + ". " +\ _('Please login to your account') self.add_message(message, "warning") return self.redirect_to('home') except (KeyError, AttributeError), e: message = _('Sorry') + ". " + _('Some error occurred') + "." self.add_message(message, "error") return self.redirect_to('home') class ContactHandler(BaseHandler): """ Handler for Contact Form """ def get(self): """ Returns a simple HTML for contact form """ if self.user: user_info = models.User.get_by_id(long(self.user_id)) if user_info.name or user_info.last_name: self.form.name.data = user_info.name + " " + user_info.last_name if user_info.email: self.form.email.data = user_info.email params = { "exception" : self.request.get('exception') } return self.render_template('boilerplate_contact.html', **params) def post(self): """ validate contact form """ if not self.form.validate(): return self.get() remoteip = self.request.remote_addr user_agent = self.request.user_agent exception = self.request.POST.get('exception') name = self.form.name.data.strip() email = self.form.email.data.lower() message = self.form.message.data.strip() try: subject = _("Contact") body = "" # exceptions for error pages that redirect to contact if exception != "": body = "* Exception error: %s" % exception body = body + """ * IP Address: %s * Web Browser: %s * Sender name: %s * Sender email: %s * Message: %s """ % (remoteip, user_agent, name, email, message) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': config.contact_recipient, 'subject' : subject, 'body' : body, 'sender' : config.contact_sender, }) message = _('Message sent successfully.') self.add_message(message, 'success') return self.redirect_to('contact') except (AttributeError, KeyError), e: message = _('Error sending the message. Please try again later.') self.add_message(message, 'error') return self.redirect_to('contact') @webapp2.cached_property def form(self): return forms.ContactForm(self) class EditProfileHandler(BaseHandler): """ Handler for Edit User Profile """ @user_required def get(self): """ Returns a simple HTML form for edit profile """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.username.data = user_info.username self.form.name.data = user_info.name self.form.last_name.data = user_info.last_name self.form.country.data = user_info.country providers_info = user_info.get_social_providers_info() params['used_providers'] = providers_info['used'] params['unused_providers'] = providers_info['unused'] params['country'] = user_info.country return self.render_template('boilerplate_edit_profile.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() name = self.form.name.data.strip() last_name = self.form.last_name.data.strip() country = self.form.country.data try: user_info = models.User.get_by_id(long(self.user_id)) try: message='' # update username if it has changed and it isn't already taken if username != user_info.username: user_info.unique_properties = ['username','email'] uniques = [ 'User.username:%s' % username, 'User.auth_id:own:%s' % username, ] # Create the unique username and auth_id. success, existing = Unique.create_multi(uniques) if success: # free old uniques Unique.delete_multi(['User.username:%s' % user_info.username, 'User.auth_id:own:%s' % user_info.username]) # The unique values were created, so we can save the user. user_info.username=username user_info.auth_ids[0]='own:%s' % username message+= _('Your new username is ') + '<strong>' + username + '</strong>.' else: message+= _('Username') + " <strong>" + username + "</strong> " + _('is already taken. It is not changed.') # At least one of the values is not unique. self.add_message(message,'error') return self.get() user_info.name=name user_info.last_name=last_name user_info.country=country user_info.put() message+= " " + _('Your profile has been updated!') self.add_message(message,'success') return self.get() except (AttributeError, KeyError, ValueError), e: message = _('Unable to update profile!') logging.error('Unable to update profile: ' + e) self.add_message(message,'error') return self.get() except (AttributeError, TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): return forms.EditProfileForm(self) class EditPasswordHandler(BaseHandler): """ Handler for Edit User Password """ @user_required def get(self): """ Returns a simple HTML form for editing password """ params = {} return self.render_template('boilerplate_edit_password.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() current_password = self.form.current_password.data.strip() password = self.form.password.data.strip() try: user_info = models.User.get_by_id(long(self.user_id)) auth_id = "own:%s" % user_info.username # Password to SHA512 current_password = utils.encrypt(current_password, config.salt) try: user = models.User.get_by_auth_password(auth_id, current_password) # Password to SHA512 password = utils.encrypt(password, config.salt) user.password = security.generate_password_hash(password, length=12) user.put() # send email subject = config.app_name + " Account Password Changed" # load email's template template_val = { "app_name": config.app_name, "first_name": user.name, "username": user.username, "email": user.email, "reset_password_url": self.uri_for("password-reset", _full=True) } email_body_path = "emails/password_changed.txt" email_body = self.jinja2.render_template(email_body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : email_body, 'sender' : config.contact_sender, }) # Login User self.auth.get_user_by_password(user.auth_ids[0], password) self.add_message(_('Password changed successfully'), 'success') return self.redirect_to('edit-profile') except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Your Current Password is wrong, please try again") self.add_message(message, 'error') return self.redirect_to('edit-password') except (AttributeError,TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): if self.is_mobile: return forms.EditPasswordMobileForm(self) else: return forms.EditPasswordForm(self) class EditEmailHandler(BaseHandler): """ Handler for Edit User's Email """ @user_required def get(self): """ Returns a simple HTML form for edit email """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.new_email.data = user_info.email return self.render_template('boilerplate_edit_email.html', **params) def post(self): """ Get fields from POST dict """ if not self.form.validate(): return self.get() new_email = self.form.new_email.data.strip() password = self.form.<PASSWORD>.strip() try: user_info = models.User.get_by_id(long(self.user_id)) auth_id = "own:%s" % user_info.username # Password to <PASSWORD> password = utils.encrypt(password, config.salt) try: # authenticate user by its password user = models.User.get_by_auth_password(auth_id, password) # if the user change his/her email address if new_email != user.email: # check whether the new email has been used by another user aUser = models.User.get_by_email(new_email) if aUser is not None: message = _("The email %s is already registered." % new_email) self.add_message(message, "error") return self.redirect_to("edit-email") # send email subject = config.app_name + " Email Changed Notification" user_token = models.User.create_auth_token(self.user_id) confirmation_url = self.uri_for("email-changed-check", user_id = user_info.get_id(), encoded_email = utils.encode(new_email), token = user_token, _full = True) # load email's template template_val = { "app_name": config.app_name, "first_name": user.name, "username": user.username, "new_email": new_email, "confirmation_url": confirmation_url, "support_url": self.uri_for("contact", _full=True) } old_body_path = "emails/email_changed_notification_old.txt" old_body = self.jinja2.render_template(old_body_path, **template_val) new_body_path = "emails/email_changed_notification_new.txt" new_body = self.jinja2.render_template(new_body_path, **template_val) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : old_body, }) email_url = self.uri_for('taskqueue-send-email') taskqueue.add(url = email_url, params={ 'to': new_email, 'subject' : subject, 'body' : new_body, }) logging.error(user) # display successful message msg = _("Please check your new email for confirmation. Your email will be updated after confirmation.") self.add_message(msg, 'success') return self.redirect_to('edit-profile') else: self.add_message(_("You didn't change your email"), "warning") return self.redirect_to("edit-email") except (InvalidAuthIdError, InvalidPasswordError), e: # Returns error message to self.response.write in # the BaseHandler.dispatcher message = _("Your password is wrong, please try again") self.add_message(message, 'error') return self.redirect_to('edit-email') except (AttributeError,TypeError), e: login_error_message = _('Sorry you are not logged in!') self.add_message(login_error_message,'error') self.redirect_to('login') @webapp2.cached_property def form(self): return forms.EditEmailForm(self) class PasswordResetHandler(LoginBaseHandler): """ Password Reset Handler with Captcha """ reCaptcha_public_key = config.captcha_public_key reCaptcha_private_key = config.captcha_private_key def get(self): chtml = captcha.displayhtml( public_key = self.reCaptcha_public_key, use_ssl = False, error = None) params = { 'captchahtml': chtml, } return self.render_template('boilerplate_password_reset.html', **params) def post(self): # check captcha challenge = self.request.POST.get('recaptcha_challenge_field') response = self.request.POST.get('recaptcha_response_field') remoteip = self.request.remote_addr cResponse = captcha.submit( challenge, response, self.reCaptcha_private_key, remoteip) if cResponse.is_valid: # captcha was valid... carry on..nothing to see here pass else: logging.warning(cResponse.error_code) _message = _('Wrong image verification code. Please try again.') self.add_message(_message, 'error') return self.redirect_to('password-reset') # check if we got an email or username email_or_username = str(self.request.POST.get('email_or_username')).lower().strip() if utils.is_email_valid(email_or_username): user = models.User.get_by_email(email_or_username) _message = _("If the e-mail address you entered") + " (<strong>%s</strong>) " % email_or_username else: auth_id = "own:%s" % email_or_username user = models.User.get_by_auth_id(auth_id) _message = _("If the username you entered") + " (<strong>%s</strong>) " % email_or_username if user is not None: user_id = user.get_id() token = models.User.create_auth_token(user_id) email_url = self.uri_for('taskqueue-send-email') reset_url = self.uri_for('password-reset-check', user_id=user_id, token=token, _full=True) subject = _("Password reminder") body = _('Please click below to create a new password:') +\ """ %s """ % reset_url taskqueue.add(url = email_url, params={ 'to': user.email, 'subject' : subject, 'body' : body, 'sender' : config.contact_sender, }) _message = _message + _("is associated with an account in our records, you will receive "\ "an e-mail from us with instructions for resetting your password. "\ "<br>If you don't receive this e-mail, please check your junk mail folder or ") +\ '<a href="' + self.uri_for('contact') + '">' + _('contact us') + '</a> ' + _("for further assistance.") self.add_message(_message, 'success') return self.redirect_to('login') _message = _('Your email / username was not found. Please try another or ') + '<a href="' + self.uri_for('register') + '">' + _('create an account') + '</a>' self.add_message(_message, 'error') return self.redirect_to('password-reset') class PasswordResetCompleteHandler(LoginBaseHandler): """ Handler to process the link of reset password that received the user """ def get(self, user_id, token): verify = models.User.get_by_auth_token(int(user_id), token) params = {} if verify[0] is None: message = _('There was an error or the link is outdated. Please copy and paste the link from your email or enter your details again below to get a new one.') self.add_message(message, 'warning') return self.redirect_to('password-reset') else: return self.render_template('boilerplate_password_reset_complete.html', **params) def post(self, user_id, token): verify = models.User.get_by_auth_token(int(user_id), token) user = verify[0] password = self.form.password.data.strip() if user and self.form.validate(): # Password to SHA512 password = utils.encrypt(password, config.salt) user.password = security.generate_password_hash(password, length=12) user.put() # Delete token models.User.delete_auth_token(int(user_id), token) # Login User self.auth.get_user_by_password(user.auth_ids[0], password) self.add_message(_('Password changed successfully'), 'success') return self.redirect_to('home') else: self.add_message(_('Please correct the form errors.'), 'error') return self.redirect_to('password-reset-check', user_id=user_id, token=token) @webapp2.cached_property def form(self): if self.is_mobile: return forms.PasswordResetCompleteMobileForm(self) else: return forms.PasswordResetCompleteForm(self) class EmailChangedCompleteHandler(BaseHandler): """ Handler for completed email change Will be called when the user click confirmation link from email """ def get(self, user_id, encoded_email, token): verify = models.User.get_by_auth_token(int(user_id), token) email = utils.decode(encoded_email) if verify[0] is None: self.add_message('There was an error or the link is outdated. Please copy and paste the link from your email.', 'warning') self.redirect_to('home') else: # save new email user = verify[0] user.email = email user.put() # delete token models.User.delete_auth_token(int(user_id), token) # add successful message and redirect self.add_message("Your email has been successfully updated!", "success") self.redirect_to('edit-profile') class SecureRequestHandler(BaseHandler): """ Only accessible to users that are logged in """ @user_required def get(self, **kwargs): user_session = self.user user_session_object = self.auth.store.get_session(self.request) user_info = models.User.get_by_id(long( self.user_id )) user_info_object = self.auth.store.user_model.get_by_auth_token( user_session['user_id'], user_session['token']) try: params = { "user_session" : user_session, "user_session_object" : user_session_object, "user_info" : user_info, "user_info_object" : user_info_object, "userinfo_logout-url" : self.auth_config['logout_url'], } return self.render_template('boilerplate_secure_zone.html', **params) except (AttributeError, KeyError), e: return _("Secure zone error:") + " %s." % e class HomeRequestHandler(RegisterBaseHandler): """ Handler to show the home page """ def get(self): """ Returns a simple HTML form for home """ params = {} return self.render_template('boilerplate_home.html', **params)
examples/wordle-cairo.py
josh95117/freetype-py
242
11122973
<reponame>josh95117/freetype-py #!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # # pycairo/cairocffi-based wordle example - Copyright 2017 <NAME> # Distributed under the terms of the new BSD license. # # rewrite of the numply,matplotlib-based example from <NAME> # - Cairo can paint partly off-screen, so this example does! # # This example behaves differently under pycairo 1.11+ (released in 2017-04-09). # Auto-checked. On older pycairo, it does not draw partial patterns at the edges. # Also, Suface.get_data() is not in the "python 3, pycairo < 1.11" combination. # # ----------------------------------------------------------------------------- from math import cos, sin from numpy import random, sort, sqrt, ndarray, ubyte from freetype import * try: # pycairo 1.11+: from cairo import Region, RectangleInt, REGION_OVERLAP_OUT except ImportError: # stubs for pycairo < 1.11: class Region: def __init__(self): return def union(self, rec): return def contains_rectangle(self, rec): # inhibit drawing return True class RectangleInt: def __init__(self, x, y, w, h): return REGION_OVERLAP_OUT = False from cairo import Context, ImageSurface, FORMAT_A8, FORMAT_ARGB32, Matrix from bitmap_to_surface import make_image_surface def make_label(text, filename, size=12, angle=0): ''' Parameters: ----------- text : string Text to be displayed filename : string Path to a font size : int Font size in 1/64th points angle : float Text angle in degrees ''' face = Face(filename) face.set_char_size( size*64 ) # FT_Angle is a 16.16 fixed-point value expressed in degrees. angle = FT_Angle(angle * 65536) matrix = FT_Matrix( FT_Cos( angle ), - FT_Sin( angle ), FT_Sin( angle ) , FT_Cos( angle ) ) flags = FT_LOAD_RENDER pen = FT_Vector(0,0) FT_Set_Transform( face._FT_Face, byref(matrix), byref(pen) ) previous = 0 xmin, xmax = 0, 0 ymin, ymax = 0, 0 for c in text: face.load_char(c, flags) kerning = face.get_kerning(previous, c) previous = c bitmap = face.glyph.bitmap pitch = face.glyph.bitmap.pitch width = face.glyph.bitmap.width rows = face.glyph.bitmap.rows top = face.glyph.bitmap_top left = face.glyph.bitmap_left pen.x += kerning.x x0 = (pen.x >> 6) + left x1 = x0 + width y0 = (pen.y >> 6) - (rows - top) y1 = y0 + rows xmin, xmax = min(xmin, x0), max(xmax, x1) ymin, ymax = min(ymin, y0), max(ymax, y1) pen.x += face.glyph.advance.x pen.y += face.glyph.advance.y L = ImageSurface(FORMAT_A8, xmax-xmin, ymax-ymin) previous = 0 pen.x, pen.y = 0, 0 ctx = Context(L) for c in text: face.load_char(c, flags) kerning = face.get_kerning(previous, c) previous = c bitmap = face.glyph.bitmap pitch = face.glyph.bitmap.pitch width = face.glyph.bitmap.width rows = face.glyph.bitmap.rows top = face.glyph.bitmap_top left = face.glyph.bitmap_left pen.x += kerning.x x = (pen.x >> 6) - xmin + left y = - (pen.y >> 6) + ymax - top if (width > 0): glyph_surface = make_image_surface(face.glyph.bitmap) ctx.set_source_surface(glyph_surface, x, y) ctx.paint() pen.x += face.glyph.advance.x pen.y += face.glyph.advance.y L.flush() return L if __name__ == '__main__': from PIL import Image n_words = 200 H, W, dpi = 600, 800, 72.0 I = ImageSurface(FORMAT_A8, W, H) ctxI = Context(I) ctxI.rectangle(0,0,800,600) ctxI.set_source_rgba (0.9, 0.9, 0.9, 0) ctxI.fill() S = random.normal(0,1,n_words) S = (S-S.min())/(S.max()-S.min()) S = sort(1-sqrt(S))[::-1] sizes = (12 + S*48).astype(int).tolist() def spiral(): eccentricity = 1.5 radius = 8 step = 0.1 t = 0 while True: t += step yield eccentricity*radius*t*cos(t), radius*t*sin(t) drawn_regions = Region() for size in sizes: angle = random.randint(-25,25) try: L = make_label('Hello', './Vera.ttf', size, angle=angle) except NotImplementedError: raise SystemExit("For python 3.x, you need pycairo >= 1.11+ (from https://github.com/pygobject/pycairo)") h = L.get_height() w = L.get_width() if h < H and w < W: x0 = W//2 + (random.uniform()-.1)*50 y0 = H//2 + (random.uniform()-.1)*50 for dx,dy in spiral(): c = .25+.75*random.random() x = int(x0+dx) y = int(y0+dy) checked = False I.flush() if not (x <= w//2 or y <= h//2 or x >= (W-w//2) or y >= (H-h//2)): ndI = ndarray(shape=(h,w), buffer=I.get_data(), dtype=ubyte, order='C', offset=(x-w//2) + I.get_stride() * (y-h//2), strides=[I.get_stride(), 1]) ndL = ndarray(shape=(h,w), buffer=L.get_data(), dtype=ubyte, order='C', strides=[L.get_stride(), 1]) if ((ndI * ndL).sum() == 0): checked = True new_region = RectangleInt(x-w//2, y-h//2, w, h) if (checked or ( drawn_regions.contains_rectangle(new_region) == REGION_OVERLAP_OUT )): ctxI.set_source_surface(L, 0, 0) pattern = ctxI.get_source() scalematrix = Matrix() scalematrix.scale(1.0,1.0) scalematrix.translate(w//2 - x, h//2 - y) pattern.set_matrix(scalematrix) ctxI.set_source_rgba(c,c,c,c) ctxI.mask(pattern) drawn_regions.union(new_region) break I.flush() I.write_to_png("wordle-cairo.png") Image.open("wordle-cairo.png").show()
lib/chips/chip_generator.py
pigtamer/SNIPER
2,722
11122998
# -------------------------------------------------------------- # SNIPER: Efficient Multi-Scale Training # Licensed under The Apache-2.0 License [see LICENSE for details] # by <NAME> and <NAME> # -------------------------------------------------------------- import chips from bbox.bbox_transform import clip_boxes, ignore_overlaps import numpy as np class chip_generator(object): def __init__(self, chip_stride=32, use_cpp=True): self.use_cpp = use_cpp self.chip_stride = chip_stride def generate(self, boxes, width, height, chipsize): if self.use_cpp: return self._cgenerate(boxes, width, height, chipsize, self.chip_stride) else: return self._pygenerate(boxes, width, height, chipsize, self.chip_stride) @staticmethod def _cgenerate(boxes, width, height, chipsize, stride): boxes = clip_boxes(boxes, np.array([height - 1, width - 1])) return chips.generate(np.ascontiguousarray(boxes, dtype=np.float32), width, height, chipsize, stride) @staticmethod def _pygenerate(boxes, width, height, chipsize, stride): chips = [] boxes = clip_boxes(boxes, np.array([height-1, width-1])) # ensure coverage of image for worst case # corners chips.append([max(width - chipsize, 0), 0, width - 1, min(chipsize, height-1)]) chips.append([0, max(height - chipsize, 0), min(chipsize, width-1), height-1]) chips.append([max(width - chipsize, 0), max(height - chipsize, 0), width-1, height-1]) for i in range(0, width - int(chipsize), stride): for j in range(0, height - int(chipsize), stride): x1 = i y1 = j x2 = i + chipsize - 1 y2 = j + chipsize - 1 chips.append([x1, y1, x2, y2]) for j in range(0, height - int(chipsize), stride): x1 = max(width - chipsize - 1,0) y1 = j x2 = width - 1 y2 = j + chipsize - 1 chips.append([x1, y1, x2, y2]) for i in range(0, width - int(chipsize), stride): x1 = i y1 = max(height - chipsize - 1,0) x2 = i + chipsize - 1 y2 = height - 1 chips.append([x1, y1, x2, y2]) chips = np.array(chips).astype(np.float) p = np.random.permutation(chips.shape[0]) chips = chips[p] overlaps = ignore_overlaps(chips, boxes.astype(np.float)) chip_matches = [] num_matches = [] for j in range(len(chips)): nvids = np.where(overlaps[j, :] == 1)[0] chip_matches.append(set(nvids.tolist())) num_matches.append(len(nvids)) fchips = [] totalmatches = 0 while True: max_matches = 0 max_match = max(num_matches) mid = np.argmax(np.array(num_matches)) if max_match == 0: break if max_match > max_matches: max_matches = max_match maxid = mid bestchip = chip_matches[maxid] fchips.append(chips[maxid]) totalmatches = totalmatches + max_matches # now remove all rois in bestchip for j in range(len(num_matches)): chip_matches[j] = chip_matches[j] - bestchip num_matches[j] = len(chip_matches[j]) return fchips
Competitions/Skillenza/Focuthon/String Replacement.py
cnm06/Competitive-Programming
994
11123102
<gh_stars>100-1000 n = int(raw_input()) for i in xrange(0, n): s = raw_input() s = s.replace('a', 'v#nt&r#s!ty').replace('e', 'v#nt&r#s!ty').replace('i', 'v#nt&r#s!ty').replace('o', 'v#nt&r#s!ty').replace('u', 'v#nt&r#s!ty').replace('A', 'v#nt&r#s!ty').replace('E', 'v#nt&r#s!ty').replace('I', 'v#nt&r#s!ty').replace('O', 'v#nt&r#s!ty').replace('U', 'v#nt&r#s!ty') s = s.replace('#', 'e').replace('&', 'u').replace('!', 'i') print s
pipeline/trainers/segmentation.py
PavelOstyakov/pipeline
214
11123117
from .base import TrainerBase class TrainerSegmentation(TrainerBase): pass
eda/implementacoes/estruturas_de_dados/SingleLinkedList.py
gabrielmbs/Tamburetei
209
11123144
# # Esta implementação foi feita em Python 3. # Esteja ciente disso ao executar :) # Nesse arquivo, focaremos na implementação da Single # Linked List, uma estrutura similar a um array, mas # de tamanho dinâmico, e que funciona por meio de nós, # onde a lista mantém uma referência ao primeiro nó, # e cada nó mantém o seu valor e a referência ao nó # seguinte. As funções implementadas se baseiam nas # necessárias em LEDA. from LinkedListNodes import SingleLinkedListNode class SingleLinkedList(object): def __init__(self): """ Construtor da classe. Inicia uma Single Linked List vazia, apenas com referência ao primeiro elemento. """ self.head = SingleLinkedListNode() def is_empty(self): """ Retorna se a lista está vazia. A lista está vazia se o primeiro elemento for um nó NIL. """ return self.head.is_nil() def insert(self, element): """ Insere um novo elemento na LinkedList. O elemento passado como parâmetro deve ser um elemento válido e, caso seja None, deve ser ignorado. """ if (element != None): if (self.head.is_nil()): self.head.set_value(element) else: current_node = self.head while (not current_node.get_next() == None): current_node = current_node.get_next() current_node.set_next_node(SingleLinkedListNode(element)) def remove(self, element): """ Remove um elemento existente na LinkedList. O elemento passado como parâmetro deve ser um elemento válido, isto é, não pode ser None. Caso o elemento passado não exista na lista, esta deve se manter inalterada. """ to_return = None if (element != None and not self.head.is_nil()): if (self.head.get_value() == element): if (self.head.get_next() != None): self.head = self.head.get_next() else: self.head.set_value(None) to_return = element else: current_node = self.head while (current_node.get_next() != None): if (current_node.get_next().get_value() == element): current_node.set_next_node(current_node.get_next().get_next()) to_return = element break else: current_node = current_node.get_next() return to_return def size(self): """ Calcula o tamanho da lista encadeada. """ linked_size = 0 current_node = self.head while (current_node != None and not current_node.is_nil()): linked_size += 1 current_node = current_node.get_next() return linked_size def search_index(self, searched_value): """ Busca um elemento na lista encadeada e retorna sua posição. Caso o elemento não seja encontrado, deve-se retornar -1. """ index = -1 if (searched_value != None): current_node = self.head while (current_node != None and not current_node.is_nil()): index += 1 if (current_node.get_value() == searched_value): break current_node = current_node.get_next() return index def search(self, searched_value): """ Busca um elemento na lista encadeada e retorna seu valor. Caso o elemento não seja encontrado, deve-se retornar None. """ node_value = None if (searched_value != None): current_node = self.head while (current_node != None and not current_node.is_nil()): if (current_node.get_value() == searched_value): node_value = searched_value break current_node = current_node.get_next() return node_value def to_array(self): """ Transforma a lista encadeada em uma lista, respeitando a ordem dos elementos da lista encadeada """ array = [] current_node = self.head while (current_node != None and not current_node.is_nil()): array.append(current_node.get_value()) current_node = current_node.get_next() return array # Agora, criaremos algumas asserções, verificando a corretude # da implementação da nossa Single linked List :) # Teste 1: inserção e remoção na lista sll = SingleLinkedList() assert sll.is_empty() == True assert sll.to_array() == [] assert sll.size() == 0 sll.insert(3) assert sll.is_empty() == False assert sll.search(3) == 3 assert sll.search_index(3) == 0 assert sll.to_array() == [3] assert sll.size() == 1 assert sll.remove(3) == 3 assert sll.size() == 0 # Teste 2: mais inserção e remoção na lista :D sll = SingleLinkedList() assert sll.is_empty() == True assert sll.to_array() == [] sll.insert(1) assert sll.is_empty() == False assert sll.search(1) == 1 assert sll.search_index(1) == 0 assert sll.to_array() == [1] assert sll.size() == 1 sll.insert(5) assert sll.is_empty() == False assert sll.to_array() == [1, 5] assert sll.search(5) == 5 assert sll.search_index(5) == 1 assert sll.size() == 2 sll.insert(10) assert sll.is_empty() == False assert sll.search(10) == 10 assert sll.search_index(10) == 2 assert sll.to_array() == [1, 5, 10] assert sll.size() == 3 assert sll.remove(5) assert sll.to_array() == [1, 10] assert sll.size() == 2 assert sll.remove(1) assert sll.to_array() == [10] assert sll.size() == 1 assert sll.remove(10) assert sll.to_array() == [] assert sll.size() == 0 # Teste 3: Erros sll = SingleLinkedList() assert sll.is_empty() == True assert sll.to_array() == [] assert sll.size() == 0 sll.insert(15) assert sll.is_empty() == False assert sll.search(15) == 15 assert sll.search_index(15) == 0 assert sll.to_array() == [15] assert sll.size() == 1 assert sll.remove(3) == None assert sll.size() == 1 assert sll.to_array() == [15] sll.insert(None) assert sll.size() == 1 assert sll.to_array() == [15] assert sll.remove(None) == None
djrill/__init__.py
timgates42/Djrill
172
11123152
from ._version import __version__, VERSION from .exceptions import (MandrillAPIError, MandrillRecipientsRefused, NotSerializableForMandrillError, NotSupportedByMandrillError)
prod/stock_gj/run_es_restful_server.py
UtorYeung/vnpy
323
11123162
# flake8: noqa import os import sys # 将repostory的目录i,作为根目录,添加到系统环境中。 ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.append(ROOT_PATH) print(f'append {ROOT_PATH} into sys.path') from vnpy.api.easytrader import server server.run(port=1430)
DQMOffline/CalibTracker/test/CRAFTCalib/SiStripDQMBadStrips_cfg.py
ckamtsikis/cmssw
852
11123198
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms process = cms.Process( "SiStripDQMBadStrips" ) ### Miscellanous ### ## Logging ## process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool( True ) ) process.MessageLogger = cms.Service( "MessageLogger", destinations = cms.untracked.vstring( 'cout' ), cout = cms.untracked.PSet( threshold = cms.untracked.string( 'INFO' ) ) ) ## Profiling ## # Memory # process.SimpleMemoryCheck = cms.Service( "SimpleMemoryCheck", ignoreTotal = cms.untracked.int32( 0 ) ) ### Import ### ## Magnetic fiels ## process.load( "Configuration.StandardSequences.MagneticField_38T_cff" ) ## Geometry ## process.load( "Configuration.StandardSequences.GeometryRecoDB_cff" ) ## Calibration ## # Global tag # process.load( "Configuration.StandardSequences.FrontierConditions_GlobalTag_cff" ) process.GlobalTag.connect = 'frontier://FrontierProd/CMS_COND_21X_GLOBALTAG' process.GlobalTag.globaltag = 'CRAFT_ALL_V4P::All' process.es_prefer_GlobalTag = cms.ESPrefer( 'PoolDBESSource', 'GlobalTag' ) # exclude masking process.siStripQualityESProducer.ListOfRecordToMerge = cms.VPSet( cms.PSet( record = cms.string( 'SiStripDetCablingRcd' ), tag = cms.string( '' ) ), cms.PSet( record = cms.string( 'SiStripBadChannelRcd' ), tag = cms.string( '' ) ) ) ### SiStrip DQM ### ## Reconstruction ## process.load( "DQM.SiStripMonitorClient.RecoForDQM_Cosmic_cff" ) ## DQM modules ## # SiStripMonitorCluster # import DQM.SiStripMonitorCluster.SiStripMonitorCluster_cfi process.siStripMonitorCluster = DQM.SiStripMonitorCluster.SiStripMonitorCluster_cfi.SiStripMonitorCluster.clone() process.siStripMonitorCluster.OutputMEsInRootFile = False process.siStripMonitorCluster.SelectAllDetectors = True process.siStripMonitorCluster.StripQualityLabel = '' process.siStripMonitorCluster.TH1ClusterPos.moduleswitchon = True process.siStripMonitorCluster.TH1nClusters.layerswitchon = True process.siStripMonitorCluster.TH1nClusters.moduleswitchon = False process.siStripMonitorCluster.TH1ClusterStoN.moduleswitchon = False process.siStripMonitorCluster.TH1ClusterStoNVsPos.moduleswitchon = True process.siStripMonitorCluster.TH1ClusterNoise.moduleswitchon = False process.siStripMonitorCluster.TH1NrOfClusterizedStrips.moduleswitchon = False process.siStripMonitorCluster.TH1ModuleLocalOccupancy.moduleswitchon = False process.siStripMonitorCluster.TH1ClusterCharge.moduleswitchon = False process.siStripMonitorCluster.TH1ClusterWidth.moduleswitchon = False ### Input ### ## PoolSource ## process.source = cms.Source( "PoolSource", fileNames = cms.untracked.vstring( '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/422164BB-FEA8-DD11-85E7-001D09F24E39.root', '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/486C391B-00A9-DD11-807C-001D09F24498.root', '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/5AD8595F-04A9-DD11-8627-0030487A1FEC.root', '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/90E5BCC7-1DA9-DD11-813C-001617C3B70E.root', '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/BC010482-01A9-DD11-AC2D-001D09F28EA3.root', '/store/data/Commissioning08/RandomTriggers/RAW/v1/000/068/665/F8554B2C-07A9-DD11-A5AC-001D09F244BB.root' ), skipEvents = cms.untracked.uint32( 0 ) ) ## Input steering ## process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32( 100000 ) ) ### Output ### ## DQM ## process.load( "DQMServices.Core.DQM_cfg" ) process.DQM.collectorHost = '' process.load( "DQMServices.Components.DQMEnvironment_cfi" ) process.dqmSaver.convention = 'Online' process.dqmSaver.dirName = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_TRACKER/DQM/SiStrip/jobs/output' process.dqmSaver.producer = 'DQM' process.dqmSaver.saveByRun = 1 process.dqmSaver.saveAtJobEnd = True process.dqmSaver.referenceHandling = 'qtests' process.dqmEnv.subSystemFolder = 'SiStrip' ### Scheduling ### ## Paths ## # DQM path # process.p = cms.Path( process.siStripDigis * process.siStripZeroSuppression * process.siStripClusters * process.siStripMonitorCluster * process.dqmSaver )
modules/nltk_contrib/tiger/query/constraints.py
h4ck3rm1k3/NLP-project
123
11123225
<filename>modules/nltk_contrib/tiger/query/constraints.py # -*- coding: utf-8 -*- # Copyright © 2007-2008 Stockholm TreeAligner Project # Author: <NAME> <<EMAIL>> # Licensed under the GNU GPLv2 """Contains the classes for constraint checking. The code and the interfaces of this module are still subject to change. Please refer to the inline comments for more information. """ from __future__ import with_statement from nltk_contrib.tiger.query.exceptions import UndefinedNameError from nltk_contrib.tiger.graph import NodeType from nltk_contrib.tiger.index import ID, EDGE_LABEL, CONTINUITY, LEFT_CORNER, RIGHT_CORNER, TOKEN_ORDER, GORN_ADDRESS from nltk_contrib.tiger.query import ast from nltk_contrib.tiger.utils.enum import Enum, enum_member from nltk_contrib.tiger.utils.factory import FactoryBase DEFAULT_TYPES = (NodeType.UNKNOWN, NodeType.UNKNOWN) # WARNING: This module is still subject to heavy change! # FIXME: while the code is correct (well, the tests run through), it's # also quite convoluted. There should be an easier way to do this, # ideally one that allows to combine constraints over the same # pair of nodes. # This is also the reason why this code is not properly documented. # the short story: # A constraint must implement the class method setup_context, which will # be called exactly once for each corpus, and may only be used for setting # data in the evaluator context, which will also be handed into the # from_op method. # The plan is to rewrite this that each constraint takes a node and a list of nodes # and returns those nodes that fulfill the constraint. This way, constraints # can take advantage of natural ordering in some cases # For evaluation, the check method will be called. For speed reasons, # the check methods should not contain any branches. class Direction(Enum): LEFT_TO_RIGHT = enum_member() RIGHT_TO_LEFT = enum_member() NONE = enum_member() BOTH = enum_member() class Constraint(object): __converters__ = {} @classmethod def setup_context(cls, context): pass @classmethod def from_op(cls, op_node, var_types, ctx): kwargs = {} for modifier_name in cls.__attributes__: conv = cls.__converters__.get(modifier_name, lambda *x: x[0]) kwargs[modifier_name] = conv(op_node.modifiers[modifier_name], cls, ctx) kwargs["types"] = var_types return cls(**kwargs) def __init__(self, types, *args): self._types = types self._modifiers = args def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): return self.__class__ is other.__class__ and \ self._modifiers == other._modifiers def get_complement(self): assert self.__attributes__[-1] == "negated" args = list(self._modifiers) args[-1] = not args[-1] return self.__class__(self._types, *args) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, ", ".join(str(x) for x in self._modifiers)) def get_predicates(self, left, right): return [], [] def get_node_variable_types(self): return NodeType.UNKNOWN, NodeType.UNKNOWN def get_singlematch_direction(self): return Direction.NONE class PrecedenceConstraint(Constraint): __attributes__ = ("range", "negated") def __init__(self, types = DEFAULT_TYPES, range = (1, 1), negated = False): super(PrecedenceConstraint, self).__init__(types, range, negated) self._negated = not negated self._direction = Direction.NONE if range == (1, 1): if types == (NodeType.TERMINAL, NodeType.TERMINAL): self.check = self.check_immedidate_tt if self._negated: self._direction = Direction.BOTH else: self.check = self.check_immediate elif range == (1, ): self.check = self.check_general else: self._min, self._max = range self.check = self.ranged_check def ranged_check(self, left_op, right_op, qc): l = left_op if left_op[CONTINUITY] == 0 else qc.get_node(left_op[LEFT_CORNER]) r = right_op if right_op[CONTINUITY] == 0 else qc.get_node(right_op[LEFT_CORNER]) return (self._min <= r[TOKEN_ORDER] - l[TOKEN_ORDER] <= self._max) is self._negated def check_general(self, left_op, right_op, qc): l = left_op if left_op[CONTINUITY] == 0 else qc.get_node(left_op[LEFT_CORNER]) r = right_op if right_op[CONTINUITY] == 0 else qc.get_node(right_op[LEFT_CORNER]) return (l[TOKEN_ORDER] < r[TOKEN_ORDER]) is self._negated def check_immediate(self, left_op, right_op, qc): l = left_op if left_op[CONTINUITY] == 0 else qc.get_node(left_op[LEFT_CORNER]) r = right_op if right_op[CONTINUITY] == 0 else qc.get_node(right_op[LEFT_CORNER]) return (l[TOKEN_ORDER] == r[TOKEN_ORDER] - 1) is self._negated def check_immedidate_tt(self, left_op, right_op, qc): return (left_op[TOKEN_ORDER] == right_op[TOKEN_ORDER] - 1) is self._negated def get_singlematch_direction(self): return self._direction class SiblingConstraint(Constraint): __attributes__ = ("ordered", "negated") def __init__(self, types = DEFAULT_TYPES, ordered = False, negated = False): assert not (negated and ordered) super(SiblingConstraint, self).__init__(types, ordered, negated) if ordered: self.check = self.check_ordered elif negated: self.check = self.check_negated else: self.check = self.check_normal def check_negated(self, left_op, right_op, qc): return len(left_op[GORN_ADDRESS]) != len(right_op[GORN_ADDRESS]) \ or left_op[GORN_ADDRESS][:-1] != right_op[GORN_ADDRESS][:-1] def check_normal(self, left_op, right_op, qc): return len(left_op[GORN_ADDRESS]) == len(right_op[GORN_ADDRESS]) \ and left_op[GORN_ADDRESS][:-1] == right_op[GORN_ADDRESS][:-1] def check_ordered(self, left_op, right_op, qc): if len(left_op[GORN_ADDRESS]) == len(right_op[GORN_ADDRESS]) \ and left_op[GORN_ADDRESS][:-1] == right_op[GORN_ADDRESS][:-1]: l = left_op if left_op[CONTINUITY] == 0 else qc.get_node(left_op[LEFT_CORNER]) r = right_op if right_op[CONTINUITY] == 0 else qc.get_node(right_op[LEFT_CORNER]) return l[TOKEN_ORDER] < r[TOKEN_ORDER] else: return False def guarded(func, exc_type, new_exc_factory, *args, **kwargs): try: return func(*args, **kwargs) except exc_type, e: raise new_exc_factory(e) from contextlib import contextmanager @contextmanager def convert_exception(exc_type, new_exc_type, args = lambda exc: exc.args): try: yield except exc_type, e: raise new_exc_type, args(e) def _get_label_id(label, dct, domain): with convert_exception(KeyError, UndefinedNameError, lambda exc: (domain, exc.args[0])): return dct[label] class DominanceConstraint(Constraint): class ChildrenTypePredicate(object): def get_query_fragment(self): return "node_data.token_order > 1" def __eq__(self, other): return self.__class__ is other.__class__ def __ne__(self, other): return not self.__eq__(other) FOR_NODE = True class EdgeLabelPredicate(object): def __init__(self, label_id): self._label_id = label_id def get_query_fragment(self): return "edge_label = %i" % (self._label_id) def __eq__(self, other): return self.__class__ == other.__class__ and self._label_id == other._label_id def __ne__(self, other): return not self.__eq__(other) FOR_NODE = True __attributes__ = ("label", "range", "negated") __converters__ = { "label": lambda l, cls, ctx: _get_label_id(l, ctx.edge_label_map, UndefinedNameError.EDGELABEL) } @classmethod def setup_context(cls, context): context.edge_label_map = dict(context.db.execute("SELECT label, id FROM edge_labels")) context.edge_label_map[None] = None def __init__(self, types = DEFAULT_TYPES, label = None, range = (1, 1), negated = False): super(DominanceConstraint, self).__init__(types, label, range, negated) self._lbl = label self._negated = not negated self._direction = Direction.NONE if range == (1, 1): if self._negated: self._direction = Direction.RIGHT_TO_LEFT if self._lbl is None: self.check = self.check_immediate else: self.check = self.check_immediate_lbl elif range == (1, ): assert label is None if negated: self.check = self.check_general_ngt else: self.check = self.check_general else: assert label is None self._min, self._max = range self.check = self.ranged_check def ranged_check(self, left_op, right_op, qc): l = len(left_op[GORN_ADDRESS]) r = len(right_op[GORN_ADDRESS]) return (self._min <= r - l <= self._max and buffer(right_op[GORN_ADDRESS][:l]) == left_op[GORN_ADDRESS]) is self._negated def check_general_ngt(self, left_op, right_op, qc): l = len(left_op[GORN_ADDRESS]) r = len(right_op[GORN_ADDRESS]) return not (r - l > 0 and buffer(right_op[GORN_ADDRESS][:l]) == left_op[GORN_ADDRESS]) def check_general(self, left_op, right_op, qc): l = len(left_op[GORN_ADDRESS]) r = len(right_op[GORN_ADDRESS]) return (r - l > 0 and buffer(right_op[GORN_ADDRESS][:l]) == left_op[GORN_ADDRESS]) def check_immediate(self, left_op, right_op, qc): l = len(left_op[GORN_ADDRESS]) r = len(right_op[GORN_ADDRESS]) return (r - l == 1 and buffer(right_op[GORN_ADDRESS][:l]) == left_op[GORN_ADDRESS]) \ is self._negated def check_immediate_lbl(self, left_op, right_op, qc): l = len(left_op[GORN_ADDRESS]) r = len(right_op[GORN_ADDRESS]) return (r - l == 1 and buffer(right_op[GORN_ADDRESS][:l]) == left_op[GORN_ADDRESS] \ and right_op[EDGE_LABEL] == self._lbl) is self._negated def get_predicates(self, left, right): l = [] if right.var_type is NodeType.NONTERMINAL: l.append(self.ChildrenTypePredicate()) return l, [self.EdgeLabelPredicate(self._lbl)] if self._lbl is not None else [] def get_node_variable_types(self): return NodeType.NONTERMINAL, NodeType.UNKNOWN def get_singlematch_direction(self): return self._direction class SecEdgeConstraint(Constraint): class SecEdgePredicate(object): # secedges.label_id is not indexed, therefore it is cheaper to load # all secedges and then check for the correct labels later ORIGIN = 0 TARGET = 1 _ID_NAMES = ["origin_id", "target_id"] def __init__(self, node): self._node = node def get_query_fragment(self): return "(SELECT COUNT(*) FROM secedges WHERE secedges.%s = node_data.id) > 0" % ( self._ID_NAMES[self._node], ) def __eq__(self, other): return self.__class__ == other.__class__ and self._node == other._node def __ne__(self, other): return not self.__eq__(other) FOR_NODE = True __attributes__ = ("label", "negated") __converters__ = { "label": lambda l, cls, ctx: _get_label_id(l, ctx.secedge_label_map, UndefinedNameError.SECEDGELABEL) } @classmethod def setup_context(cls, ev_context): ev_context.secedge_label_map = \ dict(ev_context.db.execute("SELECT label, id FROM secedge_labels")) ev_context.secedge_label_map[None] = None def __init__(self, types = DEFAULT_TYPES, label = None, negated = False): super(SecEdgeConstraint, self).__init__(types, label, negated) self._lbl = label self._neg = negated def check(self, left_op, right_op, query_context): if self._lbl is not None: query_context.cursor.execute( """SELECT origin_id FROM secedges WHERE origin_id = ? AND target_id = ? AND label_id = ?""", (left_op[ID], right_op[ID], self._lbl)) else: query_context.cursor.execute("""SELECT origin_id FROM secedges WHERE origin_id = ? AND target_id = ?""", (left_op[ID], right_op[ID])) return (query_context.cursor.fetchone() is None) is self._neg def get_predicates(self, left, right): return ([self.SecEdgePredicate(self.SecEdgePredicate.ORIGIN)], [self.SecEdgePredicate(self.SecEdgePredicate.TARGET)]) class CornerConstraint(Constraint): _IDX = {"l": LEFT_CORNER, "r": RIGHT_CORNER} __attributes__ = ("corner", "negated") __converters__ = { "corner": lambda c, cls, ctx: cls._IDX[c] } def __init__(self, types, corner, negated = False): super(CornerConstraint, self).__init__(types, corner, negated) if negated: self.check = lambda l, r, qc: l[corner] != r[ID] and not (r[ID] == l[ID] and \ l[CONTINUITY] == 0) else: self.check = lambda l, r, qc: l[corner] == r[ID] or r[ID] == l[ID] and\ l[CONTINUITY] == 0 def get_node_variable_types(self): return NodeType.UNKNOWN, NodeType.TERMINAL class ConstraintFactory(FactoryBase): __classes__ = { ast.SiblingOperator: SiblingConstraint, ast.PrecedenceOperator: PrecedenceConstraint, ast.CornerOperator: CornerConstraint, ast.SecEdgeOperator: SecEdgeConstraint, ast.DominanceOperator: DominanceConstraint } def _create_instance(self, cls, op_node, var_types, context): return cls.from_op(op_node, var_types, context) def _get_switch(self, op_node, var_types, context): return op_node.TYPE
examples/origin_str.py
huihui7987/blind_watermark
1,699
11123299
<filename>examples/origin_str.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # embed string import numpy as np from blind_watermark import WaterMark bwm1 = WaterMark(password_img=1, password_wm=1) bwm1.read_img('pic/ori_img.jpg') wm = '@guofei9987 开源万岁!' bwm1.read_wm(wm, mode='str') bwm1.embed('output/embedded.png') len_wm = len(bwm1.wm_bit) print('Put down the length of wm_bit {len_wm}'.format(len_wm=len_wm)) # %% 解水印 bwm1 = WaterMark(password_img=1, password_wm=1) wm_extract = bwm1.extract('output/embedded.png', wm_shape=len_wm, mode='str') print(wm_extract) assert wm == wm_extract, '提取水印和原水印不一致'
tests/test_fragment_select.py
zverok/wikipedia_ql
334
11123301
<gh_stars>100-1000 import re import pytest from bs4 import BeautifulSoup from wikipedia_ql.fragment import Fragment from wikipedia_ql.selectors import text, text_group, sentence, section, css, alt, page def make_fragment(html): # Because fragment is Wikipedia-oriented and always looks for this div :shrug: return Fragment.parse(f'<div class="mw-parser-output">{html.strip()}</div>') def h(html): return re.sub(r'\s+<', '<', re.sub(r'>\s+', '>', html)) def apply(fragment, selector, simplify=False): if simplify: return [h(str(f.soup)) for f in fragment._select(selector)] else: return [str(f.soup) for f in fragment._select(selector)] def test_select_text(): def select(html, selector): return apply(make_fragment(html), text(pattern=selector)) assert select(""" <h2>Header</h2> <p>Paragraph with a <a href="foo">link</a>. And <b>bold</b> text.</p> """, 'with a link') == ['<span>with a <a href="foo">link</a></span>'] def test_select_section(): def select(fragment, **args): return apply(fragment, section(**args), simplify=True) fragment = make_fragment(""" <section> <h2>Section1</h2> <p>Text1</p> <section> <h3>Section1.1</h3> <p>Text2</p> </section> <section> <h3>Section1.2</h3> <p>Text4</p> </section> </section> <section> <h2>Section2</h2> <p>Text5</p> </section> """) assert select(fragment, heading='Section1') == [ h(""" <div> <h2>Section1</h2> <p>Text1</p> <section> <h3>Section1.1</h3> <p>Text2</p> </section> <section> <h3>Section1.2</h3> <p>Text4</p> </section> </div> """), h(""" <div> <h3>Section1.1</h3> <p>Text2</p> </div> """), h(""" <div> <h3>Section1.2</h3> <p>Text4</p> </div> """) ] assert select(fragment, heading='Section1.1') == [ h(""" <div> <h3>Section1.1</h3> <p>Text2</p> </div> """) ] assert select(fragment, heading='Section2') == [ h(""" <div> <h2>Section2</h2> <p>Text5</p> </div> """) ] # TODO: # all # by level # intersecting sections?.. # text pattern (include, start/stop with, regexp) def test_select_css(): def select(fragment, css_selector): return apply(fragment, css(css_selector=css_selector), simplify=True) fragment = make_fragment(""" <h2>Section1</h2> <p>Text1</p> <ul> <li><a class="first">Link1</a></li> <li class="item"><a class="second">Link2</a>text</li> </ul> """) assert select(fragment, '.item') == [ h(""" <li class="item"><a class="second">Link2</a>text</li> """) ] def test_select_sentence(): def select(fragment, pattern): return apply(fragment, sentence(pattern=pattern)) fragment = make_fragment( """ <p>This is <b>sentence</b> one. This is phrase <a href="foo">two.</a> This is NOT</p> <p>sentence three, probably!</p> """ ) assert select(fragment, 'one') == ['<span>This is <b>sentence</b> one.</span>'] assert select(fragment, 'This.+two') == ['<span>This is phrase <a href="foo">two.</a></span>'] assert select(fragment, 'This.+three') == [] assert select(fragment, None) == [ '<span>This is <b>sentence</b> one.</span>', '<span>This is phrase <a href="foo">two.</a></span>', 'This is NOT', # the whole text after </a> 'sentence three, probably!' # takes the whole paragraph, that's why no span ] def test_select_nested(): def select(fragment, selector): return [str(f.soup) for f in fragment.select(selector)] fragment = make_fragment(""" <section> <h2>Section1</h2> <p>Text1</p> <ul> <li><a class="first">Link1</a></li> <li class="item"><a class="second">Link2</a>text</li> </ul> </section> """) selector = section(heading='Section1', nested=css(css_selector='ul', nested=text(pattern='Li...'))) assert select(fragment, selector) \ == ['<a class="first">Link1</a>', '<a class="second">Link2</a>'] # edge case: css selector of top-level node: selector = text(pattern='Link1', nested=css(css_selector='a')) assert select(fragment, selector) == ['<a class="first">Link1</a>'] def test_select_alt(): def select(fragment, *selectors): return apply(fragment, alt(*selectors), simplify=True) fragment = make_fragment(""" <h2>Section1</h2> <p>Text1</p> <ul> <li><a class="first">Link1</a></li> <li class="item"><a class="second">Link2</a>text</li> </ul> """) assert select(fragment, text(pattern='Link1'), css(css_selector='a.second')) == \ ['<a class="first">Link1</a>', '<a class="second">Link2</a>'] def test_select_text_group(): def select(fragment, id): return apply(fragment, text_group(group_id=id)) fragment = make_fragment( '<p>Some paragraph with <b>empasis</b> and <a href="#foo">link</a></p>' ) assert select(fragment.select(text(pattern=r'with (\S+ and) li(.*)')), 1) == [ '<span><b>empasis</b> and</span>' ] # When not after text with pytest.raises(ValueError, match='text-group is only allowed after text'): select(fragment, 1) # When slice index is out of range assert select(fragment.select(text(pattern=r'with (\S+ and) li(.*)')), 10) == [] # Named groups assert select(fragment.select(text(pattern=r'with (?P<group1>\S+ and) li(.*)')), 'group1') == [ '<span><b>empasis</b> and</span>' ] # Non-existent group: assert select(fragment.select(text(pattern=r'with (?P<group1>\S+ and) li(.*)')), 'group2') == [] def test_select_page(): fragment = make_fragment(""" <h2>Section1</h2> <p>Text1</p> <ul> <li><a class="first">Link1</a></li> <li class="item"><a class="second">Link2</a>text</li> </ul> """) assert str(fragment.select(page()).items[0].soup) == str(fragment.soup) assert str(fragment.select(css(css_selector='li', nested=page())).items[0].soup) == str(fragment.soup) # TODO: (laterz!) wikitable, infobox, ...
packages/vaex-astro/vaex/astro/tap.py
sethvargo/vaex
337
11123308
import numpy as np from vaex.dataset import DatasetArrays class DatasetTap(DatasetArrays): class TapColumn(object): def __init__(self, tap_dataset, column_name, column_type, ucd): self.tap_dataset = tap_dataset self.column_name = column_name self.column_type = column_type self.ucd = ucd self.alpha_min = 0 length = len(tap_dataset) steps = length/1e6 # try to do it in chunks self.alpha_step = 360/steps self.alpha_max = self.alpha_min + self.alpha_step logger.debug("stepping in alpha %f" % self.alpha_step) self.data = [] self.offset = 0 self.shape = (length,) self.dtype = DatasetTap.type_map[self.column_type]().dtype self.left_over_chunk = None self.rows_left = length import tempfile self.download_file = tempfile.mktemp(".vot") def __getitem__(self, slice): start, stop, step = slice.start, slice.stop, slice.step required_length = stop - start assert start >= self.offset chunk_data = self.left_over_chunk enough = False if chunk_data is None else len(chunk_data) >= required_length if chunk_data is not None: logger.debug("start %s offset %s chunk length %s", start, self.offset, len(chunk_data)) #assert len(chunk_data) == start - self.offset if enough: logger.debug("we can skip the query, already have results from previous query") while not enough: adql_query = "SELECT {column_name} FROM {table_name} WHERE alpha >= {alpha_min} AND alpha < {alpha_max} ORDER BY alpha ASC"\ .format(column_name=self.column_name, table_name=self.tap_dataset.table_name, alpha_min=self.alpha_min, alpha_max=self.alpha_max) logger.debug("executing: %s" % adql_query) logger.debug("executing: %s" % adql_query.replace(" ", "+")) url = self.tap_dataset.tap_url + "/sync?REQUEST=doQuery&LANG=ADQL&MAXREC=10000000&FORMAT=votable&QUERY=" +adql_query.replace(" ", "+") import urllib2 response = urllib2.urlopen(url) with open(self.download_file, "w") as f: f.write(response.read()) votable = astropy.io.votable.parse(self.download_file) data = votable.get_first_table().array[self.column_name].data # TODO: respect masked array #table = astropy.table.Table.read(url, format="votable") #, show_progress=False) #data = table[self.column_name].data.data.data logger.debug("new chunk is of lenght %d", len(data)) self.rows_left -= len(data) logger.debug("rows left %d", self.rows_left) if chunk_data is None: chunk_data = data else: chunk_data = np.concatenate([chunk_data, data]) if len(chunk_data) >= required_length: enough = True logger.debug("total chunk is of lenght %d, enough: %s", len(chunk_data), enough) self.alpha_min += self.alpha_step self.alpha_max += self.alpha_step result, self.left_over_chunk = chunk_data[:required_length], chunk_data[required_length:] #print(result) logger.debug("left over is of length %d", len(self.left_over_chunk)) return result #np.zeros(N, dtype=self.dtype) type_map = { 'REAL':np.float32, 'SMALLINT':np.int32, 'DOUBLE':np.float64, 'BIGINT':np.int64, 'INTEGER':np.int32, 'BOOLEAN':np.bool8 } #not supported types yet 'VARCHAR',', u'BOOLEAN', u'INTEGER', u'CHAR def __init__(self, tap_url="http://gaia.esac.esa.int/tap-server/tap/g10_smc", table_name=None): logger.debug("tap url: %r", tap_url) self.tap_url = tap_url self.table_name = table_name if table_name is None: # let us try to infer the table name if tap_url.endswith("tap") or tap_url.endswith("tap/"): pass # this mean we really didn't provide one else: index = tap_url.rfind("tap/") if index != -1: self.tap_url, self.table_name = tap_url[:index+4], self.tap_url[index+4:] logger.debug("inferred url is %s, and table name is %s", self.tap_url, self.table_name) if self.tap_url.startswith("tap+"): # remove tap+ part from tap+http(s), only keep http(s) part self.tap_url = self.tap_url[len("tap+"):] import requests super(DatasetTap, self).__init__(self.table_name) self.req = requests.request("get", self.tap_url+"/tables/") self.path = "tap+" +self.tap_url + "/" + table_name #print dir(self.req) from bs4 import BeautifulSoup #self.soup = BeautifulSoup(req.response) tables = BeautifulSoup(self.req.content, 'xml') self.tap_tables = collections.OrderedDict() for table in tables.find_all("table"): #print table.find("name").string, table.description.string, table["gaiatap:size"] table_name = unicode(table.find("name").string) table_size = int(table["esatapplus:size"]) #print table_name, table_size logger.debug("tap table %r ", table_name) columns = [] for column in table.find_all("column"): column_name = unicode(column.find("name").string) column_type = unicode(column.dataType.string) ucd = column.ucd.string if column.ucd else None unit = column.unit.string if column.unit else None description = column.description.string if column.description else None #print "\t", column_name, column_type, ucd #types.add() columns.append((column_name, column_type, ucd, unit, description)) self.tap_tables[table_name] = (table_size, columns) if not self.tap_tables: raise ValueError("no tables or wrong url") for name, (table_size, columns) in self.tap_tables.items(): logger.debug("table %s has length %d", name, table_size) self._full_length, self._tap_columns = self.tap_tables[self.table_name] self._length = self._full_length logger.debug("selected table table %s has length %d", self.table_name, self._full_length) #self.column_names = [] #self.columns = collections.OrderedDict() for column_name, column_type, ucd, unit, description in self._tap_columns: logger.debug(" column %s has type %s and ucd %s, unit %s and description %s", column_name, column_type, ucd, unit, description) if column_type in self.type_map.keys(): self.column_names.append(column_name) if ucd: self.ucds[column_name] = ucd if unit: self.units[column_name] = unit if description: self.descriptions[column_name] = description self.columns[column_name] = self.TapColumn(self, column_name, column_type, ucd) else: logger.warning(" type of column %s is not supported, it will be skipped", column_name) @classmethod def open(cls, path, *args, **kwargs): return cls(path, *args, **kwargs) @classmethod def quick_test(cls, path, *args, **kwargs): return False @classmethod def can_open(cls, path, *args, **kwargs): can_open = False url = None try: url = urlparse(path) except: return False if url.scheme: if url.scheme.startswith("tap+http"): # will also catch https can_open = True logger.debug("%r can open: %r" %(cls.__name__, can_open)) return can_open
Face Reconstruction/Fast Few-shot Face alignment by Reconstruction/constants.py
swapnilgarg7/Face-X
175
11123310
TRAIN = 'train' VAL = 'val' TEST = 'test'
tests/regressiontests/id_package.py
kylehodgson/SimpleIDML
136
11123348
<reponame>kylehodgson/SimpleIDML # -*- coding: utf-8 -*- import os import unittest from simple_idml.id_package import ZipInDesignPackage from simple_idml.id_package import merge_font_lst CURRENT_DIR = os.path.dirname(__file__) IDMLFILES_DIR = os.path.join(CURRENT_DIR, "IDML") class ZipInDesignPackageTestCase(unittest.TestCase): def test_get_font_list(self): archive_name = os.path.join(IDMLFILES_DIR, "article-1photo-package.zip") zip_indesign_package = ZipInDesignPackage(archive_name, "r") self.assertEqual( set(zip_indesign_package.get_font_list()), set([('AdobeFnt13.lst', 'article-1photo-package/Document fonts/AdobeFnt13.lst'), ('._AdobeFnt13.lst', '__MACOSX/article-1photo-package/Document fonts/._AdobeFnt13.lst'), ('MinionPro-Bold.otf', 'article-1photo-package/Document fonts/MinionPro-Bold.otf'), ('MinionPro-It.otf', 'article-1photo-package/Document fonts/MinionPro-It.otf'), ('MinionPro-Regular.otf', 'article-1photo-package/Document fonts/MinionPro-Regular.otf')]) ) class IDPackageTestCase(unittest.TestCase): def test_merge_font_lst(self): font_suitecases = [ ("output/Document fonts/AdobeFnt13.lst", ""), ("output/Document fonts/AdobeFnt13.lst", ""), ("output/Document fonts/AdobeFnt13.lst", ""), ] filename, content = merge_font_lst(font_suitecases) self.assertEqual(content, "") # The first file may not reference any font. font_suitecases = [ ("output/Document fonts/AdobeFnt13.lst", ""), ("output/Document fonts/AdobeFnt13.lst", """%!Adobe-FontList 1.13 %Locale:0x409 %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:Times-Roman OutlineFileName:\Times-Roman ResourceID:20 MacStyle:0 FileLength:12882 FileModTime:1342371272 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:Times-Roman FamilyName:Times StyleName:Roman MenuName:Times StyleBits:0 WeightClass:400 WidthClass:5 AngleClass:0 FullName:Times Roman WritingScript:Roman OutlineFileName:\TimesRom DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:34006 FileModTime:1342371272 DesignSize:-1 %EndFont """), ("output/Document fonts/AdobeFnt13.lst", """%!Adobe-FontList 1.13 %Locale:0x409 %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:AGaramond-BoldItalic OutlineFileName:\AGaramond-BoldItalic.ECR ResourceID:14570 MacStyle:0 FileLength:10327 FileModTime:1341477738 %EndFont %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:AGaramond-Regular OutlineFileName:\AGaramond-Regular.ECR ResourceID:14562 MacStyle:0 FileLength:18702 FileModTime:1341477705 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:AGaramond-BoldItalic FamilyName:Adobe Garamond StyleName:Bold Italic MenuName:AGaramond Bold StyleBits:3 WeightClass:700 WidthClass:5 AngleClass:1 FullName:Adobe Garamond Bold Italic WritingScript:Roman OutlineFileName:\AGarBolIta DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:45072 FileModTime:1341477738 DesignSize:-1 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:AGaramond-Regular FamilyName:Adobe Garamond StyleName:Regular MenuName:AGaramond StyleBits:0 WeightClass:400 WidthClass:5 AngleClass:0 FullName:Adobe Garamond Regular WritingScript:Roman OutlineFileName:\AGarReg DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:45376 FileModTime:1341477705 DesignSize:-1 %EndFont """)] filename, content = merge_font_lst(font_suitecases) self.assertEqual(content, """%!Adobe-FontList 1.13 %Locale:0x409 %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:Times-Roman OutlineFileName:\Times-Roman ResourceID:20 MacStyle:0 FileLength:12882 FileModTime:1342371272 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:Times-Roman FamilyName:Times StyleName:Roman MenuName:Times StyleBits:0 WeightClass:400 WidthClass:5 AngleClass:0 FullName:Times Roman WritingScript:Roman OutlineFileName:\TimesRom DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:34006 FileModTime:1342371272 DesignSize:-1 %EndFont %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:AGaramond-BoldItalic OutlineFileName:\AGaramond-BoldItalic.ECR ResourceID:14570 MacStyle:0 FileLength:10327 FileModTime:1341477738 %EndFont %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:AGaramond-Regular OutlineFileName:\AGaramond-Regular.ECR ResourceID:14562 MacStyle:0 FileLength:18702 FileModTime:1341477705 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:AGaramond-BoldItalic FamilyName:Adobe Garamond StyleName:Bold Italic MenuName:AGaramond Bold StyleBits:3 WeightClass:700 WidthClass:5 AngleClass:1 FullName:Adobe Garamond Bold Italic WritingScript:Roman OutlineFileName:\AGarBolIta DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:45072 FileModTime:1341477738 DesignSize:-1 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:AGaramond-Regular FamilyName:Adobe Garamond StyleName:Regular MenuName:AGaramond StyleBits:0 WeightClass:400 WidthClass:5 AngleClass:0 FullName:Adobe Garamond Regular WritingScript:Roman OutlineFileName:\AGarReg DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:45376 FileModTime:1341477705 DesignSize:-1 %EndFont """) def test_merge_font_lst_1file(self): font_suitecases = [ ('21283009/Document fonts/AdobeFnt13.lst', """%!Adobe-FontList 1.13 %Locale:0x409 %BeginFont Handler:DirectoryHandler FontType:Suitcase FontName:AGaramond-Bold OutlineFileName:\\AGaramond-Bold.ECR ResourceID:14571 MacStyle:0 FileLength:12909 FileModTime:1341477750 %EndFont %BeginFont Handler:DirectoryHandler FontType:Type1 FontName:AGaramond-Bold FamilyName:Adobe Garamond StyleName:Bold MenuName:AGaramond Bold StyleBits:2 WeightClass:700 WidthClass:5 AngleClass:0 FullName:Adobe Garamond Bold WritingScript:Roman OutlineFileName:\\AGarBol DataFormat:POSTResource UsesStandardEncoding:yes isCFF:no FileLength:46237 FileModTime:1341477750 DesignSize:-1 %EndFont """) ] filename, content = merge_font_lst(font_suitecases) self.assertEqual(content, '%!Adobe-FontList 1.13\n%Locale:0x409\n\n%BeginFont\nHandler:DirectoryHandler\nFontType:Suitcase\nFontName:AGaramond-Bold\nOutlineFileName:\\AGaramond-Bold.ECR\nResourceID:14571\nMacStyle:0\nFileLength:12909\nFileModTime:1341477750\n%EndFont\n\n%BeginFont\nHandler:DirectoryHandler\nFontType:Type1\nFontName:AGaramond-Bold\nFamilyName:Adobe Garamond\nStyleName:Bold\nMenuName:AGaramond Bold\nStyleBits:2\nWeightClass:700\nWidthClass:5\nAngleClass:0\nFullName:Adobe Garamond Bold\nWritingScript:Roman\nOutlineFileName:\\AGarBol\nDataFormat:POSTResource\nUsesStandardEncoding:yes\nisCFF:no\nFileLength:46237\nFileModTime:1341477750\nDesignSize:-1\n%EndFont\n\n') def suite(): suite = unittest.TestLoader().loadTestsFromTestCase(ZipInDesignPackageTestCase) suite.addTests(unittest.TestLoader().loadTestsFromTestCase(IDPackageTestCase)) return suite
commandment/pki/ca.py
pythonModule/commandment
138
11123352
<gh_stars>100-1000 from flask import g, current_app import sqlalchemy.orm.exc from .models import CertificateAuthority from commandment.models import db, Device from commandment.pki.models import CertificateType, Certificate def get_ca() -> CertificateAuthority: if 'ca' not in g: try: ca = db.session.query(CertificateAuthority).filter_by(common_name='COMMANDMENT-CA').one() except sqlalchemy.orm.exc.NoResultFound: ca = CertificateAuthority.create() g.ca = ca return g.ca # # @current_app.teardown_appcontext # def teardown_ca(): # ca = g.pop('ca', None)
generators/datagenerator/segment.py
honey-sangtani-c5i/retail-demo-store
404
11123389
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import datagenerator import json import requests # Segment event support # This follows the Segment HTTP API spec, here: # https://segment.com/docs/connections/sources/catalog/libraries/server/http-api/ # # These classes accept a user, platform, and general event properties and map them # a Segment API compatible representation. This does not support implicit identify # traits class SegmentEvent: def __init__(self, timestamp, user, platform): self.timestamp = timestamp.isoformat() self.sentAt = timestamp.isoformat() self.userId = user.id context = { 'library': { 'version': datagenerator.aws_datagenerator_version, 'name': 'AWSEventGen' } } platform_data = user.get_platform_data(platform) self.anonymousId = platform_data['anonymous_id'] if platform == 'ios': context['device'] = { 'advertisingId': platform_data['advertising_id'], 'manufacturer': 'tim_apple', 'model': platform_data['model'], 'version': platform_data['version'] } elif platform == 'android': context['device'] = { 'advertisingId': platform_data['advertising_id'], 'manufacturer': 'google', 'model': platform_data['model'], 'version': platform_data['version'] } else: context['userAgent'] = platform_data['user_agent'] self.context = context self.integrations = { 'All': True } def toJson(self): return self.__repr__() def __repr__(self): return json.dumps(self.__dict__) class SegmentIdentifyEvent(SegmentEvent): def __init__(self, timestamp, user, platform): super().__init__(timestamp, user, platform) self.type = 'identify' self.traits = user.traits self.traits['name'] = user.name self.traits['email'] = user.email self.traits['age'] = user.age self.traits['gender'] = user.gender self.traits['persona'] = user.persona self.traits['username'] = user.username class SegmentTrackEvent(SegmentEvent): def __init__(self, name, timestamp, user, platform, properties): super().__init__(timestamp, user, platform) self.event = name self.type = 'track' self.properties = properties class SegmentSender: def __init__(self, config): self.config_keys = config # MUST BE: { 'ios': <write key | none>, 'android': <write key | none>, 'web': <write key | none> } self.endpoint = 'https://api.segment.io/v1/batch' def send_batch(self, platform, events, debug=False): batch_events = { "batch": events } key = self.config_keys[platform] if key != None: events_str = json.dumps(batch_events, default=lambda x: x.__dict__) #print(f'Batch length bytes: {len(events_str)}') if debug: parsed = json.loads(events_str) print(f'{json.dumps(parsed, indent=4)}') response = None else: response = requests.post(self.endpoint, data=events_str, auth=(self.config_keys[platform], '')) #print(self.config_keys[platform]) #print(json.dumps(batch_events, default=lambda x: x.__dict__)) #print(f'Sent {len(batch_events["batch"])} events and got {response}') return response else: return None
paz/datasets/fat.py
niqbal996/paz
300
11123395
import os from glob import glob import json import numpy as np from tensorflow.keras.utils import Progbar from ..abstract import Loader from .utils import get_class_names class FAT(Loader): """ Dataset loader for the falling things dataset (FAT). # Arguments path: String indicating full path to dataset e.g. /home/user/fat/ split: String determining the data split to load. e.g. `train`, `val` or `test` class_names: `all` or list. If list it should contain as elements strings indicating each class name. # References - [Deep Object Pose Estimation (DOPE)](https://github.com/NVlabs/Deep_Object_Pose) """ # TODO: Allow selection of class_names. def __init__(self, path, split='train', class_names='all'): if class_names == 'all': class_names = get_class_names('FAT') self.class_to_arg = dict( zip(class_names, list(range(len(class_names))))) super(FAT, self).__init__(path, split, class_names, 'FAT') def load_data(self): scene_names = glob(self.path + 'mixed/*') image_paths, label_paths = [], [] for scene_name in scene_names: scene_image_paths, scene_label_paths = [], [] for image_side in ['left', 'right']: image_names = glob(scene_name + '/*%s.jpg' % image_side) side_image_paths = sorted(image_names, key=self._base_number) label_names = glob(scene_name + '/0*%s.json' % image_side) side_label_paths = sorted(label_names, key=self._base_number) scene_image_paths = scene_image_paths + side_image_paths scene_label_paths = scene_label_paths + side_label_paths image_paths = image_paths + scene_image_paths label_paths = label_paths + scene_label_paths self.data = [] progress_bar = Progbar(len(image_paths)) for sample_arg, sample in enumerate(zip(image_paths, label_paths)): image_path, label_path = sample if not self._valid_name_match(image_path, label_path): raise ValueError('Invalid name match:', image_path, label_path) boxes = self._extract_boxes(label_path) if boxes is None: continue self.data.append({'image': image_path, 'boxes': boxes}) progress_bar.update(sample_arg + 1) return self.data def _extract_boxes(self, json_filename): json_data = json.load(open(json_filename, 'r')) num_objects = len(json_data['objects']) if num_objects == 0: return None box_data = np.zeros((num_objects, 5)) for object_arg, object_data in enumerate(json_data['objects']): bounding_box = object_data['bounding_box'] y_min, x_min = bounding_box['top_left'] y_max, x_max = bounding_box['bottom_right'] x_min, y_min = x_min / 960., y_min / 540. x_max, y_max = x_max / 960., y_max / 540. box_data[object_arg, :4] = x_min, y_min, x_max, y_max class_name = object_data['class'][:-4] box_data[object_arg, -1] = self.class_to_arg[class_name] return box_data def _base_number(self, filename): order = os.path.basename(filename) order = order.split('.')[0] order = float(order) return order def _valid_name_match(self, image_path, label_path): image_name = os.path.basename(image_path) label_name = os.path.basename(label_path) return image_name[:-3] == label_name[:-4]
Python/demos/d13_HelicalGeometry.py
tsadakane/TIGRE
326
11123439
<reponame>tsadakane/TIGRE #%% Demo 13: Helical Geometry tests # # # This demo shows an example of TIGRE working on Helical scan geometries # # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # This file is part of the TIGRE Toolbox # # Copyright (c) 2015, University of Bath and # CERN-European Organization for Nuclear Research # All rights reserved. # # License: Open Source under BSD. # See the full license at # https://github.com/CERN/TIGRE/blob/master/LICENSE # # Contact: <EMAIL> # Codes: https://github.com/CERN/TIGRE/ # Coded by: <NAME> # -------------------------------------------------------------------------- ## #%%Initialize import tigre import numpy as np from tigre.utilities import sample_loader import tigre.algorithms as algs import time #%% Geometry geo = tigre.geometry_default(high_resolution=False) angles = np.linspace(0, 2 * np.pi, 100) angles = np.hstack([angles, angles, angles]) # loop 3 times # Load thorax phatom data head = sample_loader.load_head_phantom(geo.nVoxel) # This makes it helical geo.offOrigin = np.zeros((angles.shape[0], 3)) geo.offOrigin[:, 2] = np.linspace( -1024 / 2 + 128, 1024 / 2 - 128, angles.shape[0] ) # about 256^3 images fit int he detector with this size. # project data data = tigre.Ax(head, geo, angles) # Uncomment if you want to see the data # plotProj(data,angles); ## Reconstruct Helical SIRTimg = algs.sirt(data, geo, angles, 30) # SARTimg=SART(data,geo,angles,30); # takes time CGLSimg = algs.cgls(data, geo, angles, 20) ## Plot results # CGLS and SIRT tigre.plotImg(np.concatenate([head, SIRTimg, CGLSimg], axis=1), dim="z", step=3, clims=[0, 1])
BlogPosts/Hyperparameter_tuning_comparison/hyperparameter_tuning_comparison_code.py
markgraves/roamresearch
190
11123442
""" Companion code for the Roam blog post on hyperparameter optimization. """ import itertools as it import matplotlib import matplotlib.pyplot as plt import numpy as np from operator import itemgetter import pandas as pd import random from scipy import stats from time import time from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from skopt import gp_minimize, forest_minimize, gbrt_minimize from skopt.space import Categorical from sklearn.datasets import make_classification from sklearn.cross_validation import cross_val_score, StratifiedKFold from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from xgboost import XGBClassifier # Ignore these warnings, which are related to the bleeding # edge sklearn we're using. import warnings import sklearn.metrics.base warnings.filterwarnings("ignore", category=DeprecationWarning) __author__ = '<NAME> and <NAME>' __version__ = '1.0' __license__ = 'Apache License Version 2.0, January 2004 http://www.apache.org/licenses/' plt.style.use('../../src/roam.mplstyle') LOG_LOSS = 'log_loss' # Newer versions will use 'neg_log_loss' def artificial_dataset( n_samples=1000, n_features=100, n_classes=3, random_state=None): """ sklearn random classification dataset generation using `sklearn.datasets.make_classification`. Parameters ---------- n_samples : int n_features : int n_classes : int random_state : int or None Returns ------- (X, y) The design matrix `X` and target `y`. """ n_informative = int(0.8 * n_features) n_redundant = int(0.05 * n_features) X, y = make_classification( n_samples=n_samples, n_features=n_features, n_informative=n_informative, n_redundant=n_redundant, n_classes=n_classes, random_state=random_state) return (X, y) def assess( X, y, search_func, model_class, param_grid, xval_indices, loss=LOG_LOSS, test_metric=accuracy_score, dataset_name=None, search_func_args={}): """ The core of the experimental framework. This runs cross-validation and, for the inner loop, does cross-validation to find the optimal hyperparameters according to `search_func`. These optimal parameters are then used for an assessment in the outer cross-validation run. Parameters ---------- X : np.array The design matrix, dimension `(n_samples, n_features)`. y : list or np.array The target, of dimension `n_samples`. search_func : function The search function to use. Can be `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, all defined in this module. This choice has to be compatible with `param_grid`, in the sense that `grid_search` and `randomized_search` require a dict from strings to lists of values, `hyperopt_search` requires a dict from strings to hyperopt sampling functions, and the `skopt` functions require dicts from strings to (upper, lower) pairs of special `skopt` functions. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to appropriate specifications of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below (though not all methods call for that). This has to be compatible with `search_func`, and all the values must be suitable arguments to `model_class` instances. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. xval_indices : list List of train and test indices into `X` and `y`. This defines the cross-validation. This is done outside of this method to allow for identical splits across different experiments. dataset_name : str or None Name for the dataset being analyzed. For book-keeping and display only. search_func_args : dict Keyword arguments to feed to `search_func`. Returns ------- dict Accumulated information about the experiment: {'Test accuracy': list of float, 'Cross-validation time (in secs.)':list of float, 'Parameters sampled': list of int, 'Method': search_func.__name__, 'Model': model_class.__name__, 'Dataset': dataset_name, 'Best parameters': list of dict, 'Mean test accuracy': float, 'Mean cross-validation time (in secs.)': float, 'Mean parameters sampled': float} """ data = {'Test accuracy': [], 'Cross-validation time (in secs.)': [], 'Parameters sampled': [], 'Best parameters': [], 'Method': search_func.__name__, 'Model': model_class.__name__, 'Dataset': dataset_name, 'Best parameters':[]} for cv_index, (train_index, test_index) in enumerate(xval_indices, start=1): print("\t{}".format(cv_index)) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] start = time() results = search_func( X_train, y_train, model_class, param_grid, loss, **search_func_args) data['Cross-validation time (in secs.)'].append(time() - start) data['Parameters sampled'].append(len(results)) best_params = sorted(results, key=itemgetter('loss'), reverse=False) best_params = best_params[0]['params'] data['Best parameters'].append(best_params) bestmod = model_class(**best_params) bestmod.fit(X_train, y_train) predictions = bestmod.predict(X_test) data['Test accuracy'].append(test_metric(y_test, predictions)) data['Mean test accuracy'] = np.mean( data['Test accuracy']) data['Mean cross-validation time (in secs.)'] = np.mean( data['Cross-validation time (in secs.)']) data['Mean parameters sampled'] = np.mean( data['Parameters sampled']) return data def get_cross_validation_indices(X, y, n_folds=5, random_state=None): """ Use `StratifiedKFold` to create an `n_folds` cross-validator for the dataset defined by `X` and y`. Only `y` is used, but both are given for an intuitive interface; `X` could just as easily be used. """ return StratifiedKFold(y, n_folds=n_folds, random_state=random_state) def random_search( X_train, y_train, model_class, param_grid, loss, sampsize=None): """ Random search over the grid defined by `param_grid`. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. sampsize : int or None Number of samples to take from the grid. If `None`, then `sampsize` is half the size of the full grid. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. Example ------- >>> param_grid = { 'max_depth' : [4, 8], 'learning_rate' : [0.01, 0.3], 'n_estimators' : [20, 50], 'objective' : ['multi:softprob'], 'gamma' : [0, 0.25], 'min_child_weight' : [1], 'subsample' : [1], 'colsample_bytree' : [1]} >>> res = random_search(X, y, XGBClassifier, param_grid, LOG_LOSS) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ exapnded_param_grid = expand_grid(param_grid) if sampsize == None: sampsize = int(len(exapnded_param_grid) / 2.0) samp = random.sample(exapnded_param_grid, sampsize) results = [] for params in samp: err = cross_validated_scorer( X_train, y_train, model_class, params, loss) results.append({'loss': err, 'params': params}) return results def grid_search(X_train, y_train, model_class, param_grid, loss): """ Full grid search over the grid defined by `param_grid`. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. Example ------- >>> param_grid = { 'max_depth' : [4, 8], 'learning_rate' : [0.01, 0.3], 'n_estimators' : [20, 50], 'objective' : ['multi:softprob'], 'gamma' : [0, 0.25], 'min_child_weight' : [1], 'subsample' : [1], 'colsample_bytree' : [1]} >>> res = grid_search(X, y, XGBClassifier, param_grid, LOG_LOSS) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ results = [] expanded_param_grid = expand_grid(param_grid) for params in expanded_param_grid: err = cross_validated_scorer( X_train, y_train, model_class, params, loss) results.append({'loss': err, 'params': params}) return results def expand_grid(param_grid): """ Expand `param_grid` to the full grid, as a list of dicts. Parameters ---------- param_grid : dict Map from parameter names to lists of appropriate values for that parameter. This is not the expanded grid, but rather the simple map that can be expanded by `expand_grid` below. This method performs the expansion. Returns ------- list of dict If `param_grid` was {'foo': [1,2], 'bar': [3,4]} Then the return value would be [{'foo': 1, 'bar': 3}, {'foo': 1, 'bar': 4}, {'foo': 2, 'bar': 3}, {'foo': 2, 'bar': 4}] """ varNames = sorted(param_grid) return [dict(zip(varNames, prod)) for prod in it.product(*(param_grid[varName] for varName in varNames))] def cross_validated_scorer( X_train, y_train, model_class, params, loss, kfolds=5): """ The scoring function used through this module, by all search functions. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. params : dict Map from parameter names to single appropriate values for that parameter. This will be used to build a model from `model_class`. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. kfolds : int Number of cross-validation runs to do. Returns ------- float Average loss over the `kfolds` runs. """ mod = model_class(**params) cv_score = -1 * cross_val_score( mod, X_train, y=y_train, scoring=loss, cv=kfolds, n_jobs=1).mean() return cv_score def hyperopt_search( X_train, y_train, model_class, param_grid, loss, max_evals=100): """ Search according to hyperopt's Tree of Parzen Estimator. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to `hyperopt` sampling functions. The parameter names need to work with `model_class`, and the values specifying how to sample values. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. max_evals : int Number of evaluations to do. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. These values are accumulated and stored by the `Trials` instance used in the call to `fmin`. A 'status' record is also retained but not used elsewhere in the module. Example ------- >>> hyperopt_grid = { 'max_depth' : hp.choice('max_depth', range(4, 13, 1)), 'learning_rate' : hp.quniform('learning_rate', 0.01, 0.5, 0.01), 'n_estimators' : hp.choice('n_estimators', range(20, 205, 5)), 'objective' : 'multi:softprob', 'gamma' : hp.quniform('gamma', 0, 0.50, 0.01), 'min_child_weight' : hp.quniform('min_child_weight', 1, 5, 1), 'subsample' : hp.quniform('subsample', 0.1, 1, 0.01), 'colsample_bytree' : hp.quniform('colsample_bytree', 0.1, 1.0, 0.01)} >>> res = hyperopt_search(X, y, XGBClassifier, hyperopt_grid, LOG_LOSS, max_evals=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ def objective(params): err = cross_validated_scorer( X_train, y_train, model_class, params, loss) return {'loss': err, 'params': params, 'status': STATUS_OK} trials = Trials() results = fmin( objective, param_grid, algo=tpe.suggest, trials=trials, max_evals=max_evals) return trials.results def skopt_search( X_train, y_train, model_class, param_grid, loss, skopt_method, n_calls=100): """ General method for applying `skopt_method` to the data. Parameters ---------- X_train : np.array The design matrix, dimension `(n_samples, n_features)`. y_train : list or np.array The target, of dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. param_grid : dict Map from parameter names to pairs of values specifying the upper and lower ends of the space from which to sample. The values can also be directly specified as `skopt` objects like `Categorical`. loss : function or string An appropriate loss function or string recognizable by sklearn.cross_validation.cross_val_score. In sklearn, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. skopt_method : skopt function Can be `gp_minimize`, `forest_minimize`, or `gbrt_minimize`. n_calls : int Number of evaluations to do. Returns ------- list of dict Each has keys 'loss' and 'params', where 'params' stores the values from `param_grid` for that run. The primary organizing value is 'loss'. """ param_keys, param_vecs = zip(*param_grid.items()) param_keys = list(param_keys) param_vecs = list(param_vecs) def skopt_scorer(param_vec): params = dict(zip(param_keys, param_vec)) err = cross_validated_scorer( X_train, y_train, model_class, params, loss) return err outcome = skopt_method(skopt_scorer, list(param_vecs), n_calls=n_calls) results = [] for err, param_vec in zip(outcome.func_vals, outcome.x_iters): params = dict(zip(param_keys, param_vec)) results.append({'loss': err, 'params': params}) return results def skopt_gp_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the Gaussian Process search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_gp_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, gp_minimize, n_calls=n_calls) def skopt_forest_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the decision tree search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_forest_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, forest_minimize, n_calls=n_calls) def skopt_gbrt_search( X_train, y_train, model_class, param_grid, loss, n_calls=100): """`skopt` according to the gradient-boosting-tree search method. For details on the parameters, see `skopt_search`. Example ------- >>> skopt_grid = { 'max_depth': (4, 12), 'learning_rate': (0.01, 0.5), 'n_estimators': (20, 200), 'objective' : Categorical(('multi:softprob',)), 'gamma': (0, 0.5), 'min_child_weight': (1, 5), 'subsample': (0.1, 1), 'colsample_bytree': (0.1, 1)} >>> res = skopt_gbrt_search(X, y, XGBClassifier, skopt_grid, LOG_LOSS, n_calls=10) To be followed by (see below): >>> best_params, best_loss = best_results(res) """ return skopt_search( X_train, y_train, model_class, param_grid, loss, gbrt_minimize, n_calls=n_calls) def prepare_summary(results): """Format the `results` dictionary into a `pandas` `DataFrame`, with columns 'Method', 'Mean parameters sampled', 'Mean test accuracy', 'Mean cross-validation time (in secs.)'.""" results = {k:v for k,v in results.items() if k not in {'Test accuracy', 'Cross-validation time (in secs.)', 'Parameters sampled'}} df = pd.DataFrame([results]) df = df[['Method', 'Mean parameters sampled', 'Mean test accuracy', 'Mean cross-validation time (in secs.)']] return df def prepare_summaries(results_list): """Format all the results dictionaries in `results_list` into a single pandas `DataFrame`. """ dfs = [] for results in results_list: dfs.append(prepare_summary(results)) combo = pd.concat(dfs, axis=0) combo.index = range(1,len(combo)+1) return combo def run_experiments( experimental_run, dataset, model_class=XGBClassifier, loss=LOG_LOSS, test_metric=accuracy_score, random_state=None, dataset_name=None): """ Basic experimental framework. Parameters ---------- experimental_run : list of tuples These tuples should have exactly three members: the first one of `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, the second an appropriate `param_grid` dict for that function, and the third a dict specifying keyword arguments to the search function. dataset : (np.array, iterable) A dataset (X, y) where `X` has dimension `(n_samples, n_features)` and `y` has dimension `n_samples`. model_class : classifier A classifier model in the mode of `sklearn`, with at least `fit` and `predict` methods operating on things like `X` and `y`. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. random_state : int dataset_name : str or None Informal name to give the dataset. Purely for book-keeping. Returns ------- list of dict Each dict is a results dictionary of the sort returned by `assess`. """ X, y = dataset skf = get_cross_validation_indices( X, y, random_state=random_state) all_results = [] # This loop can easily be parallelized, but doing so can # be tricky on some systems, since `cross_val_score` # calls `joblib` even if `n_jobs=1`, resulting in # nested parallel jobs even if there is no actual # parallelization elsewhere in the experimental run. for search_func, param_grid, kwargs in experimental_run: print(search_func.__name__) all_results.append( assess( X, y, search_func=search_func, model_class=XGBClassifier, param_grid=param_grid, xval_indices=skf, loss=loss, test_metric=test_metric, dataset_name=dataset_name, search_func_args=kwargs)) return all_results def representation_size_experiments( experimental_run, n_samples=100, min_features=50, max_features=100, increment=50, loss=LOG_LOSS, test_metric=accuracy_score, random_state=None): """Run a series of experiments with `experimental_run` exploring `n_feature` sizes from `min_features` to `max_features` (inclusive) in increments of `increment`. Parameters ---------- experimental_run : list of tuples These tuples should have exactly three members: the first one of `grid_search`, `randomized_search`, `hyperopt_search`, `skopt_gp_minimize`, `skopt_forest_minimize`, or `skopt_forest_gbrt`, the second an appropriate `param_grid` dict for that function, and the third a dict specifying keyword arguments to the search function. n_samples : int Number of examples. min_features : int Smallest feature representation size. max_features : int Largest feature representation size. increment : int Increments between `min_features` and `max_features`. loss : function or string An appropriate loss function or string recognizable by `sklearn.cross_validation.cross_val_score`. In `sklearn`, scores are positive and losses are negative because they maximize, but here we are minimizing so we always want smaller to mean better. test_metric : function An `sklearn.metrics` function. random_state : int Returns ------- list of values returned by `run_experiments`. """ all_results = [] for n_features in range(min_features, max_features+1, increment): dataset = artificial_dataset( n_samples=100, n_features=n_features, n_classes=3, random_state=random_state) results = run_experiments( experimental_run, dataset, loss=loss, test_metric=accuracy_score, random_state=random_state, dataset_name=n_features) all_results.append(results) return all_results def plot_representation_size_accuracy( representation_size_results, include_cis=True): """Plot the test accuracy values from the output of `representation_size_experiments`""" kwargs = { 'metric_name': 'Test accuracy', 'metric_mean_name': 'Mean test accuracy', 'ylabel': 'Test accuracy', 'value_transform': (lambda x : x), 'include_cis': include_cis, 'ylabel_overlap_threshold': 0.02} plot_representation_size(representation_size_results, **kwargs) def plot_representation_size_time( representation_size_results, include_cis=True): """Plot the cross-validation time values from the output of `representation_size_experiments`""" kwargs = { 'metric_name': 'Cross-validation time (in secs.)', 'metric_mean_name': 'Mean cross-validation time (in secs.)', 'ylabel': 'Cross-validation time (log-scale)', 'value_transform': (lambda x : np.log(x)), 'include_cis': include_cis, 'ylabel_overlap_threshold': 0.2} plot_representation_size(representation_size_results, **kwargs) def plot_representation_size( representation_size_results, metric_name='', metric_mean_name='', ylabel='', value_transform=(lambda x : x), include_cis=True, ylabel_overlap_threshold=0.2): """Generic interface for plotting the output of `representation_size_experiments`""" fig, ax = plt.subplots(1) fig.set_figwidth(10) fig.set_figheight(8) methods = set([d['Method'] for results in representation_size_results for d in results]) colors = { 'grid_search': '#212121', 'random_search': '#876DB5', 'hyperopt_search': '#4D8951', 'skopt_forest_minimize': '#0499CC', 'skopt_gp_minimize': '#03A9F4', 'skopt_forest_gbrt': '#32A8B4'} text_positions = [] for method in methods: color = colors[method] method_results = [d for results in representation_size_results for d in results if d['Method']==method] method_results = sorted(method_results, key=itemgetter('Dataset')) xpos = [d['Dataset'] for d in method_results] mus = [value_transform(d[metric_mean_name]) for d in method_results] if include_cis: cis = [value_transform(get_ci(d[metric_name])) for d in method_results] for x, ci in zip(xpos, cis): ax.plot([x,x], ci, color=color) ax.plot( xpos, mus, marker='.', linestyle='-', markersize=12, color=color) text_positions.append(mus[-1]) method_text_positions = [[p,m] for p, m in zip(text_positions, methods)] method_text_positions = sorted(method_text_positions) for i in range(len(method_text_positions)-1): here = method_text_positions[i][0] there = method_text_positions[i+1][0] if there - here < ylabel_overlap_threshold: method_text_positions[i+1][0] = here + ylabel_overlap_threshold xpad = min(xpos)*0.2 for text_pos, method in method_text_positions: ax.text(max(xpos)+(xpad*2), text_pos, method, fontsize=16, color=colors[method], va='center', weight='bold') ax.set_xlim([min(xpos)-xpad, max(xpos)+xpad]) ax.set_xlabel("Number of features") ax.set_ylabel(ylabel) def get_ci(vals, percent=0.95): """Confidence interval for `vals` from the Students' t distribution. Uses `stats.t.interval`. Parameters ---------- percent : float Size of the confidence interval. The default is 0.95. The only requirement is that this be above 0 and at or below 1. Returns ------- tuple The first member is the upper end of the interval, the second the lower end of the interval. """ if len(set(vals)) == 1: return (vals[0], vals[0]) mu = np.mean(vals) df = len(vals)-1 sigma = np.std(vals) / np.sqrt(len(vals)) return stats.t.interval(percent, df, loc=mu, scale=sigma)
爬虫小demo/31 下载bilibili视频.py
lb2281075105/Python-Spider
713
11123455
import requests from lxml import html import re import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def star(url): url2 = "https://api.bilibili.com/x/player/playurl?avid={avid}&cid={cid}&qn=32&type=&otype=json" headers2 = { "host": "", "Referer": "https://www.bilibili.com", "User-Agent": "Mozilla/5.0(Windows NT 10.0;WOW64) AppleWebKit/537.36(KHTML,likeGecko)Chrome/63.0.3239.132Safari/537.36" } avid = re.findall("video/av(.+)\?", url) print(avid) cid ,name = get_cid(avid[0]) print(cid,name) flv_url , size = get_flvurl(url2.format(avid=avid[0],cid=cid)) shuju = size / 1024 / 1024 print("本视频大小为:%.2fM" % shuju) h = re.findall("https://(.+)com",flv_url) host = h[0]+"com" headers2["host"] = host res = requests.get(flv_url,headers=headers2,stream=True, verify=False) print(res.status_code) save_movie(res,name) def get_cid(aid):#获得cid header = { 'host': 'api.bilibili.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0' } url = "https://api.bilibili.com/x/player/pagelist?aid={aid}&jsonp=jsonp".format(aid=aid) response = requests.get(url,headers=header).json() # print(response["data"]) # 这个地方设置index是因为下载集合里面的视频,顺序,0代表下载第一个视频,1代表下载集合里面第二个视频,2,3,4...依次类推 index = 0 return response["data"][index]["cid"] ,response["data"][index]["part"] def get_flvurl(url):#获得视频真实flv地址 header = {'host': 'api.bilibili.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'} response = requests.get(url,headers=header).json() return response["data"]["durl"][0]["url"],response["data"]["durl"][0]["size"] def save_movie(res,name):#保存视频 chunk_size = 1024 with open("{name}.flv".format(name = name),"wb") as f: for data in res.iter_content(1024): f.write(data) if __name__ == "__main__": # 把下面的av后面的'583959574'在要下载的视频集合里面找到就可以下载视频了 url = "https://www.bilibili.com/video/av583959574?spm_id_from=333.334.b_62696c695f646f756761.5" star(url)
benchexec/tools/skink.py
MartinSpiessl/benchexec
137
11123506
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 <NAME> <https://www.sosy-lab.org> # SPDX-FileCopyrightText: 2015 <NAME> # # SPDX-License-Identifier: Apache-2.0 import benchexec.util as util import benchexec.tools.template import benchexec.result as result class Tool(benchexec.tools.template.BaseTool): REQUIRED_PATHS = [ "bin", "lib", "include", "logback-test.xml", "skink.sh", "skink.jar", "skink-fpbv.jar", "application.conf", ] def executable(self): return util.find_executable("skink.sh") def name(self): return "skink" def version(self, executable): return self._version_from_tool(executable) def determine_result(self, returncode, returnsignal, output, isTimeout): output = "\n".join(output) if "TRUE" in output: status = result.RESULT_TRUE_PROP elif "FALSE" in output: status = result.RESULT_FALSE_REACH else: status = result.RESULT_UNKNOWN return status
dask/tests/test_ml.py
marcelned/dask
9,684
11123523
def test_basic(): try: import dask_ml # noqa: F401 except ImportError: try: from dask.ml.model_selection import GridSearchCV # noqa: F401 except ImportError as e: assert "conda install dask-ml" in str(e) else: assert False else: from dask.ml.model_selection import GridSearchCV # noqa: F401
njunmt/encoders/rnn_encoder.py
whr94621/NJUNMT-tf
111
11123534
<reponame>whr94621/NJUNMT-tf # Copyright 2017 Natural Language Processing Group, Nanjing University, <EMAIL>. # # 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. """ Define RNN-based encoders. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import tensorflow as tf from njunmt.encoders.encoder import Encoder from njunmt.utils.rnn_cell_utils import get_multilayer_rnn_cells class StackBidirectionalRNNEncoder(Encoder): """ Define stacked bidirectional RNN encoder. """ def __init__(self, params, mode, name=None, verbose=True): """ Initializes the parameters of the encoder. Args: params: A dictionary of parameters to construct the encoder architecture. mode: A mode. name: The name of this encoder. verbose: Print encoder parameters if set True. """ super(StackBidirectionalRNNEncoder, self).__init__(params, mode, name, verbose) self._cells_fw = get_multilayer_rnn_cells(**self.params['rnn_cell']) self._cells_bw = get_multilayer_rnn_cells(**self.params['rnn_cell']) @staticmethod def default_params(): """ Returns a dictionary of default parameters of this encoder. """ return { "rnn_cell": { "cell_class": "LSTMCell", "cell_params": {}, "dropout_input_keep_prob": 1.0, "dropout_state_keep_prob": 1.0, "num_layers": 1 } } def encode(self, features, feature_length, **kwargs): """ Encodes the inputs via a stacked bi-directional RNN. Args: features: A Tensor, [batch_size, max_features_length, dim]. feature_length: A Tensor, [batch_size, ]. **kwargs: Returns: An instance of `collections.namedtuple`. """ scope = self.name if "scope" in kwargs: scope = kwargs.pop("scope") # outputs: [batch_size, max_time, layers_output] # layers_output = size_of_fw + size_of_bw # the returned states: # `tuple` type which has only one item, because we use MultiRNN cell for multiple cells outputs, states_fw, states_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn( cells_fw=[self._cells_fw], cells_bw=[self._cells_bw], inputs=features, sequence_length=feature_length, dtype=tf.float32, scope=scope, **kwargs) # because we use MultiRNNCell, unpack the top tuple structure states_fw = states_fw[0] states_bw = states_bw[0] return self._encoder_output_tuple_type( outputs=outputs, final_states={ "forward": states_fw[-1], "backward": states_bw[-1]}, attention_values=outputs, attention_length=feature_length) class UnidirectionalRNNEncoder(Encoder): """ Define a unidirectional RNN encoder. """ def __init__(self, params, mode, name=None, verbose=True): """ Initializes the parameters of the encoder. Args: params: A dictionary of parameters to construct the encoder architecture. mode: A mode. name: The name of this encoder. verbose: Print encoder parameters if set True. """ super(UnidirectionalRNNEncoder, self).__init__(params, mode, name, verbose) self._cells_fw = get_multilayer_rnn_cells(**self.params['rnn_cell']) @staticmethod def default_params(): """ Returns a dictionary of default parameters of this encoder. """ return { "rnn_cell": { "cell_class": "LSTMCell", "cell_params": {}, "dropout_input_keep_prob": 1.0, "dropout_state_keep_prob": 1.0, "num_layers": 1 } } def encode(self, features, feature_length, **kwargs): """ Encodes the inputs. Args: features: A Tensor, [batch_size, max_features_length, dim]. feature_length: A Tensor, [batch_size, ]. **kwargs: Returns: An instance of `collections.namedtuple`. """ scope = self.name if "scope" in kwargs: scope = kwargs.pop("scope") # outputs: [batch_size, max_time, num_units_of_hidden] outputs, states = tf.nn.dynamic_rnn( cell=self._cells_fw, inputs=features, sequence_length=feature_length, dtype=tf.float32, scope=scope, **kwargs) return self._encoder_output_tuple_type( outputs=outputs, final_statest=states[-1], attention_values=outputs, attention_length=feature_length) class BiUnidirectionalRNNEncoder(Encoder): """ Define a unidirectional RNN encoder. """ def __init__(self, params, mode, name=None, verbose=True): """ Initializes the parameters of the encoder. Args: params: A dictionary of parameters to construct the encoder architecture. mode: A mode. name: The name of this encoder. verbose: Print encoder parameters if set True. """ super(BiUnidirectionalRNNEncoder, self).__init__(params, mode, name, verbose) rnn_cell_params = copy.deepcopy(self.params["rnn_cell"]) rnn_cell_params["num_layers"] = 1 self._cells_fw = get_multilayer_rnn_cells(**rnn_cell_params) self._cells_bw = get_multilayer_rnn_cells(**rnn_cell_params) if self.params["rnn_cell"]["num_layers"] > 1: rnn_cell_params["num_layers"] = self.params["rnn_cell"]["num_layers"]-1 self._cells = get_multilayer_rnn_cells(**rnn_cell_params) @staticmethod def default_params(): """ Returns a dictionary of default parameters of this encoder. """ return { "rnn_cell": { "cell_class": "LSTMCell", "cell_params": {}, "dropout_input_keep_prob": 1.0, "dropout_state_keep_prob": 1.0, "num_layers": 2 } } def encode(self, features, feature_length, **kwargs): """ Encodes the inputs. Args: features: A Tensor, [batch_size, max_features_length, dim]. feature_length: A Tensor, [batch_size, ]. **kwargs: Returns: An instance of `collections.namedtuple`. """ scope = self.name if "scope" in kwargs: scope = kwargs.pop("scope") # outputs: [batch_size, max_features_length, hidden_size * 2] outputs, states_fw, states_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn( cells_fw=[self._cells_fw], cells_bw=[self._cells_bw], inputs=features, sequence_length=feature_length, dtype=tf.float32, scope=scope, **kwargs) final_states = {"forward": states_fw[-1], "backward": states_bw[-1]} if self.params["rnn_cell"]["num_layers"] > 1: # outputs: [batch_size, max_time, num_units_of_hidden] outputs, states = tf.nn.dynamic_rnn( cell=self._cells, inputs=outputs, sequence_length=feature_length, dtype=tf.float32, scope=scope, **kwargs) final_states = states[-1] return self._encoder_output_tuple_type( outputs=outputs, final_states=final_states, attention_values=outputs, attention_length=feature_length)
pypower/int2ext.py
Bengt/PYPOWER
221
11123572
<gh_stars>100-1000 # Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Converts internal to external bus numbering. """ import sys from warnings import warn from copy import deepcopy from pypower.idx_bus import BUS_I from pypower.idx_gen import GEN_BUS from pypower.idx_brch import F_BUS, T_BUS from pypower.idx_area import PRICE_REF_BUS from pypower.run_userfcn import run_userfcn from pypower.i2e_field import i2e_field from pypower.i2e_data import i2e_data def int2ext(ppc, val_or_field=None, oldval=None, ordering=None, dim=0): """Converts internal to external bus numbering. C{ppc = int2ext(ppc)} If the input is a single PYPOWER case dict, then it restores all buses, generators and branches that were removed because of being isolated or off-line, and reverts to the original generator ordering and original bus numbering. This requires that the 'order' key created by L{ext2int} be in place. Example:: ppc = int2ext(ppc) @see: L{ext2int}, L{i2e_field}, L{i2e_data} @author: <NAME> (PSERC Cornell) """ ppc = deepcopy(ppc) if val_or_field is None: # nargin == 1 if 'order' not in ppc: sys.stderr.write('int2ext: ppc does not have the "order" field ' 'required for conversion back to external numbering.\n') o = ppc["order"] if o["state"] == 'i': ## execute userfcn callbacks for 'int2ext' stage if 'userfcn' in ppc: ppc = run_userfcn(ppc["userfcn"], 'int2ext', ppc) ## save data matrices with internal ordering & restore originals o["int"] = {} o["int"]["bus"] = ppc["bus"].copy() o["int"]["branch"] = ppc["branch"].copy() o["int"]["gen"] = ppc["gen"].copy() ppc["bus"] = o["ext"]["bus"].copy() ppc["branch"] = o["ext"]["branch"].copy() ppc["gen"] = o["ext"]["gen"].copy() if 'gencost' in ppc: o["int"]["gencost"] = ppc["gencost"].copy() ppc["gencost"] = o["ext"]["gencost"].copy() if 'areas' in ppc: o["int"]["areas"] = ppc["areas"].copy() ppc["areas"] = o["ext"]["areas"].copy() if 'A' in ppc: o["int"]["A"] = ppc["A"].copy() ppc["A"] = o["ext"]["A"].copy() if 'N' in ppc: o["int"]["N"] = ppc["N"].copy() ppc["N"] = o["ext"]["N"].copy() ## update data (in bus, branch and gen only) ppc["bus"][o["bus"]["status"]["on"], :] = \ o["int"]["bus"] ppc["branch"][o["branch"]["status"]["on"], :] = \ o["int"]["branch"] ppc["gen"][o["gen"]["status"]["on"], :] = \ o["int"]["gen"][o["gen"]["i2e"], :] if 'areas' in ppc: ppc["areas"][o["areas"]["status"]["on"], :] = \ o["int"]["areas"] ## revert to original bus numbers ppc["bus"][o["bus"]["status"]["on"], BUS_I] = \ o["bus"]["i2e"] \ [ ppc["bus"][o["bus"]["status"]["on"], BUS_I].astype(int) ] ppc["branch"][o["branch"]["status"]["on"], F_BUS] = \ o["bus"]["i2e"][ ppc["branch"] \ [o["branch"]["status"]["on"], F_BUS].astype(int) ] ppc["branch"][o["branch"]["status"]["on"], T_BUS] = \ o["bus"]["i2e"][ ppc["branch"] \ [o["branch"]["status"]["on"], T_BUS].astype(int) ] ppc["gen"][o["gen"]["status"]["on"], GEN_BUS] = \ o["bus"]["i2e"][ ppc["gen"] \ [o["gen"]["status"]["on"], GEN_BUS].astype(int) ] if 'areas' in ppc: ppc["areas"][o["areas"]["status"]["on"], PRICE_REF_BUS] = \ o["bus"]["i2e"][ ppc["areas"] \ [o["areas"]["status"]["on"], PRICE_REF_BUS].astype(int) ] if 'ext' in o: del o['ext'] o["state"] = 'e' ppc["order"] = o else: sys.stderr.write('int2ext: ppc claims it is already using ' 'external numbering.\n') else: ## convert extra data if isinstance(val_or_field, str) or isinstance(val_or_field, list): ## field (key) warn('Calls of the form MPC = INT2EXT(MPC, ''FIELD_NAME'', ...) have been deprecated. Please replace INT2EXT with I2E_FIELD.') bus, gen = val_or_field, oldval if ordering is not None: dim = ordering ppc = i2e_field(ppc, bus, gen, dim) else: ## value warn('Calls of the form VAL = INT2EXT(MPC, VAL, ...) have been deprecated. Please replace INT2EXT with I2E_DATA.') bus, gen, branch = val_or_field, oldval, ordering ppc = i2e_data(ppc, bus, gen, branch, dim) return ppc def int2ext1(i2e, bus, gen, branch, areas): """Converts from the consecutive internal bus numbers back to the originals using the mapping provided by the I2E vector returned from C{ext2int}. @see: L{ext2int} @see: U{http://www.pserc.cornell.edu/matpower/} """ bus[:, BUS_I] = i2e[ bus[:, BUS_I].astype(int) ] gen[:, GEN_BUS] = i2e[ gen[:, GEN_BUS].astype(int) ] branch[:, F_BUS] = i2e[ branch[:, F_BUS].astype(int) ] branch[:, T_BUS] = i2e[ branch[:, T_BUS].astype(int) ] if areas != None and len(areas) > 0: areas[:, PRICE_REF_BUS] = i2e[ areas[:, PRICE_REF_BUS].astype(int) ] return bus, gen, branch, areas return bus, gen, branch
mongodb/mongodb_consistent_backup/official/mongodb_consistent_backup/Common/__init__.py
smthkissinger/docker-images
282
11123586
from Config import Config, parse_config_bool # NOQA from DB import DB, parse_read_pref_tags # NOQA from LocalCommand import LocalCommand # NOQA from Lock import Lock # NOQA from MongoUri import MongoUri # NOQA from Timer import Timer # NOQA from Util import config_to_string, is_datetime, parse_method, validate_hostname, wait_popen # NOQA
search/show_search_results.py
dongan-beta/PyRetri
1,063
11123622
# -*- coding: utf-8 -*- import os import argparse import json import codecs from utils.misc import save_to_csv, filter_by_keywords def parse_args(): parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval') parser.add_argument('opts', default=None, nargs=argparse.REMAINDER) parser.add_argument('--results_json_path', '-r', default=None, type=str, help="path of the result json") args = parser.parse_args() return args def show_results(results): for i in range(len(results)): print(results[i]) def main(): # init args args = parse_args() assert os.path.exists(args.results_json_path), 'the config file must be existed!' with open(args.results_json_path, "r") as f: results = json.load(f) # save the search results in a csv format file. csv_path = '/home/songrenjie/projects/RetrievalToolBox/test.csv' save_to_csv(results, csv_path) # define the keywords to be selected keywords = { 'data_name': ['market'], 'pre_process_name': list(), 'model_name': list(), 'feature_map_name': list(), 'aggregator_name': list(), 'post_process_name': ['no_fea_process', 'l2_normalize', 'pca_whiten', 'pca_wo_whiten'], } # show search results according to the given keywords results = filter_by_keywords(results, keywords) show_results(results) if __name__ == '__main__': main()
alibi_detect/cd/tests/test_mmd_online.py
sugatoray/alibi-detect
1,227
11123630
import numpy as np import pytest from alibi_detect.cd import MMDDriftOnline from alibi_detect.cd.pytorch.mmd_online import MMDDriftOnlineTorch from alibi_detect.cd.tensorflow.mmd_online import MMDDriftOnlineTF n, n_features = 100, 5 tests_mmddriftonline = ['tensorflow', 'pytorch', 'PyToRcH', 'mxnet'] n_tests = len(tests_mmddriftonline) @pytest.fixture def mmddriftonline_params(request): return tests_mmddriftonline[request.param] @pytest.mark.parametrize('mmddriftonline_params', list(range(n_tests)), indirect=True) def test_mmddriftonline(mmddriftonline_params): backend = mmddriftonline_params x_ref = np.random.randn(*(n, n_features)) # Instantiate and check detector class try: cd = MMDDriftOnline(x_ref=x_ref, ert=25, window_size=5, backend=backend, n_bootstraps=100) except NotImplementedError: cd = None if backend.lower() == 'pytorch': assert isinstance(cd._detector, MMDDriftOnlineTorch) elif backend.lower() == 'tensorflow': assert isinstance(cd._detector, MMDDriftOnlineTF) else: assert cd is None return # Test predict x_t = np.random.randn(n_features) t0 = cd.t cd.predict(x_t) assert cd.t - t0 == 1 # This checks state updated (self.t at least) # Test score t0 = cd.t cd.score(x_t) assert cd.t - t0 == 1
test/test_oneview_ethernet_network_facts.py
nabhajit-ray/oneview-ansible
108
11123673
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2019) Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ### import pytest from mock import mock from hpe_test_utils import OneViewBaseFactsTest from oneview_module_loader import EthernetNetworkFactsModule ERROR_MSG = 'Fake message error' PARAMS_GET_ALL = dict( config='config.json', name=None ) PARAMS_GET_BY_NAME = dict( config='config.json', name="Test Ethernet Network", options=[] ) PARAMS_GET_BY_NAME_WITH_OPTIONS = dict( config='config.json', name="Test Ethernet Network", options=['associatedProfiles', 'associatedUplinkGroups'] ) PRESENT_ENETS = [{ "name": "Test Ethernet Network", "uri": "/rest/ethernet-networks/d34dcf5e-0d8e-441c-b00d-e1dd6a067188" }] ENET_ASSOCIATED_UPLINK_GROUP_URIS = [ "/rest/uplink-sets/c6bf9af9-48e7-4236-b08a-77684dc258a5", "/rest/uplink-sets/e2f0031b-52bd-4223-9ac1-d91cb519d548" ] ENET_ASSOCIATED_PROFILE_URIS = [ "/rest/server-profiles/83e2e117-59dc-4e33-9f24-462af951cbbe", "/rest/server-profiles/57d3af2a-b6d2-4446-8645-f38dd808ea4d" ] ENET_ASSOCIATED_UPLINK_GROUPS = [dict(uri=ENET_ASSOCIATED_UPLINK_GROUP_URIS[0], name='Uplink Set 1'), dict(uri=ENET_ASSOCIATED_UPLINK_GROUP_URIS[1], name='Uplink Set 2')] ENET_ASSOCIATED_PROFILES = [dict(uri=ENET_ASSOCIATED_PROFILE_URIS[0], name='Server Profile 1'), dict(uri=ENET_ASSOCIATED_PROFILE_URIS[1], name='Server Profile 2')] @pytest.mark.resource(TestEthernetNetworkFactsModule='ethernet_networks') class TestEthernetNetworkFactsModule(OneViewBaseFactsTest): def test_should_get_all_enets(self): self.resource.get_all.return_value = PRESENT_ENETS self.mock_ansible_module.params = PARAMS_GET_ALL EthernetNetworkFactsModule().run() self.mock_ansible_module.exit_json.assert_called_once_with( changed=False, ansible_facts=dict(ethernet_networks=(PRESENT_ENETS)) ) def test_should_get_enet_by_name(self): self.resource.data = PRESENT_ENETS self.mock_ansible_module.params = PARAMS_GET_BY_NAME EthernetNetworkFactsModule().run() self.mock_ansible_module.exit_json.assert_called_once_with( changed=False, ansible_facts=dict(ethernet_networks=(PRESENT_ENETS)) ) def test_should_get_enet_by_name_with_options(self): self.resource.data = PRESENT_ENETS self.resource.get_associated_profiles.return_value = ENET_ASSOCIATED_PROFILE_URIS self.resource.get_associated_uplink_groups.return_value = ENET_ASSOCIATED_UPLINK_GROUP_URIS profiles = [] for data in ENET_ASSOCIATED_PROFILES: obj = mock.Mock() obj.data = data profiles.append(obj) uplinks = [] for data in ENET_ASSOCIATED_UPLINK_GROUPS: obj = mock.Mock() obj.data = data uplinks.append(obj) self.mock_ov_client.server_profiles.get_by_uri.side_effect = profiles self.mock_ov_client.uplink_sets.get_by_uri.side_effect = uplinks self.mock_ansible_module.params = PARAMS_GET_BY_NAME_WITH_OPTIONS EthernetNetworkFactsModule().run() self.mock_ansible_module.exit_json.assert_called_once_with( changed=False, ansible_facts=dict(ethernet_networks=PRESENT_ENETS, enet_associated_profiles=ENET_ASSOCIATED_PROFILES, enet_associated_uplink_groups=ENET_ASSOCIATED_UPLINK_GROUPS) ) if __name__ == '__main__': pytest.main([__file__])
solutions/problem_114.py
ksvr444/daily-coding-problem
1,921
11123720
<reponame>ksvr444/daily-coding-problem<gh_stars>1000+ def reverse_words(string, delimiters): words = list() delims = list() delim_positions = list() # stores positions of the delimiters seen start = 0 i = 0 while i < len(string): char = string[i] if char in delimiters: word = string[start:i] if i - start > 1: words.append(word) delims.append(char) delim_positions.append(len(words) + len(delims) - 1) start = i + 1 i += 1 # get last word if present if i - start > 1: words.append(string[start:i]) words.reverse() # reverse just the words reversed_order = list() word_index = 0 delim_index = 0 # merging the reversed words and the delimiters for i in range(len(words) + len(delims)): if delim_index < len(delim_positions) and delim_positions[delim_index] == i: # insert next delimiter if the position is saved for a delimiter reversed_order.append(delims[delim_index]) delim_index += 1 else: reversed_order.append(words[word_index]) word_index += 1 reversed_string = "".join(reversed_order) return reversed_string assert reverse_words("hello/world:here/", set([':', '/'])) == "here/world:hello/" assert reverse_words(":hello//world:here/", set([':', '/'])) == ":here//world:hello/" assert reverse_words("hello//world:here", set([':', '/'])) == "here//world:hello" assert reverse_words("hello/world:here", set([':', '/'])) == "here/world:hello"
tools/benchmark.py
Genevievekim/semantic-segmentation-1
196
11123766
<reponame>Genevievekim/semantic-segmentation-1 import torch import argparse import time from fvcore.nn import flop_count_table, FlopCountAnalysis import sys sys.path.insert(0, '.') from semseg.models import * def main( model_name: str, backbone_name: str, image_size: list, num_classes: int, device: str, ): device = torch.device('cuda' if torch.cuda.is_available() and device == 'cuda' else 'cpu') inputs = torch.randn(1, 3, *image_size).to(device) model = eval(model_name)(backbone_name, num_classes) model = model.to(device) model.eval() print(flop_count_table(FlopCountAnalysis(model, inputs))) total_time = 0.0 for _ in range(10): tic = time.perf_counter() model(inputs) toc = time.perf_counter() total_time += toc - tic total_time /= 10 print(f"Inference time: {total_time*1000:.2f}ms") print(f"FPS: {1/total_time}") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model-name', type=str, default='SegFormer') parser.add_argument('--backbone-name', type=str, default='MiT-B0') parser.add_argument('--image-size', type=list, default=[512, 512]) parser.add_argument('--num-classes', type=int, default=11) parser.add_argument('--device', type=str, default='cuda') args = parser.parse_args() main(args.model_name, args.backbone_name, args.image_size, args.num_classes, args.device)
uecli/CMakeCustomFlags.py
MonsterClosetGames/ue4cli
179
11123775
<reponame>MonsterClosetGames/ue4cli import os # The list of include directory substrings that trigger custom CMake flags CUSTOM_FLAGS_FOR_INCLUDE_DIRS = { 'libPNG-': 'PNG_PNG_INCLUDE_DIR' } # The list of library files that trigger custom CMake flags CUSTOM_FLAGS_FOR_LIBS = { 'png': 'PNG_LIBRARY', 'z': 'ZLIB_LIBRARY', 'z_fPIC': 'ZLIB_LIBRARY', 'zlibstatic': 'ZLIB_LIBRARY' } class CMakeCustomFlags(object): @staticmethod def processLibraryDetails(details): """ Processes the supplied ThirdPartyLibraryDetails instance and sets any custom CMake flags """ # If the header include directories list contains any directories we have flags for, add them for includeDir in details.includeDirs: # If the directory path matches any of the substrings in our list, generate the relevant flags for pattern in CUSTOM_FLAGS_FOR_INCLUDE_DIRS: if pattern in includeDir: flag = '-D' + CUSTOM_FLAGS_FOR_INCLUDE_DIRS[pattern] + '=' + includeDir details.cmakeFlags.append(flag) # If the libraries list contains any libs we have flags for, add them for lib in details.libs: # Extract the name of the library from the filename # (We remove any "lib" prefix or numerical suffix) filename = os.path.basename(lib) (name, ext) = os.path.splitext(filename) libName = name.replace('lib', '') if name.startswith('lib') else name libName = libName.rstrip('_-1234567890') # If the library name matches one in our list, generate its flag if libName in CUSTOM_FLAGS_FOR_LIBS: flag = '-D' + CUSTOM_FLAGS_FOR_LIBS[libName] + '=' + lib details.cmakeFlags.append(flag)
houdini/handlers/play/card.py
Oblivion-Max/houdini
444
11123793
import random from houdini import handlers from houdini.data.ninja import CardCollection, CardStarterDeck, PenguinCardCollection from houdini.handlers import Priority, XMLPacket, XTPacket @handlers.boot async def cards_load(server): server.cards = await CardCollection.get_collection() server.logger.info(f'Loaded {len(server.cards)} ninja cards') starter_deck_cards = await CardStarterDeck.query.gino.all() server.cards.set_starter_decks(starter_deck_cards) server.logger.info(f'Loaded {len(server.cards.starter_decks)} starter decks') @handlers.handler(XMLPacket('login'), priority=Priority.Low) @handlers.allow_once async def load_card_inventory(p): p.cards = await PenguinCardCollection.get_collection(p.id) @handlers.handler(XTPacket('i', 'ai')) async def handle_buy_starter_deck(p, deck_id: int): if deck_id in p.server.cards.starter_decks: starter_deck = p.server.cards.starter_decks[deck_id] power_cards = [card for card, qty in starter_deck if card.power_id > 0] for card, qty in starter_deck: if card.power_id == 0: await p.add_card(card, quantity=qty) power_card = random.choice(power_cards) await p.add_card(power_card, quantity=1) @handlers.handler(XTPacket('cd', 'gcd')) async def handle_get_card_data(p): await p.send_xt('gcd', '|'.join(f'{card.card_id},{card.quantity},{card.member_quantity}' for card in p.cards.values())) @handlers.handler(XTPacket('cd', 'bpc')) async def handle_buy_power_cards(p): if p.coins >= 1500: power_cards = random.sample(p.server.cards.power_cards, 3) for card in power_cards: await p.add_card(card, member_quantity=1) await p.update(coins=p.coins - 1500).apply() await p.send_xt('bpc', ','.join([str(card.id) for card in power_cards]), p.coins) else: await p.send_xt('bpc', 401)
autoPyTorch/pipeline/nodes/one_hot_encoding.py
mens-artis/Auto-PyTorch
1,657
11123799
<filename>autoPyTorch/pipeline/nodes/one_hot_encoding.py __author__ = "<NAME>, <NAME> and <NAME>" __version__ = "0.0.1" __license__ = "BSD" from autoPyTorch.pipeline.base.pipeline_node import PipelineNode from autoPyTorch.utils.config.config_option import ConfigOption, to_bool from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer import numpy as np import scipy.sparse class OneHotEncoding(PipelineNode): def __init__(self): super(OneHotEncoding, self).__init__() self.encode_Y = False def fit(self, pipeline_config, X, Y, dataset_info): categorical_features = dataset_info.categorical_features ohe = OneHotEncoder(categories="auto", sparse=False, handle_unknown="ignore") encoder = ColumnTransformer(transformers=[("ohe", ohe, [i for i, f in enumerate(categorical_features) if f])], remainder="passthrough") encoder.categories_ = np.array([]) encoder.categorical_features = categorical_features if any(categorical_features) and not dataset_info.is_sparse: # encode X X = encoder.fit_transform(X) encoder.categories_ = encoder.transformers_[0][1].categories_ # Y to matrix Y, y_encoder = self.complete_y_tranformation(Y) dataset_info.categorical_features = None return {'X': X, 'one_hot_encoder': encoder, 'Y': Y, 'y_one_hot_encoder': y_encoder, 'dataset_info': dataset_info} def predict(self, pipeline_config, X, one_hot_encoder): categorical_features = pipeline_config["categorical_features"] if categorical_features and any(categorical_features) and not scipy.sparse.issparse(X): X = one_hot_encoder.transform(X) return {'X': X, 'one_hot_encoder': one_hot_encoder} def reverse_transform_y(self, Y, y_one_hot_encoder): if y_one_hot_encoder is None: return Y return y_one_hot_encoder.categories_[0][np.argmax(Y, axis=1)].reshape(-1, 1) def transform_y(self, Y, y_one_hot_encoder): if y_one_hot_encoder is None: return Y return y_one_hot_encoder.transform(Y.reshape(-1, 1)) def complete_y_tranformation(self, Y): # Y to matrix y_encoder = None Y = Y.astype(np.float32) if len(Y.shape) == 1: Y = Y.reshape(-1, 1) # encode Y if self.encode_Y: y_encoder = OneHotEncoder(sparse=False, categories="auto", handle_unknown='ignore') y_encoder.categories_ = np.array([]) Y = y_encoder.fit_transform(Y) return Y, y_encoder
src/maestral/utils/caches.py
gliptak/maestral
436
11123803
"""Module containing cache implementations.""" from collections import OrderedDict from threading import RLock from typing import Any class LRUCache: """A simple LRU cache implementation :param capacity: Maximum number of entries to keep. """ _cache: OrderedDict def __init__(self, capacity: int) -> None: self._lock = RLock() self._cache = OrderedDict() self.capacity = capacity def get(self, key: Any) -> Any: """ Get the cached value for a key. Mark as most recently used. :param key: Key to query. :returns: Cached value or None. """ with self._lock: try: self._cache.move_to_end(key) return self._cache[key] except KeyError: return None def put(self, key: Any, value: Any) -> None: """ Set the cached value for a key. Mark as most recently used. :param key: Key to use. Must be hashable. :param value: Value to cache. """ with self._lock: self._cache[key] = value self._cache.move_to_end(key) if len(self._cache) > self.capacity: self._cache.popitem(last=False) def clear(self) -> None: """ Clears the cache. """ with self._lock: self._cache.clear()
examples/tutorials/05_async_python/02_cube_blinker.py
rootless4real/cozmo-python-sdk
794
11123830
<filename>examples/tutorials/05_async_python/02_cube_blinker.py #!/usr/bin/env python3 # Copyright (c) 2016 Anki, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the file LICENSE.txt or 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. '''Cube Blinker asynchronous example Cozmo first looks around for a cube. Once a cube is found, the cube's lights blink green in a circular fashion. The script then waits for the cube to be tapped. ''' import asyncio import sys import cozmo class BlinkyCube(cozmo.objects.LightCube): '''Subclass LightCube and add a light-chaser effect.''' def __init__(self, *a, **kw): super().__init__(*a, **kw) self._chaser = None def start_light_chaser(self): '''Cycles the lights around the cube with 1 corner lit up green, changing to the next corner every 0.1 seconds. ''' if self._chaser: raise ValueError("Light chaser already running") async def _chaser(): while True: for i in range(4): cols = [cozmo.lights.off_light] * 4 cols[i] = cozmo.lights.green_light self.set_light_corners(*cols) await asyncio.sleep(0.1, loop=self._loop) self._chaser = asyncio.ensure_future(_chaser(), loop=self._loop) def stop_light_chaser(self): if self._chaser: self._chaser.cancel() self._chaser = None # Make sure World knows how to instantiate the subclass cozmo.world.World.light_cube_factory = BlinkyCube async def cozmo_program(robot: cozmo.robot.Robot): '''The async equivalent of 01_cube_blinker_sync. The usage of ``async def`` makes the cozmo_program method a coroutine. Within a coroutine, ``await`` can be used. With ``await``, the statement blocks until the request being waited for has completed. Meanwhile the event loop continues in the background. For instance, the statement ``await robot.world.wait_for_observed_light_cube(timeout=60)`` blocks until Cozmo discovers a light cube or the 60 second timeout elapses, whichever occurs first. Likewise, the statement ``await cube.wait_for_tap(timeout=10)`` blocks until the tap event is received or the 10 second timeout occurs, whichever occurs first. For more information, see https://docs.python.org/3/library/asyncio-task.html ''' cube = None look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace) try: cube = await robot.world.wait_for_observed_light_cube(timeout=60) except asyncio.TimeoutError: print("Didn't find a cube :-(") return finally: look_around.stop() cube.start_light_chaser() try: print("Waiting for cube to be tapped") await cube.wait_for_tap(timeout=10) print("Cube tapped") except asyncio.TimeoutError: print("No-one tapped our cube :-(") finally: cube.stop_light_chaser() cube.set_lights_off() cozmo.run_program(cozmo_program)
openff/toolkit/utils/ambertools_wrapper.py
andrew-abimansour/openff-toolkit
120
11123868
""" Wrapper class providing a minimal consistent interface to `AmberTools <http://ambermd.org/AmberTools.php>`_. """ __all__ = ("AmberToolsToolkitWrapper",) # ============================================================================================= # IMPORTS # ============================================================================================= import subprocess import tempfile from collections import defaultdict from distutils.spawn import find_executable import numpy as np try: from openmm import unit except ImportError: from simtk import unit from openff.toolkit.utils import base_wrapper, rdkit_wrapper from openff.toolkit.utils.exceptions import ( AntechamberNotFoundError, ChargeCalculationError, ChargeMethodUnavailableError, ToolkitUnavailableException, ) from openff.toolkit.utils.utils import temporary_cd # ============================================================================================= # IMPLEMENTATION # ============================================================================================= class AmberToolsToolkitWrapper(base_wrapper.ToolkitWrapper): """ AmberTools toolkit wrapper .. warning :: This API is experimental and subject to change. """ _toolkit_name = "AmberTools" _toolkit_installation_instructions = ( "The AmberTools toolkit (free and open source) can be found at " "https://anaconda.org/conda-forge/ambertools" ) def __init__(self): super().__init__() self._toolkit_file_read_formats = [] self._toolkit_file_write_formats = [] if not self.is_available(): raise ToolkitUnavailableException( f"The required toolkit {self._toolkit_name} is not " f"available. {self._toolkit_installation_instructions}" ) # TODO: More reliable way to extract AmberTools version out = subprocess.check_output(["antechamber", "-L"]) ambertools_version = out.decode("utf-8").split("\n")[1].split()[3].strip(":") self._toolkit_version = ambertools_version # TODO: Find AMBERHOME or executable home, checking miniconda if needed # Store an instance of an RDKitToolkitWrapper for file I/O self._rdkit_toolkit_wrapper = rdkit_wrapper.RDKitToolkitWrapper() @staticmethod def is_available(): """ Check whether the AmberTools toolkit is installed Returns ------- is_installed : bool True if AmberTools is installed, False otherwise. """ # TODO: Check all tools needed # TODO: How should we implement find_executable? ANTECHAMBER_PATH = find_executable("antechamber") if ANTECHAMBER_PATH is None: return False # AmberToolsToolkitWrapper needs RDKit to do basically anything, since its interface requires SDF I/O if not (rdkit_wrapper.RDKitToolkitWrapper.is_available()): return False return True def assign_partial_charges( self, molecule, partial_charge_method=None, use_conformers=None, strict_n_conformers=False, normalize_partial_charges=True, _cls=None, ): """ Compute partial charges with AmberTools using antechamber/sqm, and assign the new values to the partial_charges attribute. .. warning :: This API experimental and subject to change. .. todo :: * Do we want to also allow ESP/RESP charges? Parameters ---------- molecule : openff.toolkit.topology.Molecule Molecule for which partial charges are to be computed partial_charge_method : str, optional, default=None The charge model to use. One of ['gasteiger', 'am1bcc', 'am1-mulliken']. If None, 'am1-mulliken' will be used. use_conformers : iterable of openmm.unit.Quantity-wrapped numpy arrays, each with shape (n_atoms, 3) and dimension of distance. Optional, default = None List of (n_atoms x 3) openmm.unit.Quantities to use for partial charge calculation. If None, an appropriate number of conformers will be generated. strict_n_conformers : bool, default=False Whether to raise an exception if an invalid number of conformers is provided for the given charge method. If this is False and an invalid number of conformers is found, a warning will be raised. normalize_partial_charges : bool, default=True Whether to offset partial charges so that they sum to the total formal charge of the molecule. This is used to prevent accumulation of rounding errors when the partial charge generation method has low precision. _cls : class Molecule constructor Raises ------ ChargeMethodUnavailableError if the requested charge method can not be handled by this toolkit ChargeCalculationError if the charge method is supported by this toolkit, but fails """ import os import subprocess from openff.toolkit.topology import Molecule if partial_charge_method is None: partial_charge_method = "am1-mulliken" else: # Standardize method name for string comparisons partial_charge_method = partial_charge_method.lower() SUPPORTED_CHARGE_METHODS = { "am1bcc": { "antechamber_keyword": "bcc", "min_confs": 1, "max_confs": 1, "rec_confs": 1, }, "am1-mulliken": { "antechamber_keyword": "mul", "min_confs": 1, "max_confs": 1, "rec_confs": 1, }, "gasteiger": { "antechamber_keyword": "gas", "min_confs": 0, "max_confs": 0, "rec_confs": 0, }, } if partial_charge_method not in SUPPORTED_CHARGE_METHODS: raise ChargeMethodUnavailableError( f"partial_charge_method '{partial_charge_method}' is not available from AmberToolsToolkitWrapper. " f"Available charge methods are {list(SUPPORTED_CHARGE_METHODS.keys())} " ) charge_method = SUPPORTED_CHARGE_METHODS[partial_charge_method] if _cls is None: _cls = Molecule # Make a temporary copy of the molecule, since we'll be messing with its conformers mol_copy = _cls(molecule) if use_conformers is None: if charge_method["rec_confs"] == 0: mol_copy._conformers = None else: mol_copy.generate_conformers( n_conformers=charge_method["rec_confs"], rms_cutoff=0.25 * unit.angstrom, toolkit_registry=rdkit_wrapper.RDKitToolkitWrapper(), ) # TODO: What's a "best practice" RMS cutoff to use here? else: mol_copy._conformers = None for conformer in use_conformers: mol_copy._add_conformer(conformer) self._check_n_conformers( mol_copy, partial_charge_method=partial_charge_method, min_confs=charge_method["min_confs"], max_confs=charge_method["max_confs"], strict_n_conformers=strict_n_conformers, ) # Find the path to antechamber # TODO: How should we implement find_executable? ANTECHAMBER_PATH = find_executable("antechamber") if ANTECHAMBER_PATH is None: raise AntechamberNotFoundError( "Antechamber not found, cannot run charge_mol()" ) # Compute charges with tempfile.TemporaryDirectory() as tmpdir: with temporary_cd(tmpdir): net_charge = mol_copy.total_charge.value_in_unit(unit.elementary_charge) # Write out molecule in SDF format # TODO: How should we handle multiple conformers? self._rdkit_toolkit_wrapper.to_file( mol_copy, "molecule.sdf", file_format="sdf" ) # Compute desired charges # TODO: Add error handling if antechamber chokes short_charge_method = charge_method["antechamber_keyword"] subprocess.check_output( [ "antechamber", "-i", "molecule.sdf", "-fi", "sdf", "-o", "charged.mol2", "-fo", "mol2", "-pf", "yes", "-dr", "n", "-c", short_charge_method, "-nc", str(net_charge), ] ) # Write out just charges subprocess.check_output( [ "antechamber", "-dr", "n", "-i", "charged.mol2", "-fi", "mol2", "-o", "charges2.mol2", "-fo", "mol2", "-c", "wc", "-cf", "charges.txt", "-pf", "yes", ] ) # Check to ensure charges were actually produced if not os.path.exists("charges.txt"): # TODO: copy files into local directory to aid debugging? raise ChargeCalculationError( "Antechamber/sqm partial charge calculation failed on " "molecule {} (SMILES {})".format( molecule.name, molecule.to_smiles() ) ) # Read the charges with open("charges.txt", "r") as infile: contents = infile.read() text_charges = contents.split() charges = np.zeros([molecule.n_atoms], np.float64) for index, token in enumerate(text_charges): charges[index] = float(token) # TODO: Ensure that the atoms in charged.mol2 are in the same order as in molecule.sdf charges = unit.Quantity(charges, unit.elementary_charge) molecule.partial_charges = charges if normalize_partial_charges: molecule._normalize_partial_charges() def compute_partial_charges_am1bcc( self, molecule, use_conformers=None, strict_n_conformers=False ): """ Compute partial charges with AmberTools using antechamber/sqm. This will calculate AM1-BCC charges on the first conformer only. .. warning :: This API is experimental and subject to change. Parameters ---------- molecule : Molecule Molecule for which partial charges are to be computed use_conformers : iterable of openmm.unit.Quantity-wrapped numpy arrays, each with shape (n_atoms, 3) and dimension of distance. Optional, default = None Coordinates to use for partial charge calculation. If None, an appropriate number of conformers will be generated. strict_n_conformers : bool, default=False Whether to raise an exception if an invalid number of conformers is provided. If this is False and an invalid number of conformers is found, a warning will be raised instead of an Exception. Returns ------- charges : numpy.array of shape (natoms) of type float The partial charges """ import warnings warnings.warn( "compute_partial_charges_am1bcc will be deprecated in an upcoming release. " "Use assign_partial_charges(partial_charge_method='am1bcc') instead.", DeprecationWarning, ) self.assign_partial_charges( molecule, partial_charge_method="AM1BCC", use_conformers=use_conformers, strict_n_conformers=strict_n_conformers, ) return molecule.partial_charges def _modify_sqm_in_to_request_bond_orders(self, file_path): """ Modify a sqm.in file produced by antechamber to include the "printbondorders=1" directive in the header. This method will overwrite the original file. Parameters ---------- file_path : str The path to sqm.in """ data = open(file_path).read() # Original sqm.in file headerlooks like: # Run semi-empirical minimization # &qmmm # qm_theory='AM1', grms_tol=0.0005, # scfconv=1.d-10, ndiis_attempts=700, qmcharge=0, # / # ... (atom coordinates in something like XYZ format) ... # To get WBOs, we need to add "printbondorders=1" to the list of keywords # First, split the sqm.in text at the "/" mark at the end of the header datasp = data.split("/") # Insert the "printbondorders" directive in a new line and re-add the "/" datasp.insert(1, "printbondorders=1, \n /") # Reassemble the file text new_data = "".join(datasp) # Write the new file contents, overwriting the original file. with open(file_path, "w") as of: of.write(new_data) def _get_fractional_bond_orders_from_sqm_out( self, file_path, validate_elements=None ): """ Process a SQM output file containing bond orders, and return a dict of the form dict[atom_1_index, atom_2_index] = fractional_bond_order Parameters ---------- file_path : str File path for sqm output file validate_elements : iterable of str The element symbols expected in molecule index order. A ValueError will be raised if the elements are not found in this order. Returns ------- bond_orders : dict[(int, int)]: float A dictionary where the keys are tuples of two atom indices and the values are floating-point bond orders. The keys are sorted in ascending order, such that the lower atom index is key[0] and the higher is key[1]. """ # Example sqm.out section with WBOs: # Bond Orders # # QMMM: NUM1 ELEM1 NUM2 ELEM2 BOND_ORDER # QMMM: 2 C 1 C 1.41107532 # QMMM: 3 C 1 C 1.41047804 # ... # QMMM: 15 H 13 H 0.00000954 # QMMM: 15 H 14 H 0.00000813 # # --------- Calculation Completed ---------- data = open(file_path).read() begin_sep = """ Bond Orders QMMM: NUM1 ELEM1 NUM2 ELEM2 BOND_ORDER """ end_sep = """ --------- Calculation Completed ---------- """ # Extract the chunk of text between begin_sep and end_sep, and split it by newline fbo_lines = data.split(begin_sep)[1].split(end_sep)[0].split("\n") # Iterate over the lines and populate the dict to return bond_orders = dict() for line in fbo_lines: linesp = line.split() atom_index_1 = int(linesp[1]) atom_element_1 = linesp[2] atom_index_2 = int(linesp[3]) atom_element_2 = linesp[4] bond_order = float(linesp[5]) # If validate_elements was provided, ensure that the ordering of element symbols is what we expected if validate_elements is not None: if (atom_element_1 != validate_elements[atom_index_1 - 1]) or ( atom_element_2 != validate_elements[atom_index_2 - 1] ): # raise ValueError('\n'.join(fbo_lines)) raise ValueError( f"Elements or indexing in sqm output differ from expectation. " f"Expected {validate_elements[atom_index_1]} with index {atom_index_1} and " f"{validate_elements[atom_index_2]} with index {atom_index_2}, " f"but SQM output has {atom_element_1} and {atom_element_2} for the same atoms." ) # To make lookup easier, we identify bonds as integer tuples with the lowest atom index # first and the highest second. index_tuple = tuple(sorted([atom_index_1, atom_index_2])) bond_orders[index_tuple] = bond_order return bond_orders def assign_fractional_bond_orders( self, molecule, bond_order_model=None, use_conformers=None, _cls=None ): """ Update and store list of bond orders this molecule. Bond orders are stored on each bond, in the `bond.fractional_bond_order` attribute. .. warning :: This API is experimental and subject to change. Parameters ---------- molecule : openff.toolkit.topology.molecule Molecule The molecule to assign wiberg bond orders to bond_order_model : str, optional, default=None The charge model to use. Only allowed value is 'am1-wiberg'. If None, 'am1-wiberg' will be used. use_conformers : iterable of openmm.unit.Quantity(np.array) with shape (n_atoms, 3) and dimension of distance, optional, default=None The conformers to use for fractional bond order calculation. If None, an appropriate number of conformers will be generated by an available ToolkitWrapper. _cls : class Molecule constructor """ from openff.toolkit.topology import Molecule # Find the path to antechamber # TODO: How should we implement find_executable? ANTECHAMBER_PATH = find_executable("antechamber") if ANTECHAMBER_PATH is None: raise AntechamberNotFoundError( "Antechamber not found, cannot run " "AmberToolsToolkitWrapper.assign_fractional_bond_orders()" ) if _cls is None: _cls = Molecule # Make a copy since we'll be messing with this molecule's conformers temp_mol = _cls(molecule) if use_conformers is None: temp_mol.generate_conformers( n_conformers=1, toolkit_registry=self._rdkit_toolkit_wrapper, ) else: temp_mol._conformers = None for conformer in use_conformers: temp_mol._add_conformer(conformer) if len(temp_mol.conformers) == 0: raise ValueError( "No conformers present in molecule submitted for fractional bond order calculation. Consider " "loading the molecule from a file with geometry already present or running " "molecule.generate_conformers() before calling molecule.assign_fractional_bond_orders" ) # Compute bond orders bond_order_model_to_antechamber_keyword = {"am1-wiberg": "mul"} supported_bond_order_models = list( bond_order_model_to_antechamber_keyword.keys() ) if bond_order_model is None: bond_order_model = "am1-wiberg" bond_order_model = bond_order_model.lower() if bond_order_model not in supported_bond_order_models: raise ValueError( f"Bond order model '{bond_order_model}' is not supported by AmberToolsToolkitWrapper. " f"Supported models are {supported_bond_order_models}" ) ac_charge_keyword = bond_order_model_to_antechamber_keyword[bond_order_model] bond_orders = defaultdict(list) for conformer in [*temp_mol.conformers]: with tempfile.TemporaryDirectory() as tmpdir: with temporary_cd(tmpdir): net_charge = temp_mol.total_charge # Write out molecule in SDF format temp_mol._conformers = [conformer] self._rdkit_toolkit_wrapper.to_file( temp_mol, "molecule.sdf", file_format="sdf" ) # Prepare sqm.in file as if we were going to run charge calc # TODO: Add error handling if antechamber chokes subprocess.check_output( [ "antechamber", "-i", "molecule.sdf", "-fi", "sdf", "-o", "sqm.in", "-fo", "sqmcrt", "-pf", "yes", "-c", ac_charge_keyword, "-nc", str(net_charge), ] ) # Modify sqm.in to request bond order calculation self._modify_sqm_in_to_request_bond_orders("sqm.in") # Run sqm to get bond orders subprocess.check_output( ["sqm", "-i", "sqm.in", "-o", "sqm.out", "-O"] ) # Ensure that antechamber/sqm did not change the indexing by checking against # an ordered list of element symbols for this molecule expected_elements = [at.element.symbol for at in molecule.atoms] conformer_bond_orders = ( self._get_fractional_bond_orders_from_sqm_out( "sqm.out", validate_elements=expected_elements ) ) for bond_indices, value in conformer_bond_orders.items(): bond_orders[bond_indices].append(value) # Note that sqm calculate WBOs for ALL PAIRS of atoms, not just those that have # bonds defined in the original molecule. So here we iterate over the bonds in # the original molecule and only nab the WBOs for those. for bond in molecule.bonds: # The atom index tuples that act as bond indices are ordered from lowest to highest by # _get_fractional_bond_orders_from_sqm_out, so here we make sure that we look them up in # sorted order as well sorted_atom_indices = sorted( tuple([bond.atom1_index + 1, bond.atom2_index + 1]) ) bond.fractional_bond_order = np.mean( bond_orders[tuple(sorted_atom_indices)] )
xfdnn/rt/scripts/layerwise.py
yarenty/ml-suite
334
11123876
<filename>xfdnn/rt/scripts/layerwise.py<gh_stars>100-1000 #!/usr/bin/env python # # // SPDX-License-Identifier: BSD-3-CLAUSE # # (C) Copyright 2018, Xilinx, Inc. # import sys, os sys.path.append(os.environ['MLSUITE_ROOT'] + '/xfdnn/rt') import xdnn, xdnn_io import numpy as np import json, copy def generateLayerwiseJson(layername): #args = xdnn_io.processCommandLine() parser = xdnn_io.default_parser_args() parser.add_argument('--layerindex', type=int, default=0, help='Index value for layer in json', required=True) argvt = parser.parse_args() args = xdnn_io.make_dict_args(argvt) with open (args['netcfg'], 'r') as fp: data = json.load(fp) #print json.dumps(data, indent=2) # Get layers from json nodes = data['network'] #print "Total layers (nodes): ", len(nodes) reachedNode = False for node in nodes: if node['active'] == 0: continue #print "Active: ", node['active'], " ", node['name'] if reachedNode == False and node['name'] == layername: reachedNode = True elif reachedNode and node['name'] != layername: node['active'] = 0 fname = str(layername) + str('.json') fjson = fname.replace('/', '_') with open(fjson, 'w') as wfp: json.dump(data, wfp, indent=2, sort_keys=True) return fjson def networkForward(netcfg, layername): #args = xdnn_io.processCommandLine() parser = xdnn_io.default_parser_args() parser.add_argument('--layerindex', type=int, default=0, help='Index value for layer in json', required=True) argvt = parser.parse_args() args = xdnn_io.make_dict_args(argvt) args['netcfg'] = netcfg # Hardcode these parameters, so we only have to look at performance of 1 PE args["batch_sz"] = 1 args["PE"] = 0 #print "{:-^100}".format(' Before: createHandle ') ret, handles = xdnn.createHandle(args['xclbin'], "kernelSxdnn_0") #print "{:-^100}".format(' After: createHandle ') if ret != 0: sys.exit(1) fpgaRT = xdnn.XDNNFPGAOp(handles, args) #print "{:-^100}".format('1') fpgaOutput = fpgaRT.getOutputs() #print "{:-^100}".format('2') fpgaInput = fpgaRT.getInputs() #print "{:-^100}".format('3') img_paths = xdnn_io.getFilePaths(args['images']) inShape = (args['batch_sz'],) + tuple ( tuple (fpgaRT.getInputDescriptors().values() )[0][1:] ) firstInput = list(fpgaInput.values())[0] firstOutput = list (fpgaOutput.values())[0] for i in xrange(0, len(img_paths), args['batch_sz']): pl = [] for j, p in enumerate(img_paths[i:i + args['batch_sz']]): firstInput[0, ...], _ = xdnn_io.loadImageBlobFromFile(img_paths[0], args['img_raw_scale'], args['img_mean'], args['img_input_scale'], inShape[2], inShape[3]) pl.append(p) with open(args['netcfg']) as fp: data = json.load(fp) #print json.dumps(data, indent=2) # Strip nodes that don't run in hardware nodes = data['network'] nodes = [x for x in nodes if x['xdnn_kv']] nLayers = len(nodes) # How many iterations to run, and average across iterations = 1 # Initialize empty list to hold accumulated runtime t1 = [] for k in range(iterations): t1.append(0.0) # Run N iterations of network permutations for l in range(iterations): fpgaRT.execute(fpgaInput, fpgaOutput) t1[l] += (fpgaRT.get_exec_time()) #for node in nodes: # print node['name'] # Average it avetime = sum(t1)/iterations #print "{:<25} = {:<25}".format(layername, avetime) return avetime xdnn.closeHandle() del fpgaRT del fpgaInput del fpgaOutput del ret def getCurrentLayerByIndex(index = 0): #args = xdnn_io.processCommandLine() parser = xdnn_io.default_parser_args() parser.add_argument('--layerindex', type=int, default=0, help='Index value for layer in json', required=True) argvt = parser.parse_args() args = xdnn_io.make_dict_args(argvt) if 'layerindex' in args: index = args['layerindex'] with open(args['netcfg']) as fp: data = json.load(fp) # Strip nodes that don't run in hardware nodes = data['network'] nodes = [x for x in nodes if x['xdnn_kv'] and x['active'] == 1] # Get layername if index >= len(nodes): return None, None if nodes[index]['xdnn_kv']['slice'] == "0": return nodes[index]['name'], "DBL" return nodes[index]['name'], nodes[index]['xdnn_kv']['XNOp'] if __name__ == '__main__': parser = xdnn_io.default_parser_args() parser.add_argument('--layerindex', type=int, default=0, help='Index value for layer in json', required=True) argvt = parser.parse_args() args = xdnn_io.make_dict_args(argvt) #print json.dumps(args, indent=2) # Get layer name layername, opname = getCurrentLayerByIndex() if layername is None and opname is None: print "All = Done" sys.exit(0) if opname is not None and layername is None: print "DataMovementLayer = 0" sys.exit(0) if opname == "DBL": layername = layername + "-DBL" print layername,"= 0" sys.exit(0) # print "\n{:-^100}".format(layername) # Generate compiler JSON till this layer jsonname = generateLayerwiseJson(layername) # print "\n{:-^100}".format(jsonname) # Get the latency of the network till this layer latency = networkForward(jsonname, layername) print "{} = {}".format(layername, latency)
example/market/sub_pricedepth_bbo.py
bailzx5522/huobi_Python
611
11123889
from huobi.client.market import MarketClient def callback(price_depth_event: 'PriceDepthBboEvent'): price_depth_event.print_object() print() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) market_client = MarketClient() market_client.sub_pricedepth_bbo("btcusdt", callback, error)
RecoTracker/DebugTools/python/TrackAlgoCompareUtil_cff.py
ckamtsikis/cmssw
852
11123892
import FWCore.ParameterSet.Config as cms from RecoTracker.DebugTools.TrackAlgoCompareUtil_cfi import *
cflearn/models/cv/encoder/backbone/settings/mobilenet.py
carefree0910/carefree-learn
400
11123893
from typing import List from collections import OrderedDict from ..api import Preset remove_layers: List[str] = [] target_layers = OrderedDict( slice0="stage0", slice1="stage1", slice2="stage2", slice3="stage3", slice4="stage4", ) @Preset.register_settings() class MobileNetPreset(Preset): remove_layers = { "mobilenet_v2": remove_layers, } target_layers = { "mobilenet_v2": target_layers, } increment_configs = { "mobilenet_v2": {"out_channels": [16, 24, 32, 96, 320]}, } __all__ = ["MobileNetPreset"]
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_sysadmin_vm.py
CiscoDevNet/ydk-py
177
11123901
<reponame>CiscoDevNet/ydk-py """ Cisco_IOS_XR_sysadmin_vm This module contains definitions for the Calvados model objects. This module contains the YANG definitions for the Cisco IOS\-XR SysAdmin 'vm profile\|cpu\|memory' commands. Copyright(c) 2018 by Cisco Systems, Inc. All rights reserved. Copyright (c) 2012\-2018 by Cisco Systems, Inc. All rights reserved. """ import sys from collections import OrderedDict from ydk.types import Entity as _Entity_ from ydk.types import EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64 from ydk.filters import YFilter from ydk.errors import YError, YModelError from ydk.errors.error_handler import handle_type_error as _handle_type_error class Vm(_Entity_): """ .. attribute:: config **type**\: :py:class:`Config <ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm.Vm.Config>` """ _prefix = 'vm' _revision = '2018-11-20' def __init__(self): if sys.version_info > (3,): super().__init__() else: super(Vm, self).__init__() self._top_entity = None self.yang_name = "vm" self.yang_parent_name = "Cisco-IOS-XR-sysadmin-vm" self.is_top_level_class = True self.has_list_ancestor = False self.ylist_key_names = [] self._child_classes = OrderedDict([("config", ("config", Vm.Config))]) self._leafs = OrderedDict() self.config = Vm.Config() self.config.parent = self self._children_name_map["config"] = "config" self._segment_path = lambda: "Cisco-IOS-XR-sysadmin-vm:vm" self._is_frozen = True def __setattr__(self, name, value): self._perform_setattr(Vm, [], name, value) class Config(_Entity_): """ .. attribute:: hw_profile **type**\: :py:class:`HwProfile <ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm.Vm.Config.HwProfile>` .. attribute:: memory **type**\: :py:class:`Memory <ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm.Vm.Config.Memory>` .. attribute:: cpu **type**\: :py:class:`Cpu <ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm.Vm.Config.Cpu>` """ _prefix = 'vm' _revision = '2018-11-20' def __init__(self): if sys.version_info > (3,): super().__init__() else: super(Vm.Config, self).__init__() self.yang_name = "config" self.yang_parent_name = "vm" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_classes = OrderedDict([("hw-profile", ("hw_profile", Vm.Config.HwProfile)), ("memory", ("memory", Vm.Config.Memory)), ("cpu", ("cpu", Vm.Config.Cpu))]) self._leafs = OrderedDict() self.hw_profile = Vm.Config.HwProfile() self.hw_profile.parent = self self._children_name_map["hw_profile"] = "hw-profile" self.memory = Vm.Config.Memory() self.memory.parent = self self._children_name_map["memory"] = "memory" self.cpu = Vm.Config.Cpu() self.cpu.parent = self self._children_name_map["cpu"] = "cpu" self._segment_path = lambda: "config" self._absolute_path = lambda: "Cisco-IOS-XR-sysadmin-vm:vm/%s" % self._segment_path() self._is_frozen = True def __setattr__(self, name, value): self._perform_setattr(Vm.Config, [], name, value) class HwProfile(_Entity_): """ .. attribute:: profile xrv9k profile vpe\|vrr **type**\: :py:class:`Profile <ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm.Vm.Config.HwProfile.Profile>` """ _prefix = 'vm' _revision = '2018-11-20' def __init__(self): if sys.version_info > (3,): super().__init__() else: super(Vm.Config.HwProfile, self).__init__() self.yang_name = "hw-profile" self.yang_parent_name = "config" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_classes = OrderedDict([]) self._leafs = OrderedDict([ ('profile', (YLeaf(YType.enumeration, 'profile'), [('ydk.models.cisco_ios_xr.Cisco_IOS_XR_sysadmin_vm', 'Vm', 'Config.HwProfile.Profile')])), ]) self.profile = None self._segment_path = lambda: "hw-profile" self._absolute_path = lambda: "Cisco-IOS-XR-sysadmin-vm:vm/config/%s" % self._segment_path() self._is_frozen = True def __setattr__(self, name, value): self._perform_setattr(Vm.Config.HwProfile, ['profile'], name, value) class Profile(Enum): """ Profile (Enum Class) xrv9k profile vpe\|vrr .. data:: vrr = 0 """ vrr = Enum.YLeaf(0, "vrr") @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm.Config.HwProfile.Profile'] @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm.Config.HwProfile']['meta_info'] class Memory(_Entity_): """ .. attribute:: admin admin container memory in GB **type**\: int **range:** 0..4294967295 .. attribute:: rp rp container memory in GB **type**\: int **range:** 0..4294967295 .. attribute:: lc lc container memory in GB **type**\: int **range:** 0..4294967295 """ _prefix = 'vm' _revision = '2018-11-20' def __init__(self): if sys.version_info > (3,): super().__init__() else: super(Vm.Config.Memory, self).__init__() self.yang_name = "memory" self.yang_parent_name = "config" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_classes = OrderedDict([]) self._leafs = OrderedDict([ ('admin', (YLeaf(YType.uint32, 'admin'), ['int'])), ('rp', (YLeaf(YType.uint32, 'rp'), ['int'])), ('lc', (YLeaf(YType.uint32, 'lc'), ['int'])), ]) self.admin = None self.rp = None self.lc = None self._segment_path = lambda: "memory" self._absolute_path = lambda: "Cisco-IOS-XR-sysadmin-vm:vm/config/%s" % self._segment_path() self._is_frozen = True def __setattr__(self, name, value): self._perform_setattr(Vm.Config.Memory, ['admin', 'rp', 'lc'], name, value) @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm.Config.Memory']['meta_info'] class Cpu(_Entity_): """ .. attribute:: assign assign cpu cores to control/data plane **type**\: str **pattern:** 0(\-[0\-9]+)?/[0\-9]+(\-[0\-9]+)? """ _prefix = 'vm' _revision = '2018-11-20' def __init__(self): if sys.version_info > (3,): super().__init__() else: super(Vm.Config.Cpu, self).__init__() self.yang_name = "cpu" self.yang_parent_name = "config" self.is_top_level_class = False self.has_list_ancestor = False self.ylist_key_names = [] self._child_classes = OrderedDict([]) self._leafs = OrderedDict([ ('assign', (YLeaf(YType.str, 'assign'), ['str'])), ]) self.assign = None self._segment_path = lambda: "cpu" self._absolute_path = lambda: "Cisco-IOS-XR-sysadmin-vm:vm/config/%s" % self._segment_path() self._is_frozen = True def __setattr__(self, name, value): self._perform_setattr(Vm.Config.Cpu, ['assign'], name, value) @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm.Config.Cpu']['meta_info'] @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm.Config']['meta_info'] def clone_ptr(self): self._top_entity = Vm() return self._top_entity @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_sysadmin_vm as meta return meta._meta_table['Vm']['meta_info']
integration/continuous_test.py
drozzy/autonomous-learning-library
584
11123948
import unittest from all.environments import GymEnvironment from all.presets.continuous import ddpg, ppo, sac from validate_agent import validate_agent class TestContinuousPresets(unittest.TestCase): def test_ddpg(self): validate_agent( ddpg.device('cpu').hyperparameters(replay_start_size=50), GymEnvironment('LunarLanderContinuous-v2') ) def test_ppo(self): validate_agent( ppo.device('cpu'), GymEnvironment('LunarLanderContinuous-v2') ) def test_sac(self): validate_agent( sac.device('cpu').hyperparameters(replay_start_size=50), GymEnvironment('LunarLanderContinuous-v2') ) if __name__ == '__main__': unittest.main()
deep_privacy/inference/deep_privacy_anonymizer.py
chinitaberrio/DeepPrivacy
1,128
11124003
<gh_stars>1000+ import numpy as np import torch import deep_privacy.torch_utils as torch_utils import cv2 import pathlib import typing from deep_privacy.detection.detection_api import ImageAnnotation from .anonymizer import Anonymizer from . import infer def batched_iterator(batch, batch_size): k = list(batch.keys())[0] num_samples = len(batch[k]) num_batches = int(np.ceil(num_samples / batch_size)) for idx in range(num_batches): start = batch_size * idx end = start + batch_size yield { key: torch_utils.to_cuda(arr[start:end]) for key, arr in batch.items() } class DeepPrivacyAnonymizer(Anonymizer): def __init__(self, generator, batch_size, save_debug, fp16_inference: bool, truncation_level=5, **kwargs): super().__init__(**kwargs) self.inference_imsize = self.cfg.models.max_imsize self.batch_size = batch_size self.pose_size = self.cfg.models.pose_size self.generator = generator self.truncation_level = truncation_level self.save_debug = save_debug self.fp16_inference = fp16_inference self.debug_directory = pathlib.Path(".debug", "inference") self.debug_directory.mkdir(exist_ok=True, parents=True) @torch.no_grad() def _get_face(self, batch): keys = ["condition", "mask", "landmarks", "z"] forward = [batch[k] for k in keys] # print([x.shape for x in forward]) with torch.cuda.amp.autocast(enabled=self.fp16_inference): return self.generator(*forward).cpu() @torch.no_grad() def anonymize_images(self, images: np.ndarray, image_annotations: typing.List[ImageAnnotation] ) -> typing.List[np.ndarray]: anonymized_images = [] for im_idx, image_annotation in enumerate(image_annotations): # pre-process imsize = self.inference_imsize condition = torch.zeros( (len(image_annotation), 3, imsize, imsize), dtype=torch.float32) mask = torch.zeros((len(image_annotation), 1, imsize, imsize)) landmarks = torch.empty( (len(image_annotation), self.pose_size), dtype=torch.float32) for face_idx in range(len(image_annotation)): face, mask_ = image_annotation.get_face(face_idx, imsize) condition[face_idx] = torch_utils.image_to_torch( face, cuda=False, normalize_img=True ) mask[face_idx, 0] = torch.from_numpy(mask_).float() kp = image_annotation.aligned_keypoint(face_idx) landmarks[face_idx] = kp[:, :self.pose_size] img = condition condition = condition * mask z = infer.truncated_z( condition, self.cfg.models.generator.z_shape, self.truncation_level) batches = dict( condition=condition, mask=mask, landmarks=landmarks, z=z, img=img ) # Inference anonymized_faces = np.zeros(( len(image_annotation), imsize, imsize, 3), dtype=np.float32) for idx, batch in enumerate( batched_iterator(batches, self.batch_size)): face = self._get_face(batch) face = torch_utils.image_to_numpy( face, to_uint8=False, denormalize=True) start = idx * self.batch_size anonymized_faces[start:start + self.batch_size] = face anonymized_image = image_annotation.stitch_faces(anonymized_faces) anonymized_images.append(anonymized_image) if self.save_debug: num_faces = len(batches["condition"]) for face_idx in range(num_faces): orig_face = torch_utils.image_to_numpy( batches["img"][face_idx], denormalize=True, to_uint8=True) condition = torch_utils.image_to_numpy( batches["condition"][face_idx], denormalize=True, to_uint8=True) fake_face = anonymized_faces[face_idx] fake_face = (fake_face * 255).astype(np.uint8) to_save = np.concatenate( (orig_face, condition, fake_face), axis=1) filepath = self.debug_directory.joinpath( f"im{im_idx}_face{face_idx}.png") cv2.imwrite(str(filepath), to_save[:, :, ::-1]) return anonymized_images def use_mask(self): return self.generator.use_mask
moonshot/commission/fx.py
windblood/moonshot
122
11124020
<gh_stars>100-1000 # Copyright 2017-2021 QuantRocket 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. from moonshot.commission import PercentageCommission class SpotFXCommission(PercentageCommission): """ Commission class for spot FX. This class can be used as-is. NOTE: min commissions are not modeled for spot FX. This is because min commissions for spot FX are in USD ($2), regardless of the quote currency. The Moonshot class passes NLVs in the quote currency (the Currency field). To accurately model min commissions, these NLVs would need to be converted to USD. Examples -------- Use this on your strategy: >>> class MyFXStrategy(Moonshot): >>> COMMISSION_CLASS = SpotFXCommission """ BROKER_COMMISSION_RATE = 0.00002 # 0.2 bps EXCHANGE_FEE_RATE = 0 MIN_COMMISSION = 0 # see NOTE in docstring
scripts/search.py
phasorhand/PyTorchText
1,136
11124034
<gh_stars>1000+ #coding:utf8 import sys sys.path.append('../') from utils import get_score import json import pickle file1='/mnt/zhihu/data/RCNN_deep_word_val_4115' file2='/mnt/zhihu/data/rccndeep_char_val_4037.pth' file3='/mnt/zhihu/data/multicnntextbndeep40705_val_word.pth' label_path = '/mnt/zhihu/data/labels.json' # test_data_path='/mnt/zhihu/data/test.npz' def ensamble(file1,file2,file3,label_path=label_path,test_data_path=test_data_path,result_csv=None): import torch as t import numpy as np if result_csv is None: import time result_csv = time.strftime('%y%m%d_%H%M%S.csv') a = t.load(file1) b = t.load(file2) c = t.load(file3) index2qid = np.load(test_data_path)['index2qid'].item() with open(label_path) as f: labels_info = json.load(f) qid2label = labels_info['d'] # with open(label_path) as f: label2qid = json.load(f)['id2label'] true_labels = [qid2label[index2qid[2999967-200000+ii]] for ii in range(len(a))] # for ii,item in enumerate(result): # rows[ii] = [index2qid[ii]] + [label2qid[str(_)] for _ in item ] previous_best_score = 0.42 def target(args): w1,w2 = args r = a + b*w1 +c*w2 result = r.topk(5,1)[1] predict_label_and_marked_label_list = [[_1,_2] for _1,_2 in zip(result,true_labels)] score,_,_,_ = get_score(predict_label_and_marked_label_list) print (args,score,_) if score>previous_best_score: previous_best_score = score with open(str(score) ,'wb') as f: pickle.dump(args,f) return -score list_space = [hp.uniform('w1',0,2),hp.uniform('w2',0,2)] best = fmin(new_target,list_space,algo=tpe.suggest,max_evals=50) print best # import csv # with open(result_csv,'w') as f: # writer = csv.writer(f) # writer.writerows(rows) if __name__ == '__main__': import fire fire.Fire()
test/integration/test_setup.py
wnojopra/dsub
146
11124049
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup module for dsub tests.""" # test_setup.py # # Intended to be imported into a test. # The code here will: # # * Ensure the DSUB_PROVIDER is set (default: local) # * Set the TEST_NAME based on the name of the calling script. # * Set the TEST_DIR to the directory the test file is in. # * For task file tests, set TASKS_FILE and TASKS_FILE_TMPL. # * Set the TEST_TMP variable for a temporary directory. from __future__ import print_function import datetime import os import random import string import sys # If the DSUB_PROVIDER is not set, figure it out from the name of the script. # If the script name is <test>.<provider>.sh, pull out the provider. # If the script name is <test>.sh, use "local". # If the DSUB_PROVIDER is set, make sure it is correct for a provider test. SCRIPT_NAME = os.path.basename(sys.argv[0]) SCRIPT_DEFAULT_PROVIDER = SCRIPT_NAME.split('.')[1] if SCRIPT_NAME.count( '.') == 2 else None DSUB_PROVIDER = os.getenv('DSUB_PROVIDER') if not DSUB_PROVIDER: if SCRIPT_DEFAULT_PROVIDER: DSUB_PROVIDER = SCRIPT_DEFAULT_PROVIDER else: DSUB_PROVIDER = 'local' elif SCRIPT_DEFAULT_PROVIDER: if DSUB_PROVIDER != SCRIPT_DEFAULT_PROVIDER: print('DSUB_PROVIDER inconsistent with default provider', file=sys.stderr) print('"%s" is not "%s"' % (DSUB_PROVIDER, SCRIPT_DEFAULT_PROVIDER), file=sys.stderr) sys.exit(1) # Compute the name of the test from the calling script # (trim the e2e_ or unit_ prefix, along with the .py extension) TEST_NAME = os.path.splitext(SCRIPT_NAME.split('_', 1)[1])[0] print('Setting up test: %s' % TEST_NAME) TEST_DIR = os.path.dirname(sys.argv[0]) TEST_TMP = '%s/tmp' % os.getenv('TEST_TMP', '/tmp/dsub-test/py/%s/%s' % (DSUB_PROVIDER, TEST_NAME)) if TEST_NAME.endswith('_tasks'): TASKS_FILE_TMPL = '%s/%s.tsv.tmpl' % (TEST_DIR, TEST_NAME) TASKS_FILE = '%s/%s.tsv' % (TEST_TMP, TEST_NAME) else: TASKS_FILE_TMPL = None TASKS_FILE = None def _generate_test_token(): # Generate an id for tests to use that is reasonably likely to be unique # (timestamp + 8 random characters). timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') suffix = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(8)) return '{}_{}'.format(timestamp, suffix) TEST_TOKEN = os.getenv('TEST_TOKEN', _generate_test_token())
examples/kitchensink/KitchenSink.py
takipsizad/pyjs
739
11124068
import pyjd # this is dummy in pyjs from pyjamas import logging from pyjamas.ui.Button import Button from pyjamas.ui.RootPanel import RootPanel from pyjamas.ui.HTML import HTML from pyjamas.ui.DockPanel import DockPanel from pyjamas.ui import HasAlignment from pyjamas.ui.Hyperlink import Hyperlink from pyjamas.ui.VerticalPanel import VerticalPanel from pyjamas.ui.Sink import SinkList from pyjamas import History from pyjamas import Window import sink.Info as Info import sink.Buttons as Buttons import sink.Layouts as Layouts import sink.Images as Images import sink.Menus as Menus import sink.Lists as Lists import sink.Popups as Popups import sink.Tables as Tables import sink.Text as Text import sink.Trees as Trees import sink.Frames as Frames import sink.Tabs as Tabs from sink.Logger import Logger log = logging.getAppendLogger(__name__, logging.DEBUG, logging.PLAIN_FORMAT) class KitchenSink: def onHistoryChanged(self, token): log.debug("onHistoryChanged: %s", token) info = self.sink_list.find(token) if info is not None: self.show(info, False) else: self.showInfo() def onModuleLoad(self): self.curInfo='' self.curSink=None self.description=HTML() self.sink_list=SinkList() self.panel=DockPanel() self.loadSinks() self.sinkContainer = DockPanel() self.sinkContainer.setStyleName("ks-Sink") vp=VerticalPanel() vp.setWidth("100%") vp.add(self.description) vp.add(self.sinkContainer) self.description.setStyleName("ks-Info") self.panel.add(self.sink_list, DockPanel.WEST) self.panel.add(vp, DockPanel.CENTER) self.panel.setCellVerticalAlignment(self.sink_list, HasAlignment.ALIGN_TOP) self.panel.setCellWidth(vp, "100%") History.addHistoryListener(self) RootPanel().add(self.panel) RootPanel().add(Logger()) #Show the initial screen. initToken = History.getToken() if len(initToken): self.onHistoryChanged(initToken) else: self.showInfo() def show(self, info, affectHistory): if info == self.curInfo: return self.curInfo = info #log.debug("showing " + info.getName()) if self.curSink is not None: #log.debug("removing " + str(self.curSink)) self.curSink.onHide() self.sinkContainer.remove(self.curSink) self.curSink = info.getInstance() self.sink_list.setSinkSelection(info.getName()) self.description.setHTML(info.getDescription()) if (affectHistory): History.newItem(info.getName()) self.sinkContainer.add(self.curSink, DockPanel.CENTER) self.sinkContainer.setCellWidth(self.curSink, "100%") self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() def loadSinks(self): self.sink_list.add(Info.init()) self.sink_list.add(Buttons.init()) self.sink_list.add(Menus.init()) self.sink_list.add(Images.init()) self.sink_list.add(Layouts.init()) self.sink_list.add(Lists.init()) self.sink_list.add(Popups.init()) self.sink_list.add(Tables.init()) self.sink_list.add(Text.init()) self.sink_list.add(Trees.init()) self.sink_list.add(Frames.init()) self.sink_list.add(Tabs.init()) def showInfo(self): self.show(self.sink_list.find("Info"), False) if __name__ == '__main__': pyjd.setup("public/KitchenSink.html") app = KitchenSink() app.onModuleLoad() pyjd.run()
tests/data/translated_titles/conf.py
asmeurer/nikola
1,901
11124076
# -*- coding: utf-8 -*- import time BLOG_AUTHOR = "<NAME>" # (translatable) BLOG_TITLE = "Demo Site" # (translatable) SITE_URL = "https://example.com/" BLOG_EMAIL = "<EMAIL>" BLOG_DESCRIPTION = "This is a demo site for Nikola." # (translatable) DEFAULT_LANG = "en" TRANSLATIONS = { "en": "", "pl": "./pl", } TRANSLATIONS_PATTERN = "{path}.{lang}.{ext}" NAVIGATION_LINKS = { DEFAULT_LANG: ( ('/archive.html', 'Archives'), ('/categories/index.html', 'Tags'), ('/rss.xml', 'RSS'), ), } POSTS = ( ("posts/*.rst", "posts", "post.tmpl"), ("posts/*.txt", "posts", "post.tmpl"), ) PAGES = ( ("pages/*.rst", "pages", "page.tmpl"), ("pages/*.txt", "pages", "page.tmpl"), ) COMPILERS = { "rest": ('.rst', '.txt'), "markdown": ('.md', '.mdown', '.markdown'), "textile": ('.textile',), "txt2tags": ('.t2t',), "bbcode": ('.bb',), "wiki": ('.wiki',), "ipynb": ('.ipynb',), "html": ('.html', '.htm'), # PHP files are rendered the usual way (i.e. with the full templates). # The resulting files have .php extensions, making it possible to run # them without reconfiguring your server to recognize them. "php": ('.php',), # Pandoc detects the input from the source filename # but is disabled by default as it would conflict # with many of the others. # "pandoc": ('.rst', '.md', '.txt'), } REDIRECTIONS = [] THEME = "bootblog4" LICENSE = "" CONTENT_FOOTER = 'Contents &copy; {date} <a href="mailto:{email}">{author}</a> - Powered by <a href="https://getnikola.com/" rel="nofollow">Nikola</a> {license}' CONTENT_FOOTER_FORMATS = { DEFAULT_LANG: ( (), { "email": BLOG_EMAIL, "author": BLOG_AUTHOR, "date": time.gmtime().tm_year, "license": LICENSE } ) } COMMENT_SYSTEM = "disqus" COMMENT_SYSTEM_ID = "nikolademo" GLOBAL_CONTEXT = {}
CurvesGenerator/draw.py
CodesHub/PathPlanning
3,693
11124078
import matplotlib.pyplot as plt import numpy as np PI = np.pi class Arrow: def __init__(self, x, y, theta, L, c): angle = np.deg2rad(30) d = 0.5 * L w = 2 x_start = x y_start = y x_end = x + L * np.cos(theta) y_end = y + L * np.sin(theta) theta_hat_L = theta + PI - angle theta_hat_R = theta + PI + angle x_hat_start = x_end x_hat_end_L = x_hat_start + d * np.cos(theta_hat_L) x_hat_end_R = x_hat_start + d * np.cos(theta_hat_R) y_hat_start = y_end y_hat_end_L = y_hat_start + d * np.sin(theta_hat_L) y_hat_end_R = y_hat_start + d * np.sin(theta_hat_R) plt.plot([x_start, x_end], [y_start, y_end], color=c, linewidth=w) plt.plot([x_hat_start, x_hat_end_L], [y_hat_start, y_hat_end_L], color=c, linewidth=w) plt.plot([x_hat_start, x_hat_end_R], [y_hat_start, y_hat_end_R], color=c, linewidth=w) class Car: def __init__(self, x, y, yaw, w, L): theta_B = PI + yaw xB = x + L / 4 * np.cos(theta_B) yB = y + L / 4 * np.sin(theta_B) theta_BL = theta_B + PI / 2 theta_BR = theta_B - PI / 2 x_BL = xB + w / 2 * np.cos(theta_BL) # Bottom-Left vertex y_BL = yB + w / 2 * np.sin(theta_BL) x_BR = xB + w / 2 * np.cos(theta_BR) # Bottom-Right vertex y_BR = yB + w / 2 * np.sin(theta_BR) x_FL = x_BL + L * np.cos(yaw) # Front-Left vertex y_FL = y_BL + L * np.sin(yaw) x_FR = x_BR + L * np.cos(yaw) # Front-Right vertex y_FR = y_BR + L * np.sin(yaw) plt.plot([x_BL, x_BR, x_FR, x_FL, x_BL], [y_BL, y_BR, y_FR, y_FL, y_BL], linewidth=1, color='black') Arrow(x, y, yaw, L / 2, 'black') # plt.axis("equal") # plt.show() if __name__ == '__main__': # Arrow(-1, 2, 60) Car(0, 0, 1, 2, 60)
tests/test_manage.py
klen/muffin
704
11124183
<filename>tests/test_manage.py<gh_stars>100-1000 import pytest from unittest import mock @pytest.fixture(params=['curio', 'trio', 'asyncio']) def cmd_aiolib(request): return request.param def test_command(app): @app.manage def cmd1(name, lower=False): """Custom description. :param name: help for name """ pass assert cmd1.parser assert cmd1.parser.description == 'Custom description.' assert cmd1.parser._actions[1].help == 'help for name' ns = cmd1.parser.parse_args(['test']) assert dict(ns._get_kwargs()) == {'name': 'test', 'lower': False} @app.manage def cmd2(*names, lower=False): pass ns = cmd2.parser.parse_args(['test']) assert dict(ns._get_kwargs()) == {'*': ['test'], 'lower': False} def test_manage(app, capsys, monkeypatch): @app.manage def hello(user_name, lower=False): if lower: user_name = user_name.lower() print("hello " + user_name) with pytest.raises(SystemExit): app.manage.run(*'hello') out, err = capsys.readouterr() assert not out assert err app.manage.run(*'hello Mike'.split()) out, err = capsys.readouterr() assert "hello Mike\n" == out app.manage.run(*'hello Sam --lower'.split()) out, err = capsys.readouterr() assert "hello sam\n" == out def test_manage_async(app, cmd_aiolib): import typing as t from muffin.utils import current_async_library start = mock.MagicMock() app.on_startup(start) finish = mock.MagicMock() app.on_shutdown(finish) run = mock.MagicMock() @app.manage(lifespan=True) async def command(name: t.Union[str, int]): run(name) assert current_async_library() == cmd_aiolib app.manage.run(*f"--aiolib={cmd_aiolib} command test".split()) assert run.called args, _ = run.call_args assert args == ('test',) assert start.called assert finish.called def test_shell_context(app): assert app.cfg.MANAGE_SHELL @app.manage.shell def custom_context(): return {"custom": True} assert app.cfg.MANAGE_SHELL is custom_context
test/unit/__init__.py
daltonconley/amazon-redshift-python-driver
125
11124233
<gh_stars>100-1000 from .mocks import MockCredentialsProvider
plugins/discovery/shodan/__init__.py
otherbeast/hackers-tool-kit
655
11124254
<filename>plugins/discovery/shodan/__init__.py<gh_stars>100-1000 from api import WebAPI __version__ = "0.5.0" __all__ = ['WebAPI']
tests/config/test_file_browser.py
kubajir/msticpy
820
11124269
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Module docstring.""" import pytest_check as check from msticpy.config.file_browser import FileBrowser __author__ = "<NAME>" # pylint: disable=protected-access, global-statement, invalid-name file_name = "" def test_file_browser(): """Function_docstring.""" f_brow = FileBrowser(".", select_cb=_callback) starting_folder = f_brow.current_folder check.greater(len(f_brow.select_file.options), 0) check.greater(len(f_brow.select_folder.options), 0) check.is_in("..", f_brow.select_folder.options) curr_files = f_brow.select_file.options check.equal(curr_files, f_brow.select_file.options) f_brow._open_folder(tgt_folder="msticpy") check.not_equal(curr_files, f_brow.select_file.options) f_brow.txt_path.value = str(starting_folder) f_brow._enter_folder(event=None) check.greater(len(f_brow.select_file.options), 0) f_brow.select_file.selected_index = 1 f_brow._return_file(btn=None) check.equal(file_name, f_brow.file) f_brow.txt_search.value = "*.py" f_brow._search(f_brow.btn_search) check.greater(len(f_brow.select_search.options), 0) def _callback(file): global file_name file_name = file
tests/trac/test-trac-0204.py
eLBati/pyxb
123
11124278
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.utils.domutils from xml.dom import Node import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="YesNoChoice"> <xs:annotation> <xs:documentation>Yes No Choice</xs:documentation> </xs:annotation> <xs:choice> <xs:element name="Yes" type="xs:boolean" fixed="true"/> <xs:element name="No" type="xs:boolean" fixed="true"/> </xs:choice> </xs:complexType> <xs:element name="yesNoChoice" type="YesNoChoice"/> </xs:schema>''' code = pyxb.binding.generate.GeneratePython(schema_text=xsd) #open('code.py', 'w').write(code) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest import sys class TestTrac0204 (unittest.TestCase): if sys.version_info[:2] < (2, 7): def assertIsNone (self, v): self.assertEqual(None, v) def assertIsNotNone (self, v): self.assertNotEqual(None, v) def testCtor (self): instance = yesNoChoice() self.assertIsNone(instance.Yes) self.assertIsNone(instance.No) instance = yesNoChoice(Yes=True) self.assertIsNotNone(instance.Yes) self.assertIsNone(instance.No) instance = yesNoChoice(Yes=True, No=True) self.assertRaises(pyxb.UnprocessedElementContentError, instance.validateBinding) if __name__ == '__main__': unittest.main()
resotocore/core/dependencies.py
someengineering/cloudkeeper
316
11124302
import argparse import logging import multiprocessing as mp import os.path from argparse import Namespace from typing import Optional, List, Callable from urllib.parse import urlparse from arango.database import StandardDatabase from resotolib.args import ArgumentParser from resotolib.jwt import add_args as jwt_add_args from core import async_extensions from core.analytics import AnalyticsEventSender from core.db.db_access import DbAccess from core.model.adjust_node import DirectAdjuster from core.task.task_handler import TaskHandler log = logging.getLogger(__name__) def parse_args(args: Optional[List[str]] = None, namespace: Optional[str] = None) -> Namespace: def is_file(message: str) -> Callable[[str], str]: def check_file(path: str) -> str: if os.path.isfile(path): return path else: raise AttributeError(f"{message}: path {path} is not a directory!") return check_file def is_dir(message: str) -> Callable[[str], str]: def check_dir(path: str) -> str: if os.path.isdir(path): return path else: raise AttributeError(f"{message}: path {path} is not a directory!") return check_dir def is_url(message: str) -> Callable[[str], str]: def check_url(url: str) -> str: try: urlparse(url) return url except ValueError as ex: raise AttributeError(f"{message}: url {url} can not be parsed!") from ex return check_url parser = ArgumentParser( env_args_prefix="RESOTOCORE_", description="Maintains graphs of resources of any shape.", epilog="Keeps all the things.", ) jwt_add_args(parser) parser.add_argument( "--log-level", default="info", help="Log level (default: info)", ) parser.add_argument( "--graphdb-server", default="http://localhost:8529", dest="graphdb_server", help="Graph database server (default: http://localhost:8529)", ) parser.add_argument( "--graphdb-database", default="resoto", dest="graphdb_database", help="Graph database name (default: resoto)", ) parser.add_argument( "--graphdb-username", default="resoto", dest="graphdb_username", help="Graph database login (default: resoto)", ) parser.add_argument( "--graphdb-password", default="", dest="graphdb_password", help='Graph database password (default: "")', ) parser.add_argument( "--graphdb-type", default="arangodb", dest="graphdb_type", help="Graph database type (default: arangodb)", ) parser.add_argument( "--graphdb-no-ssl-verify", action="store_true", dest="graphdb_no_ssl_verify", help="If the connection should not be verified (default: False)", ) parser.add_argument( "--graphdb-request-timeout", type=int, default=900, dest="graphdb_request_timeout", help="Request timeout in seconds (default: 900)", ) parser.add_argument( "--plantuml-server", default="http://plantuml.resoto.org:8080", help="PlantUML server URI for UML image rendering.", ) parser.add_argument( "--host", type=str, default="localhost", nargs="+", help="TCP host(s) to bind on (default: localhost)", ) parser.add_argument( "--port", type=int, default=8900, help="TCP port to bind on (default: 8900)", ) parser.add_argument( "--merge_max_wait_time_seconds", type=int, default=3600, help="Max waiting time to complete a merge graph action.", ) parser.add_argument("--debug", default=False, action="store_true", help=argparse.SUPPRESS) parser.add_argument( "--analytics-opt-out", default=False, action="store_true", help="Stop collecting analytics data.", ) parser.add_argument( "--ui-path", type=is_dir("can not parse --ui-dir"), help="The directory where the UI is installed. This directory will be served under /ui/.", ) parser.add_argument( "--tsdb-proxy-url", type=is_url("can not parse --tsdb-proxy-url"), help="The url to the time series database. This path will be served under /tsdb/.", ) parser.add_argument( "--tls-cert", type=is_file("can not parse --tls-cert"), help="Path to a single file in PEM format containing the certificate as well as any number " "of CA certificates needed to establish the certificate’s authenticity.", ) parser.add_argument( "--tls-key", type=is_file("can not parse --tls-key"), help="Path to a file containing the private key. " "If not defined the private key will be taken from certfile as well.", ) parser.add_argument( "--tls-password", type=str, help="Optional password to decrypt the private key file.", ) parser.add_argument( "--cli-default-graph", type=str, default="resoto", dest="cli_default_graph", help="Use this graph for CLI actions, if no graph is specified explicitly.", ) parser.add_argument( "--cli-default-section", type=str, default="reported", dest="cli_default_section", help="Use this graph section by default, if no section is specified." "Relative paths will be interpreted with respect to this section.", ) TaskHandler.add_args(parser) return parser.parse_args(args, namespace) # type: ignore # Note: this method should be called from every started process as early as possible def setup_process(args: Namespace, child_process: Optional[str] = None) -> None: # Note: if another appender than the log appender is used, proper multiprocess logging needs to be enabled. # See https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes log_format = "%(asctime)s|resotocore|%(levelname)5s|%(process)d|%(threadName)10s %(message)s" logging.basicConfig( format=log_format, datefmt="%y-%m-%d %H:%M:%S", level=logging.getLevelName(args.log_level.upper()), force=True, ) # adjust log levels for specific loggers if not args.debug: # mute analytics transmission errors unless debug is enabled logging.getLogger("posthog").setLevel(logging.FATAL) logging.getLogger("backoff").setLevel(logging.FATAL) # transitions (fsm) creates a lot of log noise. Only show warnings. logging.getLogger("transitions.core").setLevel(logging.WARNING) # set/reset process creation method reset_process_start_method() # reset global async thread pool (forked processes need to create a fresh pool) async_extensions.GlobalAsyncPool = None def reset_process_start_method() -> None: preferred = "spawn" current = mp.get_start_method(True) if current != preferred: if preferred in mp.get_all_start_methods(): log.debug(f"Set process start method to {preferred}") mp.set_start_method(preferred, True) return log.warning(f"{preferred} method not available. Have {mp.get_all_start_methods()}. Use {current}") def db_access(db: StandardDatabase, event_sender: AnalyticsEventSender) -> DbAccess: adjuster = DirectAdjuster() return DbAccess(db, event_sender, adjuster)
lib/pylayer/mask_layer.py
giladsharir/MNC-1
544
11124315
<reponame>giladsharir/MNC-1 # -------------------------------------------------------- # Multitask Network Cascade # Written by <NAME> # Copyright (c) 2016, <NAME> # Licensed under The MIT License [see LICENSE for details] # -------------------------------------------------------- import caffe import cv2 import numpy as np from transform.mask_transform import mask_overlap from mnc_config import cfg class MaskLayer(caffe.Layer): """ This layer Take input from sigmoid predicted masks Assign each label for segmentation classifier according to region overlap """ def setup(self, bottom, top): self._phase = str(self.phase) self._top_name_map = {} top[0].reshape(1, 1, cfg.MASK_SIZE, cfg.MASK_SIZE) self._top_name_map['mask_proposal'] = 0 if self._phase == 'TRAIN': top[1].reshape(1, 1) self._top_name_map['mask_proposal_label'] = 1 def reshape(self, bottom, top): """ Reshaping happens during the call to forward """ pass def forward(self, bottom, top): if str(self.phase) == 'TRAIN': blobs = self.forward_train(bottom, top) elif str(self.phase) == 'TEST': blobs = self.forward_test(bottom, top) else: print 'Unrecognized phase' raise NotImplementedError for blob_name, blob in blobs.iteritems(): top[self._top_name_map[blob_name]].reshape(*blob.shape) top[self._top_name_map[blob_name]].data[...] = blob.astype(np.float32, copy=False) def backward(self, top, propagate_down, bottom): if propagate_down[0]: bottom[0].diff.fill(0.) top_grad = top[0].diff.reshape(top[0].diff.shape[0], cfg.MASK_SIZE * cfg.MASK_SIZE) bottom[0].diff[self.pos_sample, :] = top_grad[self.pos_sample, :] def forward_train(self, bottom, top): # Take sigmoid prediction as input mask_pred = bottom[0].data # get ground truth mask and labels gt_masks = bottom[1].data gt_masks_info = bottom[2].data num_mask_pred = mask_pred.shape[0] top_label = np.zeros((gt_masks_info.shape[0], 1)) # 2. Calculate region overlap # Since the target gt mask may have different size # We need to resize predicted masks into different sizes mask_size = cfg.MASK_SIZE for i in xrange(num_mask_pred): # if the bounding box is itself background if gt_masks_info[i][0] == -1: top_label[i][0] = 0 continue else: info = gt_masks_info[i] gt_mask = gt_masks[info[0]][0:info[1], 0:info[2]] ex_mask = mask_pred[i].reshape((mask_size, mask_size)) ex_box = np.round(info[4:8]).astype(int) gt_box = np.round(info[8:12]).astype(int) # resize to large gt_masks, note cv2.resize is column first ex_mask = cv2.resize(ex_mask.astype(np.float32), (ex_box[2] - ex_box[0] + 1, ex_box[3] - ex_box[1] + 1)) ex_mask = ex_mask >= cfg.BINARIZE_THRESH top_label[i][0] = 0 if mask_overlap(ex_box, gt_box, ex_mask, gt_mask) < cfg.TRAIN.FG_SEG_THRESH else info[3] # output continuous mask for MNC resized_mask_pred = mask_pred.reshape((num_mask_pred, 1, cfg.MASK_SIZE, cfg.MASK_SIZE)) self.pos_sample = np.where(top_label > 0)[0] blobs = { 'mask_proposal': resized_mask_pred, 'mask_proposal_label': top_label } return blobs def forward_test(self, bottom, top): mask_pred = bottom[0].data num_mask_pred = mask_pred.shape[0] resized_mask_pred = mask_pred.reshape((num_mask_pred, 1, cfg.MASK_SIZE, cfg.MASK_SIZE)) blobs = { 'mask_proposal': resized_mask_pred } return blobs
benchmark/okon_grep_benchmark.py
droidmonkey/okon
194
11124322
import subprocess import sys import os import timeit from okon_benchmark_utils import * NUMBER_OF_HASHES_TO_BENCHMARK = int(sys.argv[1]) PATH_TO_ORIGINAL_FILE = sys.argv[2] NUMBER_OF_HASHES_IN_ORIGINAL_FILE = int(sys.argv[3]) BENCHMARK_SEED = int(sys.argv[4]) if len(sys.argv) > 4 else 0 def run_benchmark(hash_to_benchmark): os.system('sudo sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"') command = ['grep', '-m', '1', '^{}'.format(hash_to_benchmark), PATH_TO_ORIGINAL_FILE] start = timeit.default_timer() subprocess.run(command, stdout=subprocess.PIPE) end = timeit.default_timer() return int((end - start) * 1000) hashes = collect_hashes_to_benchmark(BENCHMARK_SEED, NUMBER_OF_HASHES_TO_BENCHMARK, PATH_TO_ORIGINAL_FILE, NUMBER_OF_HASHES_IN_ORIGINAL_FILE) results = run_benchmarks(hashes, run_benchmark) print('Grep benchmark done, result: {}ms'.format(sum(results) / len(results)))
devtools/src/klio_devtools/cli.py
gaybro8777/klio
705
11124335
# Copyright 2020 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import click from klio_cli import cli as main_cli from klio_cli import options from klio_cli.cli import main from klio_cli.utils import cli_utils from klio_core import config from klio_core import options as core_options from klio_core import utils as core_utils from klio_devtools.commands import develop @main.command( "develop", short_help="Develop on the klio ecosystem in a job's container.", help=( "Builds & runs a job's container, mounts the job's code in " "`/usr/src/app`, installs klio packages as 'editable' packages " "that will automatically pick up local changes, and attaches to " "the container with an interactive terminal to enable manual " "runs of `klioexec`.\n\nNOTE: It's probably a good idea to locally " "bump the versions of the libraries to ensure proper installation." ), ) @core_options.job_dir @core_options.config_file @core_options.image_tag(default=None, show_default="``git-sha[dirty?]``") @options.runtime @click.option( "--klio-path", type=click.Path( exists=True, dir_okay=True, file_okay=False, readable=True, writable=True, resolve_path=True, ), help="Path to klio repo", required=True, ) @click.option( "--exclude", help="exclude installing a particular package", multiple=True, ) def develop_job(job_dir, config_file, **kwargs): job_dir, config_path = core_utils.get_config_job_dir(job_dir, config_file) config_data = core_utils.get_config_by_path(config_path) conf = config.KlioConfig(config_data) git_sha = cli_utils.get_git_sha(job_dir, kwargs.get("image_tag")) image_tag = kwargs.get("image_tag") or git_sha if config_file: basename = os.path.basename(config_file) image_tag = "{}-{}".format(image_tag, basename) runtime_config = main_cli.DockerRuntimeConfig( image_tag=image_tag, force_build=kwargs.get("force_build"), config_file_override=config_file, ) klio_pipeline = develop.DevelopKlioContainer( job_dir, conf, runtime_config, kwargs["klio_path"], kwargs["exclude"] ) klio_pipeline.run()
examples/xtensa/wasm_fac/make_flash.py
rakati/ppci-mirror
161
11124337
#!/usr/bin/python from ppci.api import construct construct('build.xml') with open('hello.bin', 'rb') as f: hello_bin = f.read() flash_size = 4 * 1024 * 1024 with open('lx60.flash', 'wb') as f: f.write(hello_bin) padding = flash_size - len(hello_bin) f.write(bytes(padding))
python codes/Queue.py
mflilian/Hacktoberfest2020-1
266
11124430
class Queue: def __init__(self): self.items = [] def add_item(self, item): return self.items.insert(0, item) def remove_item(self): if self.is_empty(): return print("Queue is Empty") return self.items.pop() def is_empty(self): return self.items == [] def length(self): return len(self.items) def peek(self): if self.is_empty(): return print("Queue is Empty") return self.items[-1] def main(): queue = Queue() print("Type Your Name : ") name = input() print("Welcome " + name) print("Choose your option") while True: print(" 1. Add Item \n 2. Remove Item \n 3. Length of Queue \n 4. Next Remove Item \n 5. Show Queue") print("________________________\n________________________") choice = input() if choice == "1": print("Enter Element (Any Data Type)") x = input() queue.add_item(x) print("*********************\n*********************") elif choice == "2": queue.remove_item() elif choice == "3": print('Length of the Queue is in Below') print(queue.length()) print("*********************\n*********************") elif choice == "4": print("Next Remove Item is in below") print(queue.peek()) print("*********************\n*********************") elif choice == "5": print(queue.items) print("*********************\n*********************") main()
h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_display_day_of_month.py
ahmedengu/h2o-3
6,098
11124476
<filename>h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_display_day_of_month.py df14['D'].day() # D # --- # 18 # 19 # 20
Applications/ctkSimplePythonShell/Python/ctkSimplePythonShell.py
ntoussaint/CTK
515
11124489
<filename>Applications/ctkSimplePythonShell/Python/ctkSimplePythonShell.py import qt, ctk def app(): return _ctkSimplePythonShellInstance def quit(): exit() def exit(): app().quit()
__scraping__/newegg.ca - urllib, BS/main.py
furas/python-code
140
11124506
<reponame>furas/python-code # author: Bartlomiej "furas" Burek (https://blog.furas.pl) # date: 2021.10.07 # # title: 'NoneType' object is not subscriptable when webscraping image title # url: https://stackoverflow.com/questions/69475748/nonetype-object-is-not-subscriptable-when-webscraping-image-title/69477667#69477667 # ['NoneType' object is not subscriptable when webscraping image title](https://stackoverflow.com/questions/69475748/nonetype-object-is-not-subscriptable-when-webscraping-image-title/69477667#69477667) from bs4 import BeautifulSoup as soup from urllib.request import urlopen as ureq url2 = 'https://www.newegg.ca/Desktop-Graphics-Cards/SubCategory/ID-48?Tid=7708' # opening up connection, grabbing page uclient = ureq(url2) html = uclient.read() uclient.close() # html parsing page_soup = soup(html, "html.parser") #grabs each product containers = page_soup.findAll("div", {"class": "item-container"}) #print(containers[15].div.div.a.img["title"]) for number, container in enumerate(containers): print("---", number, "---") #if container.div.div.a.img: # brand = container.div.div.a.img["title"] #else: # brand = '???' brand = container.div.find("img", {"title": True})["title"] product_name = container.find("a", {"class": "item-title"}).text shipping = container.find("li", {"class": "price-ship"}).text.strip() print(brand) print(product_name) print(shipping)
concordia/migrations/0004_auto_20181010_1715.py
juliecentofanti172/juliecentofanti.github.io
134
11124523
# Generated by Django 2.0.9 on 2018-10-10 17:15 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("concordia", "0003_auto_20181004_2103"), ] operations = [ migrations.RemoveField(model_name="asset", name="status"), migrations.RemoveField(model_name="campaign", name="status"), migrations.RemoveField(model_name="item", name="status"), migrations.RemoveField(model_name="project", name="status"), migrations.RemoveField(model_name="transcription", name="status"), migrations.AddField( model_name="asset", name="published", field=models.BooleanField(default=False), ), migrations.AddField( model_name="asset", name="transcription_status", field=models.CharField( choices=[ ("edit", "Open for Edit"), ("submitted", "Submitted for Review"), ("completed", "Completed"), ], default="edit", editable=False, max_length=10, ), ), migrations.AddField( model_name="transcription", name="accepted", field=models.DateTimeField(blank=True, null=True), ), migrations.AddField( model_name="transcription", name="rejected", field=models.DateTimeField(blank=True, null=True), ), migrations.AddField( model_name="transcription", name="reviewed_by", field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="transcription_reviewers", to=settings.AUTH_USER_MODEL, ), ), migrations.AddField( model_name="transcription", name="submitted", field=models.DateTimeField( blank=True, help_text="Timestamp when the creator submitted this for review", null=True, ), ), migrations.AddField( model_name="transcription", name="supersedes", field=models.ForeignKey( blank=True, help_text="A previous transcription record which is replaced by this one", # NOQA null=True, on_delete=django.db.models.deletion.CASCADE, to="concordia.Transcription", ), ), ]
benchmarks/_bench/robust_plot_synthetic.py
rth/scikit-learn-extra
120
11124529
""" ================================================================== Plot of accuracy and time as sample_size and num_features increase ================================================================== We show that the increase in computation time is linear when increasing the number of features or the sample size increases. """ import matplotlib.pyplot as plt import numpy as np from time import time from sklearn_extra.robust import RobustWeightedEstimator from sklearn.linear_model import SGDClassifier from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score rng = np.random.RandomState(42) x_label = "Number of features" dimensions = np.linspace(50, 5000, num=8).astype(int) sample_sizes = np.linspace(50, 5000, num=8).astype(int) accuracies = [] times = [] # Get the accuracy and time of computations for a dataset with varying number # of features for d in dimensions: # Make an example in dimension d. Use a scale factor for the problem to be # easy even in high dimension. X, y = make_classification( n_samples=200, n_features=d, scale=1 / np.sqrt(2 * d), random_state=rng ) stime = time() clf = RobustWeightedEstimator( SGDClassifier(loss="hinge", penalty="l1"), loss="hinge", random_state=rng, ) accuracies.append(np.mean(cross_val_score(clf, X, y, cv=10))) times.append(time() - stime) fig, axs = plt.subplots(2, 2) axs[0, 0].plot(dimensions, accuracies) axs[0, 0].set_xlabel(x_label) axs[0, 0].set_ylabel("accuracy") axs[0, 1].plot(dimensions, times) axs[0, 1].set_xlabel(x_label) axs[0, 1].set_ylabel("Time to fit and predict (s)") accuracies = [] times = [] # Get the accuracy and time of computations for a dataset with varying number # of samples for n in sample_sizes: X, y = make_classification(n_samples=n, n_features=5, random_state=rng) stime = time() clf = RobustWeightedEstimator( SGDClassifier(loss="hinge", penalty="l1"), loss="hinge", random_state=rng, ) accuracies.append(np.mean(cross_val_score(clf, X, y, cv=10))) times.append(time() - stime) axs[1, 0].plot(dimensions, accuracies) axs[1, 0].set_xlabel(x_label) axs[1, 0].set_ylabel("accuracy") axs[1, 1].plot(dimensions, times) axs[1, 1].set_xlabel(x_label) axs[1, 1].set_ylabel("Time to fit and predict (s)") plt.show()
manga_py/providers/mangahi_net.py
sonvt1710/manga-py
337
11124561
<reponame>sonvt1710/manga-py from .zmanga_net import ZMangaNet class MangaHiNet(ZMangaNet): _type = 'chapter' main = MangaHiNet
samples/invoice/third_party_invoicing.py
Hey-Marvelous/PayPal-Python-SDK
653
11124573
from paypalrestsdk import Invoice import logging from paypalrestsdk.openid_connect import Tokeninfo logging.basicConfig(level=logging.INFO) # Using Log In with PayPal, third party merchants can authorize your application to create and submit invoices on their behalf. # See https://developer.paypal.com/docs/integration/direct/identity/log-in-with-paypal/ for more details about Log In with PayPal. # Step 1. Generate a Log In with PayPal authorization URL. The third party merchant will need to visit this URL and authorize your request. You should use the `openid`, `https://uri.paypal.com/services/invoicing`, and `email` scopes at the minimum. # paypalrestsdk.configure({'openid_client_id': 'CLIENT_ID', 'openid_client_secret': 'CLIENT_SECRET', 'openid_redirect_uri': 'http://example.com'}) # login_url = Tokeninfo.authorize_url({'scope': 'openid profile'}) # For example, the URL to redirect the third party merchant may be like: # https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id=AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS&scope=openid%20https%3A%2F%2Furi.paypal.com%2Fservices%2Finvoicing%20email&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fpaypal%2FPayPal-PHP-SDK%2Fsample%2Flipp%2FUserConsentRedirect.php%3Fsuccess%3Dtrue # Step 2. After the third party merchant authorizes your request, Log In with PayPal will redirect the browser to your configured openid_redirect_uri with an authorization code query parameter value. # For example, after the merchant successfully authorizes your request, they will be redirected to the merchant's website configured via `openid_redirect_uri` like: # http://localhost/paypal/PayPal-Python-SDK/sample/UserConsentRedirect.php?success=true&scope=https%3A%2F%2Furi.paypal.com%2Fservices%2Finvoicing+openid+email&code=<KEY> # Step 3. Your web app should parse the query parameters for the authorization `code` value. You should use the `code` value to get a refresh token and securely save it for later use. #begin # authorization_code = "<KEY>" # tokeninfo = Tokeninfo.create(code) # print(tokeninfo) # # Response 200 # tokeninfo = { # token_type: 'Bearer', # expires_in: '28800', # refresh_token: '<KEY>', # id_token: '<some value>', # access_token: '<some value>' # } #end # Step 4. You can use the refresh token to get the third party merchant's email address to use in the invoice, and then you can create an invoice on behalf of the third party merchant. refresh_token = "<KEY>" token_info = Tokeninfo.create_with_refresh_token(refresh_token) print(token_info) user_info = token_info.userinfo() print(user_info) invoice = Invoice({ "merchant_info": { # The email address used here would be of a third party. "email": user_info.email, "first_name": "Dennis", "last_name": "Doctor", "business_name": "Medical Professionals, LLC", "phone": { "country_code": "001", "national_number": "5032141716" }, "address": { "line1": "1234 Main St.", "city": "Portland", "state": "OR", "postal_code": "97217", "country_code": "US" } }, "billing_info": [{"email": "<EMAIL>"}], "items": [ { "name": "Sutures", "quantity": 50, "unit_price": { "currency": "USD", "value": 5 } } ], "note": "Medical Invoice 16 Jul, 2013 PST", "payment_term": { "term_type": "NET_45" }, "shipping_info": { "first_name": "Sally", "last_name": "Patient", "business_name": "Not applicable", "phone": { "country_code": "001", "national_number": "5039871234" }, "address": { "line1": "1234 Broad St.", "city": "Portland", "state": "OR", "postal_code": "97216", "country_code": "US" } } }) if invoice.create(refresh_token): print("Third Party Invoice[%s] created successfully" % (invoice.id)) # Fetch the resource similarly as shown below: result = Invoice.find(invoice.id, refresh_token=refresh_token) print("Invoice Detail: %s" % result) else: print(invoice.error)
convlab2/laug/Speech_Recognition/TTS.py
ljw23/ConvLab-2
339
11124610
#coding: UTF-8 from gtts import gTTS from pydub.audio_segment import AudioSegment import os def text2wav(text,language='en',filename='temp',tld='cn'): gTTS(text=text, tld=tld,lang=language).save(filename+".mp3") AudioSegment.from_mp3(filename+".mp3").set_frame_rate(16000).export(filename+".wav", format="wav")
packages/pyright-internal/src/tests/samples/descriptor2.py
Microsoft/pyright
3,934
11124611
<filename>packages/pyright-internal/src/tests/samples/descriptor2.py # This sample validates that a member's descriptor protocol is # accessed via a member access expression only when accessing it # through a class variable, not through an instance variable. from typing import Any class Descriptor: def __get__(self, obj: Any, objtype: Any = None) -> float: return 1.0 class ClassA: x: Descriptor def __init__(self, x: Descriptor): reveal_type(self.x, expected_type="float") def func1(self): reveal_type(self.x, expected_type="float") class ClassB: def __init__(self, x: Descriptor): self.x = x reveal_type(self.x, expected_type="Descriptor") def func1(self): reveal_type(self.x, expected_type="Descriptor")
src/commands/refactor/extract_variable.py
PranjalPansuriya/JavaScriptEnhancements
690
11124644
import sublime, sublime_plugin import os from ...libs import util from ...libs import FlowCLI class JavascriptEnhancementsRefactorExtractVariableCommand(sublime_plugin.TextCommand): def run(self, edit, **args): view = self.view selection = view.sel()[0] contents = view.substr(selection).strip() contents = contents[:-1] if contents[-1] == ";" else contents variable_name = "new_var" flow_cli = FlowCLI(view) result = flow_cli.ast(contents=contents) if result[0] and not result[1]["errors"] and result[1]["body"] and "type" in result[1]["body"][0] and result[1]["body"][0]["type"] == "ExpressionStatement": result = flow_cli.ast() if result[0]: if "body" in result[1]: body = result[1]["body"] items = util.nested_lookup("type", ["BlockStatement"], body) last_block_statement = None last_item = None region = None for item in items: region = sublime.Region(int(item["range"][0]), int(item["range"][1])) if region.contains(selection): last_block_statement = region last_item = item if last_block_statement: for item in last_item["body"]: r = sublime.Region(int(item["range"][0]), int(item["range"][1])) if r.contains(selection): region = r break else: for item in body: r = sublime.Region(int(item["range"][0]), int(item["range"][1])) if r.contains(selection): region = r break if region: prev_line_is_empty = util.prev_line_is_empty(view, region) space = util.get_whitespace_from_line_begin(view, region) str_assignement = ("\n" + space if not prev_line_is_empty else "") + "let " + variable_name + " = " + contents + "\n" + space view.erase(edit, selection) view.insert(edit, selection.begin(), variable_name) view.insert(edit, region.begin(), str_assignement) view.sel().clear() view.sel().add_all([ sublime.Region( selection.begin()+len(str_assignement), selection.begin()+len(str_assignement)+len(variable_name) ), sublime.Region( region.begin() + len(("\n" + space if not prev_line_is_empty else "") + "let "), region.begin() + len(("\n" + space if not prev_line_is_empty else "") + "let ") + len(variable_name) ) ]) variable_kind = ["let", "const", "var"] whitespace_length = len("\n" + space if not prev_line_is_empty else "") view.window().show_quick_panel(variable_kind, None, 0, 0, lambda index: self.view.run_command("javascript_enhancements_replace_text_view", args={"start": region.begin() + whitespace_length, "end": region.begin() + whitespace_length + len(view.substr(view.word(region.begin() + whitespace_length))) , "text": variable_kind[index]})) else: sublime.error_message("Cannot introduce variable. Some problems occured.") else: sublime.error_message("Cannot introduce variable. Selection does not form an ExpressionStatement.") def is_enabled(self, **args) : view = self.view if not util.selection_in_js_scope(view) : return False selection = view.sel()[0] return selection.begin() != selection.end() def is_visible(self, **args) : view = self.view if not util.selection_in_js_scope(view) : return False selection = view.sel()[0] return selection.begin() != selection.end()
assembler.py
zshift/chungus-2-assembler
183
11124652
<reponame>zshift/chungus-2-assembler from os import path from typing import List, Tuple import formats from schem import generate_schematic ############################################################################### # assembler ############################################################################### class AssemblyError(Exception): pass def get_operands(line: str) -> Tuple[str, List[str]]: """Get the opcode and operands of an assembly line""" opcode = line.split(" ")[0] operands = line[len(opcode) + 1:].replace(",", "") operands = operands.split() if operands else [] return (opcode, operands) def to_decimal(number: str) -> int: """Convert other bases to decimal""" if number[0:2] == "0b": # binary return int(number[2:], 2) if number[0:2] == "0x": # hex return int(number[2:], 16) if number[0:2] == "0o": # octal return int(number[2:], 8) if number[0:2] == "0d": # decimal return int(number[2:], 10) # default - decimal return int(number) def get_binary(number: int, length: int) -> str: """Convert a decimal number to signed binary number of given length""" if number < 0: # use 2's complement number = 2 ** length + number result = str(bin(number))[2:] # result over the maximum allowed size if len(result) > length: raise AssemblyError(f"Number too long for {length} bits: {number}") return result.zfill(length) def parse_immediate(immediate: str, length: int) -> str: """Get the binary representation of an immediate value""" # ASCII character if immediate[0] == '"': return get_binary(ord(immediate[1].replace("@", " ")), length) # remove prefix e.g. "M10" (for memory address 10) -> "10" if not immediate[0] in "-0123456789": immediate = immediate[1:] # make sure immediate is an integer try: immediateindex = to_decimal(immediate) except ValueError: raise AssemblyError(f"Invalid immediate: {immediate}") else: # the immediate may be too long (for example in branch instructions) # so take it mod 2 ^ length return get_binary(immediateindex % (2 ** length), length) def parse_register(register: str) -> str: """Get the binary representation of a register""" # make sure it is actually a register if not (len(register) == 2 and register[0] in ("$", "R")): raise AssemblyError(f"Invalid register: {register}") # make sure register is valid try: registerindex = to_decimal(register[1:]) except ValueError: raise AssemblyError(f"Invalid register: {register}") if registerindex > 7: raise AssemblyError(f"Invalid register: {register}") return get_binary(registerindex, 3) def parse_line(line: str) -> str: """Translate an assembly instruction to machine code""" opcode, operands = get_operands(line) # get base instruction base = formats.ALIAS.get(opcode, opcode) if base not in formats.FORMATS: raise AssemblyError(f"Invalid opcode: {opcode}") result = "" for operand in formats.FORMATS[base]: if operand == "REG": # register - assume R0 if not given result += parse_register(operands.pop(0)) if operands else "000" elif operand[0:3] == "IMM": # fixed length immediate - default 0 length = int(operand.split("_")[1]) if not operands: result += "0" * length else: result += parse_immediate(operands.pop(0), length) elif operand == "BITS": # operand depends on the opcode result += formats.BITS[opcode] elif operand == "OPERAND": # control bits (required) if not operands: raise AssemblyError("Not enough operands") if not operands[0] in formats.OPERANDS: raise AssemblyError(f"Unknown operand: {operands[0]}") result += formats.OPERANDS[operands.pop(0)] else: # fixed operand for the instruction result += operand return result ############################################################################### # cleanup code ############################################################################### def remove_comments(lines: List[str]) -> List[str]: """Remove comments and empty lines""" formatlines = [] for line in lines: # comment if "//" in line: formatlines.append(line[:line.index("//")].strip()) # ignore blank lines elif line: formatlines.append(line) return formatlines def parse_pages(lines: List[str]) -> List[str]: """Add NOPs between pages to keep size 64""" # (prevent 64 NOPs at the start of program) if lines[0] == ".PAGE:0": lines.pop(0) instructioncount = 0 formatlines = [] for line in lines: # if a new page is found and the last one is not full, fill with NOPs # which assemble to 00000000 if line[0:6] == ".PAGE:": formatlines.extend(["NOP" for i in range(64 - instructioncount)]) instructioncount = 0 # otherwise add to formatlines else: formatlines.append(line) # ignore labels in instruction count if line[0] != ".": instructioncount += 1 return formatlines def parse_labels(lines: List[str]) -> List[str]: """Turn labels into immediate values""" def is_label(line): # check if a given line is a label line = line.strip() return line and line[0] == "." labels = {} linenum = 0 # find all labels and their line numbers while linenum < len(lines): if is_label(lines[linenum]): # add to label dict and remove from lines labels[lines[linenum].strip()] = str(linenum) lines.pop(linenum) else: linenum += 1 # convert labels to immediates formatlines = [] for line in lines: if not line: # blank line (should be cleaned up?) continue # get operands - NOTE: you cannot just replace labels, because there # could be a ".test" label but also a ".test2" label, and the first # would overwrite the second. opcode, operands = get_operands(line.strip()) operands = [labels.get(operand, operand) for operand in operands] # turn back into a formatted assembly instruction formatlines.append(opcode + " " + ", ".join(operands)) return formatlines def cleanup(lines: List[str]) -> List[str]: """Clean up assembly code and parse labels""" lines = remove_comments(lines) lines = parse_pages(lines) lines = parse_labels(lines) return lines ############################################################################### # file management ############################################################################### def read_file(filepath: str) -> List[str]: """Read an assembly file and remove comments""" with open(filepath, "r") as f: lines = [line.strip() for line in f] lines = remove_comments(lines) return lines def write_file(filepath: str, lines: List[str]) -> None: """Write a machine code file""" with open(filepath, "w") as f: for line in lines: f.write(line + "\n") ############################################################################### # io ############################################################################### def assemble(lines: List[str]) -> List[str]: """Translate a list of assembly instructions to machine code""" result = [] lines = cleanup(lines) for linenumber, line in enumerate(lines): try: machinecode = parse_line(line) except AssemblyError as error: # format error message errorcode = f"Error on line {linenumber}: {error}" raise AssemblyError(errorcode) from None else: result.append(machinecode) return format_assembly(result) def assemble_file(filepath: str) -> None: """Assemble an assembly file to a machine code file""" lines = read_file(filepath) lines = assemble(lines) # get resulting file name filename = path.splitext(filepath)[0] + ".txt" write_file(filename, lines) # also create a schematic to run on the Minecraft hardware generate_schematic( [line[0:8] + line[9:17] for line in lines], path.splitext(filepath)[0] + "_CHUNGUS2" ) def format_assembly(lines: List[str]) -> List[str]: """Split assembly instructions into 2 bytes""" return [line[0:8] + " " + line[8:16] for line in lines] if __name__ == "__main__": filepath = input("Enter file path: ") assemble_file(filepath)
dagda/remote/agent.py
hoominkani/dagda
947
11124673
# # Licensed to Dagda under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Dagda licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import json import requests from analysis.analyzer import Analyzer # Dagda remote agent class class Agent: # -- Public methods # Agent Constructor def __init__(self, dagda_server_url): super(Agent, self).__init__() self.dagda_server_url = dagda_server_url self.analyzer = Analyzer(dagda_server_url=dagda_server_url) def run_static_analysis(self, image_name=None, container_id=None): evaluated_docker_image = self.analyzer.evaluate_image(image_name=image_name, container_id=container_id) docker_image_name = evaluated_docker_image['image_name'] r = requests.post(self.dagda_server_url + '/history/' + docker_image_name, data=json.dumps(evaluated_docker_image), headers={'content-type': 'application/json'}) # -- Print cmd output if r is not None and r.content: print(json.dumps(json.loads(r.content.decode('utf-8')), sort_keys=True, indent=4))
text-generation/tests/test_text_generator.py
dumpmemory/serverless-transformers-on-aws-lambda
103
11124694
from src.text_generator import TextGenerator pipeline = TextGenerator() def test_response(requests, response): assert response == pipeline(requests)
econml/dynamic/dml/__init__.py
imatiach-msft/EconML
1,846
11124720
<gh_stars>1000+ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Double Machine Learning for Dynamic Treatment Effects. A Double/Orthogonal machine learning approach to estimation of heterogeneous treatment effect in the dynamic treatment regime. For the theoretical foundations of these methods see: [dynamicdml]_. References ---------- .. [dynamicdml] <NAME> and <NAME>. Double/Debiased Machine Learning for Dynamic Treatment Effects. `<https://arxiv.org/abs/2002.07285>`_, 2021. """ from ._dml import DynamicDML __all__ = ["DynamicDML"]
pytorch-DRIT-PONO-MS/src/model_pono.py
Boyiliee/PONO
133
11124730
import networks_pono as networks import torch import torch.nn as nn import torch.nn.functional as F class DRIT(nn.Module): def __init__(self, opts): super(DRIT, self).__init__() # parameters lr = 0.0001 lr_dcontent = lr / 2.5 self.nz = 8 self.concat = opts.concat self.arch = opts.arch self.vgg_w = opts.vgg_w if self.vgg_w > 0.: self.vgg = networks.VGG19(init_weights='/home/fw245/share/public/vgg19.pth', feature_mode=True) self.vgg.eval() for param in self.vgg.parameters(): param.requires_grad = False else: self.vgg = None # discriminators if opts.dis_scale > 1: self.disA = networks.MultiScaleDis(opts.input_dim_a, opts.dis_scale, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disB = networks.MultiScaleDis(opts.input_dim_b, opts.dis_scale, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disA2 = networks.MultiScaleDis(opts.input_dim_a, opts.dis_scale, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disB2 = networks.MultiScaleDis(opts.input_dim_b, opts.dis_scale, norm=opts.dis_norm, sn=opts.dis_spectral_norm) else: self.disA = networks.Dis(opts.input_dim_a, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disB = networks.Dis(opts.input_dim_b, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disA2 = networks.Dis(opts.input_dim_a, norm=opts.dis_norm, sn=opts.dis_spectral_norm) self.disB2 = networks.Dis(opts.input_dim_b, norm=opts.dis_norm, sn=opts.dis_spectral_norm) if self.arch in {'drit_pono_ms'}: self.with_stats = True self.disContent = networks.Dis_content_pono_ms(n_stats=3) else: self.with_stats = False self.disContent = networks.Dis_content() # encoders if self.arch in {'drit_pono_ms'}: self.enc_c = networks.E_content_pono_ms(opts.input_dim_a, opts.input_dim_b) else: self.enc_c = networks.E_content(opts.input_dim_a, opts.input_dim_b) # enc_a if self.concat: self.enc_a = networks.E_attr_concat(opts.input_dim_a, opts.input_dim_b, self.nz, \ norm_layer=None, nl_layer=networks.get_non_linearity(layer_type='lrelu')) else: self.enc_a = networks.E_attr(opts.input_dim_a, opts.input_dim_b, self.nz) # generator if self.concat: if self.arch in {'drit'}: self.gen = networks.G_concat(opts.input_dim_a, opts.input_dim_b, nz=self.nz) elif self.arch in {'drit_pono_ms'}: self.gen = networks.G_concat_pono_ms(opts.input_dim_a, opts.input_dim_b, nz=self.nz) else: raise ValueError(self.arch) else: if self.arch in {'drit'}: self.gen = networks.G(opts.input_dim_a, opts.input_dim_b, nz=self.nz) elif self.arch in {'drit_pono_ms'}: self.gen = networks.G_pono_ms(opts.input_dim_a, opts.input_dim_b, nz=self.nz) else: raise ValueError(self.arch) # optimizers self.disA_opt = torch.optim.Adam(self.disA.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.disB_opt = torch.optim.Adam(self.disB.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.disA2_opt = torch.optim.Adam(self.disA2.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.disB2_opt = torch.optim.Adam(self.disB2.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.disContent_opt = torch.optim.Adam(self.disContent.parameters(), lr=lr_dcontent, betas=(0.5, 0.999), weight_decay=0.0001) self.enc_c_opt = torch.optim.Adam(self.enc_c.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.enc_a_opt = torch.optim.Adam(self.enc_a.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) self.gen_opt = torch.optim.Adam(self.gen.parameters(), lr=lr, betas=(0.5, 0.999), weight_decay=0.0001) # Setup the loss function for training self.criterionL1 = torch.nn.L1Loss() def initialize(self): self.disA.apply(networks.gaussian_weights_init) self.disB.apply(networks.gaussian_weights_init) self.disA2.apply(networks.gaussian_weights_init) self.disB2.apply(networks.gaussian_weights_init) self.disContent.apply(networks.gaussian_weights_init) self.gen.apply(networks.gaussian_weights_init) self.enc_c.apply(networks.gaussian_weights_init) self.enc_a.apply(networks.gaussian_weights_init) def set_scheduler(self, opts, last_ep=0): self.disA_sch = networks.get_scheduler(self.disA_opt, opts, last_ep) self.disB_sch = networks.get_scheduler(self.disB_opt, opts, last_ep) self.disA2_sch = networks.get_scheduler(self.disA2_opt, opts, last_ep) self.disB2_sch = networks.get_scheduler(self.disB2_opt, opts, last_ep) self.disContent_sch = networks.get_scheduler(self.disContent_opt, opts, last_ep) self.enc_c_sch = networks.get_scheduler(self.enc_c_opt, opts, last_ep) self.enc_a_sch = networks.get_scheduler(self.enc_a_opt, opts, last_ep) self.gen_sch = networks.get_scheduler(self.gen_opt, opts, last_ep) def setgpu(self, gpu): self.gpu = gpu self.disA.cuda(self.gpu) self.disB.cuda(self.gpu) self.disA2.cuda(self.gpu) self.disB2.cuda(self.gpu) self.disContent.cuda(self.gpu) self.enc_c.cuda(self.gpu) self.enc_a.cuda(self.gpu) self.gen.cuda(self.gpu) if self.vgg is not None: self.vgg.cuda(self.gpu) def get_z_random(self, batchSize, nz, random_type='gauss'): z = torch.randn(batchSize, nz).cuda(self.gpu) return z def test_forward(self, image, a2b=True): self.z_random = self.get_z_random(image.size(0), self.nz, 'gauss') if a2b: self.z_content = self.enc_c.forward_a(image) output = self.gen.forward_b(self.z_content, self.z_random) else: self.z_content = self.enc_c.forward_b(image) output = self.gen.forward_a(self.z_content, self.z_random) return output def test_forward_transfer(self, image_a, image_b, a2b=True): self.z_content_a, self.z_content_b = self.enc_c.forward(image_a, image_b) if self.concat: self.mu_a, self.logvar_a, self.mu_b, self.logvar_b = self.enc_a.forward(image_a, image_b) std_a = self.logvar_a.mul(0.5).exp_() eps = self.get_z_random(std_a.size(0), std_a.size(1), 'gauss') self.z_attr_a = eps.mul(std_a).add_(self.mu_a) std_b = self.logvar_b.mul(0.5).exp_() eps = self.get_z_random(std_b.size(0), std_b.size(1), 'gauss') self.z_attr_b = eps.mul(std_b).add_(self.mu_b) else: self.z_attr_a, self.z_attr_b = self.enc_a.forward(image_a, image_b) if a2b: output = self.gen.forward_b(self.z_content_a, self.z_attr_b) else: output = self.gen.forward_a(self.z_content_b, self.z_attr_a) return output def forward(self): # input images half_size = 1 real_A = self.input_A real_B = self.input_B self.real_A_encoded = real_A[0:half_size] self.real_A_random = real_A[half_size:] self.real_B_encoded = real_B[0:half_size] self.real_B_random = real_B[half_size:] # get encoded z_c self.z_content_a, self.z_content_b = self.enc_c.forward(self.real_A_encoded, self.real_B_encoded) # get encoded z_a if self.concat: self.mu_a, self.logvar_a, self.mu_b, self.logvar_b = self.enc_a.forward(self.real_A_encoded, self.real_B_encoded) std_a = self.logvar_a.mul(0.5).exp_() eps_a = self.get_z_random(std_a.size(0), std_a.size(1), 'gauss') self.z_attr_a = eps_a.mul(std_a).add_(self.mu_a) std_b = self.logvar_b.mul(0.5).exp_() eps_b = self.get_z_random(std_b.size(0), std_b.size(1), 'gauss') self.z_attr_b = eps_b.mul(std_b).add_(self.mu_b) else: self.z_attr_a, self.z_attr_b = self.enc_a.forward(self.real_A_encoded, self.real_B_encoded) # get random z_a self.z_random = self.get_z_random(self.real_A_encoded.size(0), self.nz, 'gauss') # first cross translation if self.with_stats: input_content_forA = ( torch.cat((self.z_content_b[0], self.z_content_a[0], self.z_content_b[0]), 0), [ (torch.cat((self.z_content_b[1][i][0], self.z_content_a[1][i][0], self.z_content_b[1][i][0]), 0), torch.cat((self.z_content_b[1][i][1], self.z_content_a[1][i][1], self.z_content_b[1][i][1]), 0)) for i in range(len(self.z_content_b[1])) ], ) input_content_forB = ( torch.cat((self.z_content_a[0], self.z_content_b[0], self.z_content_a[0]), 0), [ (torch.cat((self.z_content_a[1][i][0], self.z_content_b[1][i][0], self.z_content_a[1][i][0]), 0), torch.cat((self.z_content_a[1][i][1], self.z_content_b[1][i][1], self.z_content_a[1][i][1]), 0)) for i in range(len(self.z_content_b[1])) ], ) else: input_content_forA = torch.cat((self.z_content_b, self.z_content_a, self.z_content_b),0) input_content_forB = torch.cat((self.z_content_a, self.z_content_b, self.z_content_a),0) input_attr_forA = torch.cat((self.z_attr_a, self.z_attr_a, self.z_random),0) input_attr_forB = torch.cat((self.z_attr_b, self.z_attr_b, self.z_random),0) output_fakeA = self.gen.forward_a(input_content_forA, input_attr_forA) output_fakeB = self.gen.forward_b(input_content_forB, input_attr_forB) if self.with_stats: self.fake_A_encoded, self.fake_AA_encoded, self.fake_A_random = torch.split(output_fakeA, self.z_content_a[0].size(0), dim=0) self.fake_B_encoded, self.fake_BB_encoded, self.fake_B_random = torch.split(output_fakeB, self.z_content_a[0].size(0), dim=0) else: self.fake_A_encoded, self.fake_AA_encoded, self.fake_A_random = torch.split(output_fakeA, self.z_content_a.size(0), dim=0) self.fake_B_encoded, self.fake_BB_encoded, self.fake_B_random = torch.split(output_fakeB, self.z_content_a.size(0), dim=0) # get reconstructed encoded z_c self.z_content_recon_b, self.z_content_recon_a = self.enc_c.forward(self.fake_A_encoded, self.fake_B_encoded) # get reconstructed encoded z_a if self.concat: self.mu_recon_a, self.logvar_recon_a, self.mu_recon_b, self.logvar_recon_b = self.enc_a.forward(self.fake_A_encoded, self.fake_B_encoded) std_a = self.logvar_recon_a.mul(0.5).exp_() eps_a = self.get_z_random(std_a.size(0), std_a.size(1), 'gauss') self.z_attr_recon_a = eps_a.mul(std_a).add_(self.mu_recon_a) std_b = self.logvar_recon_b.mul(0.5).exp_() eps_b = self.get_z_random(std_b.size(0), std_b.size(1), 'gauss') self.z_attr_recon_b = eps_b.mul(std_b).add_(self.mu_recon_b) else: self.z_attr_recon_a, self.z_attr_recon_b = self.enc_a.forward(self.fake_A_encoded, self.fake_B_encoded) # second cross translation self.fake_A_recon = self.gen.forward_a(self.z_content_recon_a, self.z_attr_recon_a) self.fake_B_recon = self.gen.forward_b(self.z_content_recon_b, self.z_attr_recon_b) # for display self.image_display = torch.cat((self.real_A_encoded[0:1].detach().cpu(), self.fake_B_encoded[0:1].detach().cpu(), \ self.fake_B_random[0:1].detach().cpu(), self.fake_AA_encoded[0:1].detach().cpu(), self.fake_A_recon[0:1].detach().cpu(), \ self.real_B_encoded[0:1].detach().cpu(), self.fake_A_encoded[0:1].detach().cpu(), \ self.fake_A_random[0:1].detach().cpu(), self.fake_BB_encoded[0:1].detach().cpu(), self.fake_B_recon[0:1].detach().cpu()), dim=0) # for latent regression if self.concat: self.mu2_a, _, self.mu2_b, _ = self.enc_a.forward(self.fake_A_random, self.fake_B_random) else: self.z_attr_random_a, self.z_attr_random_b = self.enc_a.forward(self.fake_A_random, self.fake_B_random) def forward_content(self): half_size = 1 self.real_A_encoded = self.input_A[0:half_size] self.real_B_encoded = self.input_B[0:half_size] # get encoded z_c self.z_content_a, self.z_content_b = self.enc_c.forward(self.real_A_encoded, self.real_B_encoded) def update_D_content(self, image_a, image_b): self.input_A = image_a self.input_B = image_b self.forward_content() self.disContent_opt.zero_grad() loss_D_Content = self.backward_contentD(self.z_content_a, self.z_content_b) self.disContent_loss = loss_D_Content.item() nn.utils.clip_grad_norm_(self.disContent.parameters(), 5) self.disContent_opt.step() def update_D(self, image_a, image_b): self.input_A = image_a self.input_B = image_b self.forward() # update disA self.disA_opt.zero_grad() loss_D1_A = self.backward_D(self.disA, self.real_A_encoded, self.fake_A_encoded) self.disA_loss = loss_D1_A.item() self.disA_opt.step() # update disA2 self.disA2_opt.zero_grad() loss_D2_A = self.backward_D(self.disA2, self.real_A_random, self.fake_A_random) self.disA2_loss = loss_D2_A.item() self.disA2_opt.step() # update disB self.disB_opt.zero_grad() loss_D1_B = self.backward_D(self.disB, self.real_B_encoded, self.fake_B_encoded) self.disB_loss = loss_D1_B.item() self.disB_opt.step() # update disB2 self.disB2_opt.zero_grad() loss_D2_B = self.backward_D(self.disB2, self.real_B_random, self.fake_B_random) self.disB2_loss = loss_D2_B.item() self.disB2_opt.step() # update disContent self.disContent_opt.zero_grad() loss_D_Content = self.backward_contentD(self.z_content_a, self.z_content_b) self.disContent_loss = loss_D_Content.item() nn.utils.clip_grad_norm_(self.disContent.parameters(), 5) self.disContent_opt.step() def backward_D(self, netD, real, fake): pred_fake = netD.forward(fake.detach()) pred_real = netD.forward(real) loss_D = 0 for it, (out_a, out_b) in enumerate(zip(pred_fake, pred_real)): out_fake = torch.sigmoid(out_a) out_real = torch.sigmoid(out_b) all0 = torch.zeros_like(out_fake).cuda(self.gpu) all1 = torch.ones_like(out_real).cuda(self.gpu) ad_fake_loss = nn.functional.binary_cross_entropy(out_fake, all0) ad_true_loss = nn.functional.binary_cross_entropy(out_real, all1) loss_D += ad_true_loss + ad_fake_loss loss_D.backward() return loss_D def backward_contentD(self, imageA, imageB): if self.with_stats: # import pdb; pdb.set_trace() imageA = (imageA[0].detach(), [(imageA[1][i][0].detach(), imageA[1][i][1].detach()) for i in range(len(imageA[1]))]) imageB = (imageB[0].detach(), [(imageB[1][i][0].detach(), imageB[1][i][1].detach()) for i in range(len(imageB[1]))]) else: imageA, imageB = imageA.detach(), imageB.detach() pred_fake = self.disContent.forward(imageA) pred_real = self.disContent.forward(imageB) for it, (out_a, out_b) in enumerate(zip(pred_fake, pred_real)): out_fake = torch.sigmoid(out_a) out_real = torch.sigmoid(out_b) all1 = torch.ones((out_real.size(0))).cuda(self.gpu) all0 = torch.zeros((out_fake.size(0))).cuda(self.gpu) ad_true_loss = nn.functional.binary_cross_entropy(out_real, all1) ad_fake_loss = nn.functional.binary_cross_entropy(out_fake, all0) loss_D = ad_true_loss + ad_fake_loss loss_D.backward() return loss_D def update_EG(self): # update G, Ec, Ea self.enc_c_opt.zero_grad() self.enc_a_opt.zero_grad() self.gen_opt.zero_grad() self.backward_EG() self.enc_c_opt.step() self.enc_a_opt.step() self.gen_opt.step() # update G, Ec self.enc_c_opt.zero_grad() self.gen_opt.zero_grad() self.backward_G_alone() self.enc_c_opt.step() self.gen_opt.step() def backward_EG(self): # content Ladv for generator loss_G_GAN_Acontent = self.backward_G_GAN_content(self.z_content_a) loss_G_GAN_Bcontent = self.backward_G_GAN_content(self.z_content_b) # Ladv for generator loss_G_GAN_A = self.backward_G_GAN(self.fake_A_encoded, self.disA) loss_G_GAN_B = self.backward_G_GAN(self.fake_B_encoded, self.disB) # KL loss - z_a if self.concat: kl_element_a = self.mu_a.pow(2).add_(self.logvar_a.exp()).mul_(-1).add_(1).add_(self.logvar_a) loss_kl_za_a = torch.sum(kl_element_a).mul_(-0.5) * 0.01 kl_element_b = self.mu_b.pow(2).add_(self.logvar_b.exp()).mul_(-1).add_(1).add_(self.logvar_b) loss_kl_za_b = torch.sum(kl_element_b).mul_(-0.5) * 0.01 else: loss_kl_za_a = self._l2_regularize(self.z_attr_a) * 0.01 loss_kl_za_b = self._l2_regularize(self.z_attr_b) * 0.01 # KL loss - z_c if self.with_stats: loss_kl_zc_a = self._l2_regularize(self.z_content_a[0]) * 0.01 # for mean, std in self.z_content_a[1]: # loss_kl_zc_a += (self._l2_regularize(mean) + self._l2_regularize(std)) * 0.001 loss_kl_zc_b = self._l2_regularize(self.z_content_b[0]) * 0.01 # for mean, std in self.z_content_a[1]: # loss_kl_zc_b += (self._l2_regularize(mean) + self._l2_regularize(std)) * 0.001 else: loss_kl_zc_a = self._l2_regularize(self.z_content_a) * 0.01 loss_kl_zc_b = self._l2_regularize(self.z_content_b) * 0.01 # cross cycle consistency loss loss_G_L1_A = self.criterionL1(self.fake_A_recon, self.real_A_encoded) * 10 loss_G_L1_B = self.criterionL1(self.fake_B_recon, self.real_B_encoded) * 10 loss_G_L1_AA = self.criterionL1(self.fake_AA_encoded, self.real_A_encoded) * 10 loss_G_L1_BB = self.criterionL1(self.fake_BB_encoded, self.real_B_encoded) * 10 if self.vgg_w > 0.: loss_vgg_a = self.compute_vgg19_loss(self.vgg, self.fake_A_encoded, self.real_B_encoded) * self.vgg_w loss_vgg_b = self.compute_vgg19_loss(self.vgg, self.fake_B_encoded, self.real_A_encoded) * self.vgg_w loss_vgg_a_rand = self.compute_vgg19_loss(self.vgg, self.fake_A_random, self.real_B_encoded) * self.vgg_w loss_vgg_b_rand = self.compute_vgg19_loss(self.vgg, self.fake_B_random, self.real_A_encoded) * self.vgg_w else: loss_vgg_a = loss_vgg_b = loss_vgg_a_rand = loss_vgg_b_rand = 0. loss_G = loss_G_GAN_A + loss_G_GAN_B + \ loss_G_GAN_Acontent + loss_G_GAN_Bcontent + \ loss_G_L1_AA + loss_G_L1_BB + \ loss_G_L1_A + loss_G_L1_B + \ loss_kl_zc_a + loss_kl_zc_b + \ loss_kl_za_a + loss_kl_za_b + \ loss_vgg_a + loss_vgg_b + \ loss_vgg_a_rand + loss_vgg_b_rand loss_G.backward(retain_graph=True) self.gan_loss_a = loss_G_GAN_A.item() self.gan_loss_b = loss_G_GAN_B.item() self.gan_loss_acontent = loss_G_GAN_Acontent.item() self.gan_loss_bcontent = loss_G_GAN_Bcontent.item() self.kl_loss_za_a = loss_kl_za_a.item() self.kl_loss_za_b = loss_kl_za_b.item() self.kl_loss_zc_a = loss_kl_zc_a.item() self.kl_loss_zc_b = loss_kl_zc_b.item() self.l1_recon_A_loss = loss_G_L1_A.item() self.l1_recon_B_loss = loss_G_L1_B.item() self.l1_recon_AA_loss = loss_G_L1_AA.item() self.l1_recon_BB_loss = loss_G_L1_BB.item() self.G_loss = loss_G.item() if self.vgg_w > 0.: self.vgg_loss_a = loss_vgg_a.item() self.vgg_loss_b = loss_vgg_b.item() self.vgg_loss_a_rand = loss_vgg_a_rand.item() self.vgg_loss_b_rand = loss_vgg_b_rand.item() def backward_G_GAN_content(self, data): outs = self.disContent.forward(data) for out in outs: outputs_fake = torch.sigmoid(out) all_half = 0.5*torch.ones((outputs_fake.size(0))).cuda(self.gpu) ad_loss = nn.functional.binary_cross_entropy(outputs_fake, all_half) return ad_loss def backward_G_GAN(self, fake, netD=None): outs_fake = netD.forward(fake) loss_G = 0 for out_a in outs_fake: outputs_fake = torch.sigmoid(out_a) all_ones = torch.ones_like(outputs_fake).cuda(self.gpu) loss_G += nn.functional.binary_cross_entropy(outputs_fake, all_ones) return loss_G def backward_G_alone(self): # Ladv for generator loss_G_GAN2_A = self.backward_G_GAN(self.fake_A_random, self.disA2) loss_G_GAN2_B = self.backward_G_GAN(self.fake_B_random, self.disB2) # latent regression loss if self.concat: loss_z_L1_a = torch.mean(torch.abs(self.mu2_a - self.z_random)) * 10 loss_z_L1_b = torch.mean(torch.abs(self.mu2_b - self.z_random)) * 10 else: loss_z_L1_a = torch.mean(torch.abs(self.z_attr_random_a - self.z_random)) * 10 loss_z_L1_b = torch.mean(torch.abs(self.z_attr_random_b - self.z_random)) * 10 loss_z_L1 = loss_z_L1_a + loss_z_L1_b + loss_G_GAN2_A + loss_G_GAN2_B loss_z_L1.backward() self.l1_recon_z_loss_a = loss_z_L1_a.item() self.l1_recon_z_loss_b = loss_z_L1_b.item() self.gan2_loss_a = loss_G_GAN2_A.item() self.gan2_loss_b = loss_G_GAN2_B.item() def update_lr(self): self.disA_sch.step() self.disB_sch.step() self.disA2_sch.step() self.disB2_sch.step() self.disContent_sch.step() self.enc_c_sch.step() self.enc_a_sch.step() self.gen_sch.step() def _l2_regularize(self, mu): mu_2 = torch.pow(mu, 2) encoding_loss = torch.mean(mu_2) return encoding_loss def resume(self, model_dir, train=True): checkpoint = torch.load(model_dir) # weight if train: self.disA.load_state_dict(checkpoint['disA']) self.disA2.load_state_dict(checkpoint['disA2']) self.disB.load_state_dict(checkpoint['disB']) self.disB2.load_state_dict(checkpoint['disB2']) self.disContent.load_state_dict(checkpoint['disContent']) self.enc_c.load_state_dict(checkpoint['enc_c']) self.enc_a.load_state_dict(checkpoint['enc_a']) self.gen.load_state_dict(checkpoint['gen']) # optimizer if train: self.disA_opt.load_state_dict(checkpoint['disA_opt']) self.disA2_opt.load_state_dict(checkpoint['disA2_opt']) self.disB_opt.load_state_dict(checkpoint['disB_opt']) self.disB2_opt.load_state_dict(checkpoint['disB2_opt']) self.disContent_opt.load_state_dict(checkpoint['disContent_opt']) self.enc_c_opt.load_state_dict(checkpoint['enc_c_opt']) self.enc_a_opt.load_state_dict(checkpoint['enc_a_opt']) self.gen_opt.load_state_dict(checkpoint['gen_opt']) return checkpoint['ep'], checkpoint['total_it'] def save(self, filename, ep, total_it): state = { 'disA': self.disA.state_dict(), 'disA2': self.disA2.state_dict(), 'disB': self.disB.state_dict(), 'disB2': self.disB2.state_dict(), 'disContent': self.disContent.state_dict(), 'enc_c': self.enc_c.state_dict(), 'enc_a': self.enc_a.state_dict(), 'gen': self.gen.state_dict(), 'disA_opt': self.disA_opt.state_dict(), 'disA2_opt': self.disA2_opt.state_dict(), 'disB_opt': self.disB_opt.state_dict(), 'disB2_opt': self.disB2_opt.state_dict(), 'disContent_opt': self.disContent_opt.state_dict(), 'enc_c_opt': self.enc_c_opt.state_dict(), 'enc_a_opt': self.enc_a_opt.state_dict(), 'gen_opt': self.gen_opt.state_dict(), 'ep': ep, 'total_it': total_it } torch.save(state, filename) return def assemble_outputs(self): images_a = self.normalize_image(self.real_A_encoded).detach() images_b = self.normalize_image(self.real_B_encoded).detach() images_a1 = self.normalize_image(self.fake_A_encoded).detach() images_a2 = self.normalize_image(self.fake_A_random).detach() images_a3 = self.normalize_image(self.fake_A_recon).detach() images_a4 = self.normalize_image(self.fake_AA_encoded).detach() images_b1 = self.normalize_image(self.fake_B_encoded).detach() images_b2 = self.normalize_image(self.fake_B_random).detach() images_b3 = self.normalize_image(self.fake_B_recon).detach() images_b4 = self.normalize_image(self.fake_BB_encoded).detach() row1 = torch.cat((images_a[0:1, ::], images_b1[0:1, ::], images_b2[0:1, ::], images_a4[0:1, ::], images_a3[0:1, ::]),3) row2 = torch.cat((images_b[0:1, ::], images_a1[0:1, ::], images_a2[0:1, ::], images_b4[0:1, ::], images_b3[0:1, ::]),3) return torch.cat((row1,row2),2) def normalize_image(self, x): return x[:,0:3,:,:] def compute_vgg19_loss(self, vgg, img, target, vgg_type='vgg19'): img_feature = self.vgg((img + 1) / 2) target_feature = self.vgg((target + 1) / 2).detach() return F.l1_loss(img_feature, target_feature)
BRATS/compress_data.py
eanemo/KiU-Net-pytorch
236
11124758
<gh_stars>100-1000 import argparse import os import numpy as np from multiprocessing import Pool def float2uint(file_path): filename = file_path[:file_path.find('.npy')]+'.npz' data_float32 = np.load(file_path) data_temp = 255 * data_float32 data_uint8 = data_temp.astype(np.uint8) print(filename) np.savez_compressed(filename, data=data_uint8) os.remove(file_path) parser = argparse.ArgumentParser() parser.add_argument('-output', '--output', default='/home/pkao/brats2017-master/output', type=str) #parser.add_argument('-output', '--output', default='/media/hdd1/pkao/brats2018/output', type=str) parser.add_argument('-cfg', '--cfg', default='unet_ce_hard', type=str) #parser.add_argument('-mode', '--mode', default='validation', type=str) args = parser.parse_args() #root_dir = os.path.join(args.output, args.mode, args.cfg) root_dir = os.path.join(args.output, args.cfg) #print(root_dir) float32_paths = [os.path.join(root, name) for root, dirs, files in os.walk(root_dir) for name in files if name.endswith('.npy')] assert(len(float32_paths) == 191) pool = Pool(16) pool.map(float2uint, float32_paths)
tests/test_aliases.py
orsinium/condition
311
11124781
from inspect import getdoc from typing import get_type_hints import pytest import deal def get_func(): @deal.pre(lambda x: x > 0) @deal.post(lambda x: x > 0) @deal.ensure(lambda *args, **kwargs: True) @deal.raises(ValueError) @deal.safe @deal.safe() @deal.pure @deal.chain(deal.safe, deal.pure) def func(x: int) -> int: """docs were before docker """ return x return func def test_preserve_type_annotations(): """ IMPORTANT: this checks preserving type annotations in runtime. mypy is a static analyser and can produce a different result. """ func = get_func() annotations = get_type_hints(func) assert set(annotations) == {'x', 'return'} assert annotations['x'] in ('int', int) assert annotations['return'] in ('int', int) def test_preserve_docstring(): func = get_func() docs = getdoc(func) assert docs is not None assert docs.strip() == 'docs were before docker' def test_implies(): @deal.pre(lambda x, y: deal.implies(x, y)) def f(x, y): pass f(True, True) f(False, True) f(False, False) with pytest.raises(deal.PreContractError): f(True, False) def test_catch(): def div(x, y): return x / y assert deal.catch(div, 1, 2) is None assert deal.catch(div, 1, y=2) is None assert deal.catch(div, x=1, y=2) is None assert deal.catch(div, 1, 0) is ZeroDivisionError
vaas-app/src/vaas/external/oauth.py
allegro/vaas
251
11124789
<reponame>allegro/vaas import importlib from django.conf import settings from tastypie.authentication import MultiAuthentication # If Oauth for API is enabled & custom module (OAUTH_AUTH_MODULE) is not present, # default TastyPie OAuthAuthentication backend will be used API_OAUTH_ENABLED = getattr(settings, 'API_OAUTH_ENABLED', False) OAUTH_AUTH_MODULE = getattr(settings, 'OAUTH_AUTH_MODULE', 'tastypie.authentication') if API_OAUTH_ENABLED: oauth_module = importlib.import_module(OAUTH_AUTH_MODULE) OAuthAuthentication = getattr(oauth_module, 'OAuthAuthentication') class VaasMultiAuthentication(MultiAuthentication): def __init__(self, *backends, **kwargs): super(MultiAuthentication, self).__init__(**kwargs) if API_OAUTH_ENABLED: backends = backends + (OAuthAuthentication(),) self.backends = backends
applications/MultilevelMonteCarloApplication/external_libraries/PyCOMPSs/exaqute/common/exception.py
lkusch/Kratos
778
11124802
<reponame>lkusch/Kratos<filename>applications/MultilevelMonteCarloApplication/external_libraries/PyCOMPSs/exaqute/common/exception.py<gh_stars>100-1000 class ExaquteException(Exception): pass
tests/test_repo.py
Bing1012/3
1,040
11124823
<reponame>Bing1012/3 import os import subprocess import sys from pathlib import Path import pytest from pyscaffold import actions, api, cli, repo, shell, structure, toml from pyscaffold.file_system import chdir, move, rm_rf def test_init_commit_repo(tmpfolder): with tmpfolder.mkdir("my_porject").as_cwd(): struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, "dummy": None, } structure.create_structure(struct, {}) dummy_file = Path("dummy") with dummy_file.open(mode="w"): os.utime(str(dummy_file), None) repo.init_commit_repo(".", struct) assert Path(".git").exists() def test_pretend_init_commit_repo(tmpfolder): with tmpfolder.mkdir("my_porject").as_cwd(): struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, "dummy": None, } structure.create_structure(struct, {}) dummy_file = Path("dummy") with dummy_file.open(mode="w"): os.utime(str(dummy_file), None) repo.init_commit_repo(".", struct, pretend=True) assert not Path(".git").exists() def test_init_commit_repo_with_wrong_structure(tmpfolder): project = "my_project" struct = {"my_file": type("StrangeType", (object,), {})()} os.mkdir(project) with pytest.raises(TypeError): repo.init_commit_repo(project, struct) def test_add_tag(tmpfolder): project = "my_project" struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, } structure.create_structure(struct, dict(project_path=project)) repo.init_commit_repo(project, struct) repo.add_tag(project, "v0.0") repo.add_tag(project, "v0.1", "Message with whitespace") @pytest.mark.slow def test_version_of_subdir(tmpfolder): projects = ["main_project", "inner_project"] for project in projects: opts = cli.parse_args([project]) opts = api.bootstrap_options(opts) _, opts = actions.get_default_options({}, opts) struct, _ = structure.define_structure({}, opts) struct, _ = structure.create_structure(struct, opts) repo.init_commit_repo(project, struct) rm_rf(Path("inner_project", ".git")) move("inner_project", target="main_project/inner_project") # setuptools_scm required explicitly setting the git root when setup.py is # not at the root of the repository nested_setup_py = Path(tmpfolder, "main_project/inner_project/setup.py") content = nested_setup_py.read_text() content = content.replace( "use_scm_version={", 'use_scm_version={"root": "..", "relative_to": __file__, ' ) nested_setup_py.write_text(content) nested_pyproject_toml = Path(tmpfolder, "main_project/inner_project/pyproject.toml") config = toml.loads(nested_pyproject_toml.read_text()) config["tool"]["setuptools_scm"]["root"] = ".." nested_pyproject_toml.write_text(toml.dumps(config)) with chdir("main_project"): main_version = ( subprocess.check_output([sys.executable, "setup.py", "--version"]) .strip() .splitlines()[-1] ) with chdir("inner_project"): inner_version = ( subprocess.check_output([sys.executable, "setup.py", "--version"]) .strip() .splitlines()[-1] ) assert main_version.strip() == inner_version.strip() def test_is_git_repo(tmpfolder): assert not repo.is_git_repo("/a-folder/that-not/exist") newdir = tmpfolder.join("new").ensure_dir() assert not repo.is_git_repo(str(newdir)) newdir.chdir() shell.git("init") tmpfolder.chdir() assert repo.is_git_repo(str(newdir)) def test_get_git_root(tmpfolder): project = "my_project" struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, } structure.create_structure(struct, {"project_path": project}) repo.init_commit_repo(project, struct) with chdir(project): git_root = repo.get_git_root() assert Path(git_root).name == project def test_get_git_root_with_nogit(tmpfolder, nogit_mock): project = "my_project" struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, } structure.create_structure(struct, {"project_path": project}) with chdir(project): git_root = repo.get_git_root(default=".") assert git_root == "." def test_get_git_root_with_nonegit(tmpfolder, nonegit_mock): project = "my_project" struct = { "my_file": "Some other content", "my_dir": {"my_file": "Some more content"}, } structure.create_structure(struct, {"project_path": project}) with chdir(project): git_root = repo.get_git_root(default=".") assert git_root == "."
site/search-index/pagerank.py
vishalbelsare/neupy
801
11124890
<gh_stars>100-1000 import scipy import numpy as np import scipy.sparse as sp def pagerank(graph_matrix, n_iter=100, alpha=0.9, tol=1e-6): n_nodes = graph_matrix.shape[0] n_edges_per_node = graph_matrix.sum(axis=1) n_edges_per_node = np.array(n_edges_per_node).flatten() np.seterr(divide='ignore') normilize_vector = np.where((n_edges_per_node != 0), 1. / n_edges_per_node, 0) np.seterr(divide='warn') normilize_matrix = sp.spdiags(normilize_vector, 0, *graph_matrix.shape, format='csr') graph_proba_matrix = normilize_matrix * graph_matrix teleport_proba = np.repeat(1. / n_nodes, n_nodes) is_dangling, = scipy.where(normilize_vector == 0) x_current = teleport_proba for _ in range(n_iter): x_previous = x_current.copy() dangling_total_proba = sum(x_current[is_dangling]) x_current = ( x_current * graph_proba_matrix + dangling_total_proba * teleport_proba ) x_current = alpha * x_current + (1 - alpha) * teleport_proba error = np.abs(x_current - x_previous).mean() if error < tol: break else: print("PageRank didn't converge") return x_current
algoexpert.io/python/Longest_Common_Subsequence.py
its-sushant/coding-interview-gym
713
11124895
<reponame>its-sushant/coding-interview-gym # Solution: My solution using 2d dp # O(nm) time | O(nm) space def longestCommonSubsequence(string1, string2): dp = [[[] for _ in range(len(string2) + 1)] for _ in range(len(string1) + 1)] for i in range(1, len(string1) + 1): x = string1[i - 1] for j in range(1, len(string2) + 1): rx = string2[j - 1] if x == rx: dp[i][j] = dp[i - 1][j - 1] + [x] else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j], key=len) return dp[-1][-1]
one_step_app.py
Questions1/Rong360_2nd
107
11124909
import numpy as np import pandas as pd def read_app(file_path): reader = pd.read_table(file_path, header=None, chunksize=10000) data = pd.concat(reader, axis=0, ignore_index=True) data.columns = ['id', 'apps'] return data def get_apps_dummy(data): """ 把dat_app里用户装的app信息0-1化 1. 读取需要的104个app:app_104_list 2. 然后得到长度为‘len(app_104_list)’的0-1向量 """ def is_in_all_apps(x): xs = x.split(',') xs = set(xs) app_vec = list(map(lambda app: int(app in xs), app_66)) return app_vec apps_dummy_0 = list(map(is_in_all_apps, data['apps'])) apps_dummy_1 = pd.DataFrame(apps_dummy_0, columns=app_66) apps_dummy_2 = pd.concat([data[['id']], apps_dummy_1], axis=1) return apps_dummy_2 if __name__ == '__main__': input_path = './' sample_train = pd.read_table('./open_data/sample_train.txt') # 训练集约1.9万 valid_id = pd.read_table('./open_data/valid_id.txt') # 验证集 test_id = pd.read_table('./open_data/test_id.txt') # 测试集 dat_app = pd.concat([read_app('./open_data/dat_app/dat_app_%s' % x) for x in range(1, 8)], axis=0, ignore_index=True) important_feature_app = pd.read_csv('./output/important_feature_app.csv') app_66 = [str(x) for x in important_feature_app['feature']] son = pd.read_csv('./output/son.csv') father = pd.read_csv('./output/father.csv') all_id = pd.concat([sample_train[['id']], valid_id[['id']], test_id[['id']]], axis=0) whole_id = list(set(son['to_id']).union(set(father['from_id'])).union(all_id['id'])) one_step_id = pd.DataFrame({'id': whole_id}) one_step_app = pd.merge(one_step_id, dat_app, on='id') one_step_apps_dummy = get_apps_dummy(one_step_app) one_step_apps_dummy.to_csv('./output/one_step_apps_dummy.csv', index=False)
controllers/admin/admin_offseason_scraper_controller.py
tervay/the-blue-alliance
266
11124925
import datetime import logging import os from google.appengine.ext import ndb from google.appengine.ext.webapp import template from controllers.base_controller import LoggedInHandler from datafeeds.datafeed_usfirst_offseason import DatafeedUsfirstOffseason from consts.event_type import EventType from helpers.event_manipulator import EventManipulator from models.event import Event class AdminOffseasonScraperController(LoggedInHandler): """ View and add un-added offseasons from FIRST's site """ def get(self): self._require_admin() df = DatafeedUsfirstOffseason() new_events = df.getEventList() old_events = Event.query().filter( Event.event_type_enum == EventType.OFFSEASON).filter( Event.year == datetime.datetime.now().year).filter( Event.first_eid != None).fetch(100) old_first_eids = [event.first_eid for event in old_events] truly_new_events = [event for event in new_events if event.first_eid not in old_first_eids] self.template_values.update({ "events": truly_new_events, "event_key": self.request.get("event_key"), "success": self.request.get("success"), }) path = os.path.join(os.path.dirname(__file__), '../../templates/admin/offseasons.html') self.response.out.write(template.render(path, self.template_values)) def post(self): self._require_admin() if self.request.get("submit") == "duplicate": old_event = Event.get_by_id(self.request.get("duplicate_event_key")) old_event.first_eid = self.request.get("event_first_eid") old_event.dirty = True # TODO: hacky EventManipulator.createOrUpdate(old_event) self.redirect("/admin/offseasons?success=duplicate&event_key=%s" % self.request.get("duplicate_event_key")) return if self.request.get("submit") == "create": start_date = None if self.request.get("event_start_date"): start_date = datetime.datetime.strptime(self.request.get("event_start_date"), "%Y-%m-%d") end_date = None if self.request.get("event_end_date"): end_date = datetime.datetime.strptime(self.request.get("event_end_date"), "%Y-%m-%d") event_key = str(self.request.get("event_year")) + str.lower(str(self.request.get("event_short"))) event = Event( id=event_key, event_type_enum=int(self.request.get("event_type_enum")), event_short=self.request.get("event_short"), first_eid=self.request.get("event_first_eid"), name=self.request.get("event_name"), year=int(self.request.get("event_year")), start_date=start_date, end_date=end_date, city=self.request.get("city"), state_prov=self.request.get("state_prov"), country=self.request.get("country"), ) event = EventManipulator.createOrUpdate(event) self.redirect("/admin/offseasons?success=create&event_key=%s" % event_key) return self.redirect("/admin/offseasons")