content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
txhash = "0xb538eabb6cea1fc3af58f1474c2b8f1adbf36a209ec8dc5534618b1f2d860c8e"
version = "1.1.0"
network = "ropsten"
address = 'bc1qzse3hm25w3nx70e8nlss6nlfusj7wd4q3m8gax'
transaction_data = {
'txid': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b',
'hash': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b',
'version': 2,
'size': 222,
'vsize': 222,
'weight': 888,
'locktime': 1865235,
'vin': [{
'txid': '3c1324004cf55aff8d4153bda4b6059a82f6fdc4aa43b5b2d26fa3a97eed0e4f',
'vout': 0,
'scriptSig': {
'asm': '3044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff89251043[ALL] 0299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6',
'hex': '473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6'
},
'sequence': 4294967293
}],
'vout': [{
'value': 0.01,
'n': 0,
'scriptPubKey': {
'asm': '0 89c82f97d743d939d5c9f4068e3a53dfd09ec5fc',
'hex': '001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc',
'reqSigs': 1,
'type': 'witness_v0_keyhash',
'addresses': ['tb1q38yzl97hg0vnn4wf7srguwjnmlgfa30uq3nrwt']}
}, {
'value': 1.989997,
'n': 1,
'scriptPubKey': {
'asm': 'OP_DUP OP_HASH160 4c8bda34fa519008db22b421711ee6b9fb52b559 OP_EQUALVERIFY OP_CHECKSIG',
'hex': '76a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac',
'reqSigs': 1,
'type': 'pubkeyhash',
'addresses': ['mnVhBkEWwvP4MMeTBZoZa3GGTVsNm135eG']}
}],
'hex': '02000000014f0eed7ea9a36fd2b2b543aac4fdf6829a05b6a4bd53418dff5af54c0024133c000000006a473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6fdffffff0240420f000000000016001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc947edc0b000000001976a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac13761c00',
'blockhash': '0000000005629b78403c6b58bf094b1987dd9e62a9349f71ff4882c05f0ad517',
'confirmations': 24854,
'time': 1603872469,
'blocktime': 1603872469
}
| txhash = '0xb538eabb6cea1fc3af58f1474c2b8f1adbf36a209ec8dc5534618b1f2d860c8e'
version = '1.1.0'
network = 'ropsten'
address = 'bc1qzse3hm25w3nx70e8nlss6nlfusj7wd4q3m8gax'
transaction_data = {'txid': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'hash': '6cc808a28150482f783fdff7c99a6245a59437f55bb85575aa31c99ab2b0898b', 'version': 2, 'size': 222, 'vsize': 222, 'weight': 888, 'locktime': 1865235, 'vin': [{'txid': '3c1324004cf55aff8d4153bda4b6059a82f6fdc4aa43b5b2d26fa3a97eed0e4f', 'vout': 0, 'scriptSig': {'asm': '3044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff89251043[ALL] 0299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6', 'hex': '473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6'}, 'sequence': 4294967293}], 'vout': [{'value': 0.01, 'n': 0, 'scriptPubKey': {'asm': '0 89c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'hex': '001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc', 'reqSigs': 1, 'type': 'witness_v0_keyhash', 'addresses': ['tb1q38yzl97hg0vnn4wf7srguwjnmlgfa30uq3nrwt']}}, {'value': 1.989997, 'n': 1, 'scriptPubKey': {'asm': 'OP_DUP OP_HASH160 4c8bda34fa519008db22b421711ee6b9fb52b559 OP_EQUALVERIFY OP_CHECKSIG', 'hex': '76a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac', 'reqSigs': 1, 'type': 'pubkeyhash', 'addresses': ['mnVhBkEWwvP4MMeTBZoZa3GGTVsNm135eG']}}], 'hex': '02000000014f0eed7ea9a36fd2b2b543aac4fdf6829a05b6a4bd53418dff5af54c0024133c000000006a473044022052d0875f4412e26e2db1470126f5ccc537e8998bcb5b203e6346ca9b1bf847d2022039182a20dd4c2a30b4155d4b72426aaa6c6cf97c02928c7c06fd4cff8925104301210299b7faf388c5d8e6ba1654476083098e896bd2ec384aba20484b8a82d01496b6fdffffff0240420f000000000016001489c82f97d743d939d5c9f4068e3a53dfd09ec5fc947edc0b000000001976a9144c8bda34fa519008db22b421711ee6b9fb52b55988ac13761c00', 'blockhash': '0000000005629b78403c6b58bf094b1987dd9e62a9349f71ff4882c05f0ad517', 'confirmations': 24854, 'time': 1603872469, 'blocktime': 1603872469} |
class CognitiveAbilitiesGroupingPolicy:
@staticmethod
def group(filename: str) -> str:
return filename.split(".")[0].split("-")[0]
| class Cognitiveabilitiesgroupingpolicy:
@staticmethod
def group(filename: str) -> str:
return filename.split('.')[0].split('-')[0] |
n=int(input());s=input();r=0;l=len(s)
for i in range(l):
r+=(ord(s[i])-ord('a')+1)*31**i
print(r%1234567891)
| n = int(input())
s = input()
r = 0
l = len(s)
for i in range(l):
r += (ord(s[i]) - ord('a') + 1) * 31 ** i
print(r % 1234567891) |
#!/usr/bin/env python3
def edit_distance(s1: str, s2: str) -> int:
n = len(s1)
m = len(s2)
edit = [[None for i in range(1 + m)] for j in range(1 + n)]
for i in range(1 + m):
edit[0][i] = i
for i in range(1, 1 + n):
edit[i][0] = i
for j in range(1, 1 + m):
replace = edit[i-1][j-1]
insert = 1 + edit[i][j - 1]
delete = 1 + edit[i - 1][j]
if not (s1[i - 1] == s2[j - 1]):
replace += 1
edit[i][j] = min(insert, delete, replace)
return edit[n][m]
if __name__ == '__main__':
s1 = input('s1: ')
s2 = input('s2: ')
print(edit_distance(s1, s2))
| def edit_distance(s1: str, s2: str) -> int:
n = len(s1)
m = len(s2)
edit = [[None for i in range(1 + m)] for j in range(1 + n)]
for i in range(1 + m):
edit[0][i] = i
for i in range(1, 1 + n):
edit[i][0] = i
for j in range(1, 1 + m):
replace = edit[i - 1][j - 1]
insert = 1 + edit[i][j - 1]
delete = 1 + edit[i - 1][j]
if not s1[i - 1] == s2[j - 1]:
replace += 1
edit[i][j] = min(insert, delete, replace)
return edit[n][m]
if __name__ == '__main__':
s1 = input('s1: ')
s2 = input('s2: ')
print(edit_distance(s1, s2)) |
FILTERS = [
[4, 1, 2],
[2, 2, 4],
[1, 4, 4],
[1, 4, 1]
]
MSG_LEN = 16
KEY_LEN = 16
BATCH_SIZE = 512
NUM_EPOCHS = 60
LEARNING_RATE = 0.0008
| filters = [[4, 1, 2], [2, 2, 4], [1, 4, 4], [1, 4, 1]]
msg_len = 16
key_len = 16
batch_size = 512
num_epochs = 60
learning_rate = 0.0008 |
def metade(preco=0, formato=False):
res = preco / 2
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if formato is False else moeda(res)
def aumento(preco=0, taxa=0, formato=False):
res = preco * (1 + taxa/100)
return res if formato is False else moeda(res)
def reducao(preco=0, taxa=0, formato=False):
res = preco * (1 - taxa/100)
return res if formato is False else moeda(res)
def moeda(preco=0, moeda='R$'):
return f' {moeda} {preco:7.2f}'.replace('.',',') | def metade(preco=0, formato=False):
res = preco / 2
return res if formato is False else moeda(res)
def dobro(preco=0, formato=False):
res = preco * 2
return res if formato is False else moeda(res)
def aumento(preco=0, taxa=0, formato=False):
res = preco * (1 + taxa / 100)
return res if formato is False else moeda(res)
def reducao(preco=0, taxa=0, formato=False):
res = preco * (1 - taxa / 100)
return res if formato is False else moeda(res)
def moeda(preco=0, moeda='R$'):
return f' {moeda} {preco:7.2f}'.replace('.', ',') |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utilities for managing globals for the environment.
"""
def create_initial_globals(path):
"""
Emulates a ``globals()`` call in a freshly loaded module.
The implementation of this function is likely to raise a couple of questions. If you read the
implementation and nothing bothered you, feel free to skip the rest of this docstring.
First, why is this function in its own module and not, say, in the same module of the other
environment-related functions? Second, why is it implemented in such a way that copies the
globals, then deletes the item that represents this function, and then changes some other
entries?
Well, these two questions can be answered with one (elaborate) explanation. If this function was
in the same module with the other environment-related functions, then we would have had to
delete more items in globals than just ``create_initial_globals``. That is because all of the
other function names would also be in globals, and since there is no built-in mechanism that
return the name of the user-defined objects, this approach is quite an overkill.
*But why do we rely on the copy-existing-globals-and-delete-entries method, when it seems to
force us to put ``create_initial_globals`` in its own file?*
Well, because there is no easier method of creating globals of a newly loaded module.
*How about hard coding a ``globals`` dict? It seems that there are very few entries:
``__doc__``, ``__file__``, ``__name__``, ``__package__`` (but don't forget ``__builtins__``).*
That would be coupling our implementation to a specific ``globals`` implementation. What if
``globals`` were to change?
"""
copied_globals = globals().copy()
copied_globals.update({
'__doc__': 'Dynamically executed script',
'__file__': path,
'__name__': '__main__',
'__package__': None
})
del copied_globals[create_initial_globals.__name__]
return copied_globals
| """
Utilities for managing globals for the environment.
"""
def create_initial_globals(path):
"""
Emulates a ``globals()`` call in a freshly loaded module.
The implementation of this function is likely to raise a couple of questions. If you read the
implementation and nothing bothered you, feel free to skip the rest of this docstring.
First, why is this function in its own module and not, say, in the same module of the other
environment-related functions? Second, why is it implemented in such a way that copies the
globals, then deletes the item that represents this function, and then changes some other
entries?
Well, these two questions can be answered with one (elaborate) explanation. If this function was
in the same module with the other environment-related functions, then we would have had to
delete more items in globals than just ``create_initial_globals``. That is because all of the
other function names would also be in globals, and since there is no built-in mechanism that
return the name of the user-defined objects, this approach is quite an overkill.
*But why do we rely on the copy-existing-globals-and-delete-entries method, when it seems to
force us to put ``create_initial_globals`` in its own file?*
Well, because there is no easier method of creating globals of a newly loaded module.
*How about hard coding a ``globals`` dict? It seems that there are very few entries:
``__doc__``, ``__file__``, ``__name__``, ``__package__`` (but don't forget ``__builtins__``).*
That would be coupling our implementation to a specific ``globals`` implementation. What if
``globals`` were to change?
"""
copied_globals = globals().copy()
copied_globals.update({'__doc__': 'Dynamically executed script', '__file__': path, '__name__': '__main__', '__package__': None})
del copied_globals[create_initial_globals.__name__]
return copied_globals |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#---------------------------------------------------------------------------
#
# Author: lubo
# E-mail: 454331202@qq.com
# LastModified: 2014-05-23 11:18:31
# Filename: gl.py
# Desc:
#
#---------------------------------------------------------------------------
headline1 = ''
headline2 = ''
mysql_headline1 = ''
mysql_headline2 = ''
ncpu = 0 #Number of processors
# Options Flag
optflag = 0 #whether input opt
timeFlag = 0 # -t : print current time
interval = 1 # -i : time(second) interval
my_load = 0 # -l : print load info
my_cpu = 0 # -c : print cpu info
my_swap = 0 # -s : print swap info
my_disk = None # -d : print disk info
my_net = None # -n : print net info
mysql = 0 # -mysql: print mysql status
mysql_conn ='' # mysql conn info
com = 0; # -com : print mysql status
innodb_hit = 0 # -hit : Print Innodb Hit%
innodb_rows = 0 # -innodb_rows : Print Innodb Rows Status
innodb_pages= 0 # -innodb_pages: Innodb Buffer Pool Pages Status
innodb_data = 0 # -innodb_data : Innodb Data Status
innodb_log = 0 # -innodb_log : Innodb Log Status
innodb_status=0 # -innodb_status: Show Engine Innodb Status
threads = 0 # -T : Print Threads Status
bytes = 0 # -B : Print Bytes Status
my_port = '3306' # default prot 3306
my_socket =None # sockfile
my_pwd =None # root user password
dbrt = 0 # -rt
lock_file=''
tcprstat_logfile=''
tcprstat_dir='/tmp/'
orz_logfile=None
old_console=''
logfile_by_day=0 # one day one logfile
# Variables For :
#-----> Get SysInfo (from /proc/stat): CPU
sys_cpu1 = (0,0,0,0,0,0,0,0)
total_1 = 0
#
#<----- Get SysInfo (from /proc/stat): CPU
#-----> Get SysInfo (from /proc/vmstat): SWAP
swap1 ={'pswpin':0,'pswpout':0}
swap_not_first = 0
#<----- Get SysInfo (from /proc/vmstat): SWAP
#-----> Get SysInfo (from /proc/net/dev): NET
net1 ={'recv':0,'send':0}
net_not_first = 0
#<----- Get SysInfo (from /proc/net/dev): NET
#-----> Get SysInfo (from /proc/diskstats): IO
sys_io1 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
io_not_first = 0; # no print first value
#ncpu = `grep processor /proc/cpuinfo | wc -l`; #/* Number of processors */
# grep "HZ" -R /usr/include/*
# /usr/include/asm-x86_64/param.h:#define HZ 100
HZ = 100
#<----- Get SysInfo (from /proc/diskstats): IO
#-----> Get Mysql Status
mystat1={"Com_select":0,
"Com_delete":0 ,
"Com_update":0,
"Com_insert":0,
"Innodb_buffer_pool_read_requests":0,
"Innodb_rows_inserted":0,
"Innodb_rows_updated":0,
"Innodb_rows_deleted":0,
"Innodb_rows_read":0,
"Threads_created":0,
"Bytes_received":0,
"Bytes_sent":0,
"Innodb_buffer_pool_pages_flushed":0,
"Innodb_data_read":0,
"Innodb_data_reads":0,
"Innodb_data_writes":0,
"Innodb_data_written":0,
"Innodb_os_log_fsyncs":0,
"Innodb_os_log_written":0}
mysql_no_first = 0
#<----- Get Mysql Status
HAS_COLOR=1
count=None #times
python_version=''
| headline1 = ''
headline2 = ''
mysql_headline1 = ''
mysql_headline2 = ''
ncpu = 0
optflag = 0
time_flag = 0
interval = 1
my_load = 0
my_cpu = 0
my_swap = 0
my_disk = None
my_net = None
mysql = 0
mysql_conn = ''
com = 0
innodb_hit = 0
innodb_rows = 0
innodb_pages = 0
innodb_data = 0
innodb_log = 0
innodb_status = 0
threads = 0
bytes = 0
my_port = '3306'
my_socket = None
my_pwd = None
dbrt = 0
lock_file = ''
tcprstat_logfile = ''
tcprstat_dir = '/tmp/'
orz_logfile = None
old_console = ''
logfile_by_day = 0
sys_cpu1 = (0, 0, 0, 0, 0, 0, 0, 0)
total_1 = 0
swap1 = {'pswpin': 0, 'pswpout': 0}
swap_not_first = 0
net1 = {'recv': 0, 'send': 0}
net_not_first = 0
sys_io1 = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
io_not_first = 0
hz = 100
mystat1 = {'Com_select': 0, 'Com_delete': 0, 'Com_update': 0, 'Com_insert': 0, 'Innodb_buffer_pool_read_requests': 0, 'Innodb_rows_inserted': 0, 'Innodb_rows_updated': 0, 'Innodb_rows_deleted': 0, 'Innodb_rows_read': 0, 'Threads_created': 0, 'Bytes_received': 0, 'Bytes_sent': 0, 'Innodb_buffer_pool_pages_flushed': 0, 'Innodb_data_read': 0, 'Innodb_data_reads': 0, 'Innodb_data_writes': 0, 'Innodb_data_written': 0, 'Innodb_os_log_fsyncs': 0, 'Innodb_os_log_written': 0}
mysql_no_first = 0
has_color = 1
count = None
python_version = '' |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"display": "00_core.ipynb",
"Markdown": "00_core.ipynb",
"Audio": "00_core.ipynb",
"first_run": "00_core.ipynb",
"beep": "00_core.ipynb",
"h1": "00_core.ipynb",
"h2": "00_core.ipynb",
"h3": "00_core.ipynb",
"h4": "00_core.ipynb",
"h5": "00_core.ipynb",
"h6": "00_core.ipynb",
"from_file": "00_core.ipynb",
"good_url": "00_core.ipynb",
"user_agent": "00_core.ipynb",
"extract_apex": "00_core.ipynb",
"extract_meta_link": "00_core.ipynb",
"extract_links": "00_core.ipynb",
"extract_title": "00_core.ipynb",
"extract_meta": "00_core.ipynb",
"extract_hx": "00_core.ipynb",
"extract_body": "00_core.ipynb",
"extract_stemmed": "00_core.ipynb",
"extract_url_keywords": "00_core.ipynb",
"extract_keywords": "00_core.ipynb",
"gsc_guess_site": "00_core.ipynb",
"gsc_url2keyword_query": "00_core.ipynb",
"gsc_url_query": "00_core.ipynb",
"gsc2df": "00_core.ipynb",
"df_allout": "00_core.ipynb",
"ga_accounts": "00_core.ipynb",
"ga_properties": "00_core.ipynb",
"ga_properties_g4": "00_core.ipynb",
"ga_profiles": "00_core.ipynb",
"ga_everything": "00_core.ipynb",
"inspect_url": "00_core.ipynb",
"drop_table": "00_core.ipynb",
"pk_compositor": "00_core.ipynb",
"pk_inserter": "00_core.ipynb",
"config2dict": "00_core.ipynb",
"build_google_search_query": "00_core.ipynb",
"extract_serps": "00_core.ipynb",
"run_me": "00_core.ipynb",
"look": "00_core.ipynb",
"show_globals": "00_core.ipynb",
"enlighten_me": "00_core.ipynb",
"save_me": "00_core.ipynb",
"please_explain": "00_core.ipynb",
"bs": "00_core.ipynb",
"lr": "10_requirements.ipynb",
"SPACES": "00_core.ipynb",
"LINES": "00_core.ipynb",
"pstem": "00_core.ipynb",
"stop_words": "00_core.ipynb",
"pkl": "00_core.ipynb",
"unpkl": "00_core.ipynb",
"svc_ga": "00_core.ipynb",
"svc_ga4": "00_core.ipynb",
"svc_gsc": "00_core.ipynb",
"svc_mail": "00_core.ipynb",
"svc_oauth": "00_core.ipynb",
"svc_sheet": "00_core.ipynb",
"svc_photo": "00_core.ipynb",
"svc_youtube": "00_core.ipynb",
"out": "10_requirements.ipynb",
"table": "10_requirements.ipynb",
"upgrades": "10_requirements.ipynb",
"outputs": "10_requirements.ipynb"}
modules = ["core.py",
"pip_upgrades.py"]
doc_url = "https://miklevin.github.io/mlseo/"
git_url = "https://github.com/miklevin/mlseo/tree/main/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'display': '00_core.ipynb', 'Markdown': '00_core.ipynb', 'Audio': '00_core.ipynb', 'first_run': '00_core.ipynb', 'beep': '00_core.ipynb', 'h1': '00_core.ipynb', 'h2': '00_core.ipynb', 'h3': '00_core.ipynb', 'h4': '00_core.ipynb', 'h5': '00_core.ipynb', 'h6': '00_core.ipynb', 'from_file': '00_core.ipynb', 'good_url': '00_core.ipynb', 'user_agent': '00_core.ipynb', 'extract_apex': '00_core.ipynb', 'extract_meta_link': '00_core.ipynb', 'extract_links': '00_core.ipynb', 'extract_title': '00_core.ipynb', 'extract_meta': '00_core.ipynb', 'extract_hx': '00_core.ipynb', 'extract_body': '00_core.ipynb', 'extract_stemmed': '00_core.ipynb', 'extract_url_keywords': '00_core.ipynb', 'extract_keywords': '00_core.ipynb', 'gsc_guess_site': '00_core.ipynb', 'gsc_url2keyword_query': '00_core.ipynb', 'gsc_url_query': '00_core.ipynb', 'gsc2df': '00_core.ipynb', 'df_allout': '00_core.ipynb', 'ga_accounts': '00_core.ipynb', 'ga_properties': '00_core.ipynb', 'ga_properties_g4': '00_core.ipynb', 'ga_profiles': '00_core.ipynb', 'ga_everything': '00_core.ipynb', 'inspect_url': '00_core.ipynb', 'drop_table': '00_core.ipynb', 'pk_compositor': '00_core.ipynb', 'pk_inserter': '00_core.ipynb', 'config2dict': '00_core.ipynb', 'build_google_search_query': '00_core.ipynb', 'extract_serps': '00_core.ipynb', 'run_me': '00_core.ipynb', 'look': '00_core.ipynb', 'show_globals': '00_core.ipynb', 'enlighten_me': '00_core.ipynb', 'save_me': '00_core.ipynb', 'please_explain': '00_core.ipynb', 'bs': '00_core.ipynb', 'lr': '10_requirements.ipynb', 'SPACES': '00_core.ipynb', 'LINES': '00_core.ipynb', 'pstem': '00_core.ipynb', 'stop_words': '00_core.ipynb', 'pkl': '00_core.ipynb', 'unpkl': '00_core.ipynb', 'svc_ga': '00_core.ipynb', 'svc_ga4': '00_core.ipynb', 'svc_gsc': '00_core.ipynb', 'svc_mail': '00_core.ipynb', 'svc_oauth': '00_core.ipynb', 'svc_sheet': '00_core.ipynb', 'svc_photo': '00_core.ipynb', 'svc_youtube': '00_core.ipynb', 'out': '10_requirements.ipynb', 'table': '10_requirements.ipynb', 'upgrades': '10_requirements.ipynb', 'outputs': '10_requirements.ipynb'}
modules = ['core.py', 'pip_upgrades.py']
doc_url = 'https://miklevin.github.io/mlseo/'
git_url = 'https://github.com/miklevin/mlseo/tree/main/'
def custom_doc_links(name):
return None |
#17/02/21
#What does this code do?
# This code takes an input "n" and counts out until that number is reached.
# This works similarly to the previous code, except with numbers.
n = int(input('Enter a number: '))
for i in range(n):
print(i + 1)
#What is happening here?
# In line 1, our code is taking an integer input, and assigning it to "n"
# After that, it prints i+1, until n is reached.
| n = int(input('Enter a number: '))
for i in range(n):
print(i + 1) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
strarr=[]
for x in range(n):
strin=input()
strarr.append(strin)
stradd=set(strarr)
print(len(stradd))
| n = int(input())
strarr = []
for x in range(n):
strin = input()
strarr.append(strin)
stradd = set(strarr)
print(len(stradd)) |
'''
580C. Kefa and Park
dfs and similar, graphs, trees, 1500
http://codeforces.com/problemset/problem/580/C
'''
n, m = map(int, input().split())
cat = 1
empty = 0
status = [-1] + list(map(int, input().split()))
tree = {}
for _ in range(n-1):
s, e = map(int, input().split())
if s not in tree:
tree[s] = [e]
else:
tree[s].append(e)
if e not in tree:
tree[e] = [s]
else:
tree[e].append(s)
count = 0
# graph: dict type, s: start node code
def BFS(graph, s):
queue = []
queue.append(s)
seen = set()
seen.add(s[0])
result = 0
while (len(queue) > 0):
vertex, current_c = queue.pop(0)
if current_c <= m:
nodes = graph[vertex]
# if is the restaurant(leaves)
if vertex != s[0] and len(nodes) == 1:
result += 1
else:
# if not leaves, add the children
for w in nodes:
if w not in seen:
# if not exceed max cat met
if status[w] == empty:
queue.append([w, 0])
elif current_c+status[w] <= m:
queue.append([w, current_c+status[w]])
seen.add(w)
return result
count = BFS(tree, [1, status[1]])
print(count) | """
580C. Kefa and Park
dfs and similar, graphs, trees, 1500
http://codeforces.com/problemset/problem/580/C
"""
(n, m) = map(int, input().split())
cat = 1
empty = 0
status = [-1] + list(map(int, input().split()))
tree = {}
for _ in range(n - 1):
(s, e) = map(int, input().split())
if s not in tree:
tree[s] = [e]
else:
tree[s].append(e)
if e not in tree:
tree[e] = [s]
else:
tree[e].append(s)
count = 0
def bfs(graph, s):
queue = []
queue.append(s)
seen = set()
seen.add(s[0])
result = 0
while len(queue) > 0:
(vertex, current_c) = queue.pop(0)
if current_c <= m:
nodes = graph[vertex]
if vertex != s[0] and len(nodes) == 1:
result += 1
else:
for w in nodes:
if w not in seen:
if status[w] == empty:
queue.append([w, 0])
elif current_c + status[w] <= m:
queue.append([w, current_c + status[w]])
seen.add(w)
return result
count = bfs(tree, [1, status[1]])
print(count) |
""" Practice Binary Search """
def binary_search(array, target):
mid = len(array) // 2
high = len(array) - 1
print("high", high)
low = 0
while low <= high:
mid = int((low+high)) // 2
print("mid", mid)
print('mid element', array[mid])
if array[mid] == target:
print("Print statement ends")
return array[mid]
if target < array[mid]:
high = mid - 1
else:
low = mid + 1
return None
# test:
array = [2, 3, 14, 18, 19, 42, 46, 90, 1001]
target = 42
print(binary_search(array,target))
| """ Practice Binary Search """
def binary_search(array, target):
mid = len(array) // 2
high = len(array) - 1
print('high', high)
low = 0
while low <= high:
mid = int(low + high) // 2
print('mid', mid)
print('mid element', array[mid])
if array[mid] == target:
print('Print statement ends')
return array[mid]
if target < array[mid]:
high = mid - 1
else:
low = mid + 1
return None
array = [2, 3, 14, 18, 19, 42, 46, 90, 1001]
target = 42
print(binary_search(array, target)) |
# https://adventofcode.com/2021/day/14
test = "2021-14_sample.txt"
run = "2021-14_input.txt"
def part1(fname):
template = None
inserts = {}
for i, line in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = line[6]
#print(template)
for _ in range(10):
reversed = [template[-1]]
for i in range(len(template)-2, -1, -1):
pair = template[i:i+2]
#print(f'{pair}')
if pair in inserts:
reversed.append(inserts[pair])
reversed.append(template[i])
template = ''.join(reversed[::-1])
#print(template)
counts = {}
for c in template:
counts[c] = counts.get(c, 0) + 1
print(counts)
return max(counts.values()) - min(counts.values())
def print_nonzero(inserts):
print('---')
for k, v in inserts.items():
if v['count'] > 0:
print(f' {k} : {v}')
print('---')
def part2(fname, steps):
inserts = {}
for i, line in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = {'count':0, 'next':[line[0]+line[6], line[6]+line[1]]}
print(template)
for i in range(len(template)-1):
pair = template[i:i+2]
inserts[pair]['count'] += 1
#print_nonzero(inserts)
for _ in range(steps):
# with 40 steps the string becomes terabytes in size
state = {}
for k in inserts:
state[k] = inserts[k]['count']
inserts[k]['count'] = 0
for k in state:
for nk in inserts[k]['next']:
inserts[nk]['count'] += state[k]
#print_nonzero(inserts)
counts = {template[-1]:1}
for pair in inserts:
c = pair[0]
counts[c] = counts.get(c, 0) + inserts[pair]['count']
for i in counts.items():
print(i)
return max(counts.values()) - min(counts.values())
assert part1(test) == 1588
print(f'part1: {part1(run)}')
assert part2(test, 10) == 1588
assert part2(test, 40) == 2188189693529
print(f'part2: {part2(run, 40)}')
| test = '2021-14_sample.txt'
run = '2021-14_input.txt'
def part1(fname):
template = None
inserts = {}
for (i, line) in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = line[6]
for _ in range(10):
reversed = [template[-1]]
for i in range(len(template) - 2, -1, -1):
pair = template[i:i + 2]
if pair in inserts:
reversed.append(inserts[pair])
reversed.append(template[i])
template = ''.join(reversed[::-1])
counts = {}
for c in template:
counts[c] = counts.get(c, 0) + 1
print(counts)
return max(counts.values()) - min(counts.values())
def print_nonzero(inserts):
print('---')
for (k, v) in inserts.items():
if v['count'] > 0:
print(f' {k} : {v}')
print('---')
def part2(fname, steps):
inserts = {}
for (i, line) in enumerate(open(fname)):
if i == 0:
template = line.rstrip()
elif line[2:6] == ' -> ':
inserts[line[0:2]] = {'count': 0, 'next': [line[0] + line[6], line[6] + line[1]]}
print(template)
for i in range(len(template) - 1):
pair = template[i:i + 2]
inserts[pair]['count'] += 1
for _ in range(steps):
state = {}
for k in inserts:
state[k] = inserts[k]['count']
inserts[k]['count'] = 0
for k in state:
for nk in inserts[k]['next']:
inserts[nk]['count'] += state[k]
counts = {template[-1]: 1}
for pair in inserts:
c = pair[0]
counts[c] = counts.get(c, 0) + inserts[pair]['count']
for i in counts.items():
print(i)
return max(counts.values()) - min(counts.values())
assert part1(test) == 1588
print(f'part1: {part1(run)}')
assert part2(test, 10) == 1588
assert part2(test, 40) == 2188189693529
print(f'part2: {part2(run, 40)}') |
'''
Created on 11 Dec 2021
@author: laurentmichel
'''
class MappingException(Exception):
pass
class ParsingException(Exception):
pass
class NotImplementedException(Exception):
pass
| """
Created on 11 Dec 2021
@author: laurentmichel
"""
class Mappingexception(Exception):
pass
class Parsingexception(Exception):
pass
class Notimplementedexception(Exception):
pass |
_base_ = [
'../_base_/models/dla34up_lane.py',
'../_base_/datasets/bdd100k_lane.py',
'../_base_/schedules/bdd100k_lane_12e.py',
'../_base_/default_runtime.py'
]
| _base_ = ['../_base_/models/dla34up_lane.py', '../_base_/datasets/bdd100k_lane.py', '../_base_/schedules/bdd100k_lane_12e.py', '../_base_/default_runtime.py'] |
class Solution(object):
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total, l = 0, len(nums)
for i in range(0, 32):
bit_count = 0
for num in nums:
bit_count += (num >> i) & 1
total += bit_count * (l - bit_count)
return total
| class Solution(object):
def total_hamming_distance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
(total, l) = (0, len(nums))
for i in range(0, 32):
bit_count = 0
for num in nums:
bit_count += num >> i & 1
total += bit_count * (l - bit_count)
return total |
class ColumnLayer(tf.keras.layers.Layer):
def __init__(
self,
upstream_dim,
num_column_instances,
position_dim,
context_fan_in,
context_num_samples,
context_initial_sharpness,
train_context,
noise_rate,
bypass_rate,
):
super(ColumnLayer, self).__init__()
self.upstream_dim = upstream_dim
self.num_column_instances = num_column_instances
self.position_dim = position_dim
self.context_fan_in = context_fan_in
self.context_num_samples = context_num_samples
self.context_initial_sharpness = context_initial_sharpness
self.train_context = train_context
self.noise_rate = noise_rate
self.bypass_rate = bypass_rate
def build(self, input_shape):
self.context_aggregator = ContextAggregationLayer(
context_fan_in=self.context_fan_in,
position_dim=self.position_dim,
num_samples=self.context_num_samples,
initial_sharpness=self.context_initial_sharpness,
train_context=self.train_context,
dtype='mixed_float16',
)
self.permanence_separator = PermanenceSeparatorLayer(
upstream_dim=self.upstream_dim,
position_dim=self.position_dim,
bypass_rate=self.bypass_rate,
noise_rate=self.noise_rate,
)
self.column_selector = ColumnSelectorLayer(
num_column_instances=self.num_column_instances,
)
super(ColumnLayer, self).build(input_shape)
def reconstruct(self, upstream_state):
reconstruction = self.permanence_separator.reconstruct(upstream_state)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return reconstruction
def call(self, centered_input, training, is_bootstrapping=False):
enriched_input = self.context_aggregator(centered_input)
full_upstream_state, full_reconstruction = self.permanence_separator(
enriched_input,
is_bootstrapping=is_bootstrapping,
)
full_reconstruction = self.context_aggregator.reconstruct(full_reconstruction)
upstream_state = self.column_selector(full_upstream_state)
# Restore unit length for the selected upstream states
upstream_state = tf.math.l2_normalize(upstream_state, axis=-1, epsilon=tf.keras.backend.epsilon())
reconstruction = self.permanence_separator.reconstruct(upstream_state, training=training)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return [upstream_state, reconstruction, full_reconstruction]
| class Columnlayer(tf.keras.layers.Layer):
def __init__(self, upstream_dim, num_column_instances, position_dim, context_fan_in, context_num_samples, context_initial_sharpness, train_context, noise_rate, bypass_rate):
super(ColumnLayer, self).__init__()
self.upstream_dim = upstream_dim
self.num_column_instances = num_column_instances
self.position_dim = position_dim
self.context_fan_in = context_fan_in
self.context_num_samples = context_num_samples
self.context_initial_sharpness = context_initial_sharpness
self.train_context = train_context
self.noise_rate = noise_rate
self.bypass_rate = bypass_rate
def build(self, input_shape):
self.context_aggregator = context_aggregation_layer(context_fan_in=self.context_fan_in, position_dim=self.position_dim, num_samples=self.context_num_samples, initial_sharpness=self.context_initial_sharpness, train_context=self.train_context, dtype='mixed_float16')
self.permanence_separator = permanence_separator_layer(upstream_dim=self.upstream_dim, position_dim=self.position_dim, bypass_rate=self.bypass_rate, noise_rate=self.noise_rate)
self.column_selector = column_selector_layer(num_column_instances=self.num_column_instances)
super(ColumnLayer, self).build(input_shape)
def reconstruct(self, upstream_state):
reconstruction = self.permanence_separator.reconstruct(upstream_state)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return reconstruction
def call(self, centered_input, training, is_bootstrapping=False):
enriched_input = self.context_aggregator(centered_input)
(full_upstream_state, full_reconstruction) = self.permanence_separator(enriched_input, is_bootstrapping=is_bootstrapping)
full_reconstruction = self.context_aggregator.reconstruct(full_reconstruction)
upstream_state = self.column_selector(full_upstream_state)
upstream_state = tf.math.l2_normalize(upstream_state, axis=-1, epsilon=tf.keras.backend.epsilon())
reconstruction = self.permanence_separator.reconstruct(upstream_state, training=training)
reconstruction = self.context_aggregator.reconstruct(reconstruction)
return [upstream_state, reconstruction, full_reconstruction] |
###################
# COLOR CONSTANTS
###################
HEADER = '\033[95m'
OK_BLUE = '\033[94m'
OK_GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
###########################
# ERROR MESSAGES CONSTANTS
###########################
BASE_ERROR_MSG = '\n\nAll available commands:\n' \
'flaskbox --init \tInit the flaskbox.yml file' \
'\nflaskbox --start \tRun your mock Server\n'
FILE_EXISTS_MESSAGE = OK_GREEN + 'flaskbox.yml' \
+ ENDC + ' already exists'
NOT_EXISTS_MESSAGE = 'You need to create the ' + OK_GREEN + \
'flaskbox.yml' + ENDC + ' file' + BASE_ERROR_MSG
| header = '\x1b[95m'
ok_blue = '\x1b[94m'
ok_green = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
base_error_msg = '\n\nAll available commands:\nflaskbox --init \tInit the flaskbox.yml file\nflaskbox --start \tRun your mock Server\n'
file_exists_message = OK_GREEN + 'flaskbox.yml' + ENDC + ' already exists'
not_exists_message = 'You need to create the ' + OK_GREEN + 'flaskbox.yml' + ENDC + ' file' + BASE_ERROR_MSG |
def copyFile():
with open('test.txt') as file:
content = file.read()
with open('anotherTest.txt', 'w') as file:
file.write(content)
copyFile() | def copy_file():
with open('test.txt') as file:
content = file.read()
with open('anotherTest.txt', 'w') as file:
file.write(content)
copy_file() |
#!/usr/bin/env python3
# Day 10: Excel Sheet Column Number
#
# Given a column title as appear in an Excel sheet, return its corresponding
# column number.
# A = 1
# B = 2
# C = 3
# ...
# Z = 26
# AA = 27
# AB = 28
# ...
class Solution:
def titleToNumber(self, s: str) -> int:
# In other words, convert from base 26 to base 10, plus 1 as we
# don't start at zero
decimal = 0
for digit in s:
decimal *= 26
decimal += ord(digit) - ord("A") + 1
return decimal
# Tests
assert Solution().titleToNumber("A") == 1
assert Solution().titleToNumber("AB") == 28
assert Solution().titleToNumber("ZY") == 701
| class Solution:
def title_to_number(self, s: str) -> int:
decimal = 0
for digit in s:
decimal *= 26
decimal += ord(digit) - ord('A') + 1
return decimal
assert solution().titleToNumber('A') == 1
assert solution().titleToNumber('AB') == 28
assert solution().titleToNumber('ZY') == 701 |
class MissingValueError(ValueError):
pass
class ValidationError(ValueError):
pass
| class Missingvalueerror(ValueError):
pass
class Validationerror(ValueError):
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 21 20:59:18 2021
@author: anelmusic
"""
def train_model(model, train_ds, val_ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss):
model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
steps_per_epoch =num_train_imgs//batch_size
val_steps = num_val_imgs//batch_size
model_history = model.fit(train_ds, epochs=epochs,
steps_per_epoch=val_steps,
validation_steps=val_steps,
validation_data=val_ds)
model.save_weights(config.SAVE_LOAD_WEIGHTS_PATH)
def evaluate_model(model, ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss):
model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
steps_per_epoch =num_train_imgs//batch_size
val_steps = num_val_imgs//batch_size
model.load_weights(config.SAVE_LOAD_WEIGHTS_PATH)
loss, acc = model.evaluate(ds, steps= val_steps)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc)) | """
Created on Mon Jun 21 20:59:18 2021
@author: anelmusic
"""
def train_model(model, train_ds, val_ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss):
model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
steps_per_epoch = num_train_imgs // batch_size
val_steps = num_val_imgs // batch_size
model_history = model.fit(train_ds, epochs=epochs, steps_per_epoch=val_steps, validation_steps=val_steps, validation_data=val_ds)
model.save_weights(config.SAVE_LOAD_WEIGHTS_PATH)
def evaluate_model(model, ds, epochs, batch_size, num_train_imgs, num_val_imgs, optimizer, metrics, loss):
model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
steps_per_epoch = num_train_imgs // batch_size
val_steps = num_val_imgs // batch_size
model.load_weights(config.SAVE_LOAD_WEIGHTS_PATH)
(loss, acc) = model.evaluate(ds, steps=val_steps)
print('Restored model, accuracy: {:5.2f}%'.format(100 * acc)) |
class AImodel:
def __init__(self):
pass
def process(self,input):
return -1 | class Aimodel:
def __init__(self):
pass
def process(self, input):
return -1 |
#Factorial digit sum
#Recursive funtion to calculate
def factorial(num):
#For negative numbers 0 or 1 will return 1
if num <= 1:
return 1
else:
#If num is greater than 1 multiply num by num-1 recursively until it returns 1(lowest value)
return num * factorial(num-1)
#Ask user to input a number and asgn value to f
f = input("Please, enter a natural number to calculate factorial from: ")
#Call function passing in f parsed and print the returning value.
print(factorial(int(f)))
| def factorial(num):
if num <= 1:
return 1
else:
return num * factorial(num - 1)
f = input('Please, enter a natural number to calculate factorial from: ')
print(factorial(int(f))) |
class Solution:
def minRefuelStops(self, target, startFuel, stations):
"""
:type target: int
:type startFuel: int
:type stations: List[List[int]]
:rtype: int
"""
# dp[i] means maximum distance with ith refuel
n = len(stations)
dp = [startFuel] + [0] * n
for i in range(n): # for every station
for j in reversed(range(i + 1)):
if dp[j] >= stations[i][0]:
dp[j + 1] = max(dp[j + 1], dp[j] + stations[i][1])
return next((i for i in range(len(dp)) if dp[i] >= target), -1)
| class Solution:
def min_refuel_stops(self, target, startFuel, stations):
"""
:type target: int
:type startFuel: int
:type stations: List[List[int]]
:rtype: int
"""
n = len(stations)
dp = [startFuel] + [0] * n
for i in range(n):
for j in reversed(range(i + 1)):
if dp[j] >= stations[i][0]:
dp[j + 1] = max(dp[j + 1], dp[j] + stations[i][1])
return next((i for i in range(len(dp)) if dp[i] >= target), -1) |
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n = len(arr)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
cnt += abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c
return cnt
| class Solution:
def count_good_triplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n = len(arr)
cnt = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
cnt += abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and (abs(arr[i] - arr[k]) <= c)
return cnt |
"""
3, 6, 7, 11, H=8
4 4. 4. 4
1 2. 2. 3 sum()=8
34567
FTTTT
[30,11,23,4,20], H = 5
29,30,31
F. T. T
Input: piles = [3,6,7,11], H = 8
3,6,7,11
3
6
1 1
45678
FFTTT
30,11,23,4,20
30
1. 1. 1. 1. 1
5T
29
2. 1. 1 1. 1
6 F
"""
class Solution:
def minEatingSpeed(self, piles: List[int], H: int) -> int:
def canEatPile(rate):
hoursFull = 0
for p in piles:
# Eat until full
hoursFull += p // rate
if p % rate > 0:
hoursFull += 1
return hoursFull <= H
left, right = 1, max(piles)
while left < right:
mid = left + (right - left) // 2
if canEatPile(mid):
right = mid
else:
left = mid + 1
return left
| """
3, 6, 7, 11, H=8
4 4. 4. 4
1 2. 2. 3 sum()=8
34567
FTTTT
[30,11,23,4,20], H = 5
29,30,31
F. T. T
Input: piles = [3,6,7,11], H = 8
3,6,7,11
3
6
1 1
45678
FFTTT
30,11,23,4,20
30
1. 1. 1. 1. 1
5T
29
2. 1. 1 1. 1
6 F
"""
class Solution:
def min_eating_speed(self, piles: List[int], H: int) -> int:
def can_eat_pile(rate):
hours_full = 0
for p in piles:
hours_full += p // rate
if p % rate > 0:
hours_full += 1
return hoursFull <= H
(left, right) = (1, max(piles))
while left < right:
mid = left + (right - left) // 2
if can_eat_pile(mid):
right = mid
else:
left = mid + 1
return left |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
###################################################################################################
########################### Global variables #################################
###################################################################################################
adcSym_SEQR1_USCH = []
adcCHMenu = []
adcSym_CH_CHER = []
adcSym_CH_NAME = []
adcSym_CH_PositiveInput = []
adcSym_CH_NegativeInput = []
adcSym_CH_IER_EOC = []
###################################################################################################
########################### Callback Functions #################################
###################################################################################################
def adcClockControl(symbol, event):
clockSet = False
Database.clearSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE")
for channelID in range(0, 12):
if (adcSym_CH_CHER[channelID].getValue() == True):
clockSet = True
if(clockSet == True):
Database.setSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE", True, 2)
else:
Database.setSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE", False, 2)
def adcInterruptEnableDisableCallback(symbol, event):
global interruptSymbolEnable
deviceHandlerLastName = "_InterruptHandler"
interruptLastNameHandler = "_INTERRUPT_HANDLER"
interruptLastNameHandlerLock = "_INTERRUPT_HANDLER_LOCK"
interruptNamespace = "core"
interruptSymbolHandler = adcInstanceName.getValue() + interruptLastNameHandler
interruptSymbolHandlerLock = adcInstanceName.getValue() + interruptLastNameHandlerLock
interruptSet = False
Database.clearSymbolValue("core", interruptSymbolHandlerLock)
Database.clearSymbolValue("core", interruptSymbolEnable)
Database.clearSymbolValue("core", interruptSymbolHandler)
for channelID in range(0, 12):
if (adcSym_CH_IER_EOC[channelID].getValue() == True):
interruptSet = True
if (adcSym_IER_COMPE.getValue() == True):
interruptSet = True
if(interruptSet == True):
Database.setSymbolValue( interruptNamespace, interruptSymbolEnable, True, 2)
Database.setSymbolValue( interruptNamespace, interruptSymbolHandler, adcInstanceName.getValue() + deviceHandlerLastName, 2)
Database.setSymbolValue( interruptNamespace, interruptSymbolHandlerLock, True, 2)
else:
#Do not try to restore the handler name to the default
Database.setSymbolValue( interruptNamespace, interruptSymbolHandlerLock, False, 2)
Database.setSymbolValue( interruptNamespace, interruptSymbolEnable, False, 2)
def dependencyClockStatus(symbol, event):
clockSet = False
clock = bool(Database.getSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_ENABLE"))
for channelID in range(0, 12):
if (adcSym_CH_CHER[channelID].getValue() == True):
clockSet = True
if(clockSet == True and clock == False):
symbol.setVisible(True)
else:
symbol.setVisible(False)
def dependencyIntStatus(symbol, event):
global interruptSymbolEnable
interruptSet = False
interrupt = bool(Database.getSymbolValue("core", interruptSymbolEnable))
for channelID in range(0, 12):
if (adcSym_CH_IER_EOC[channelID].getValue() == True):
interruptSet = True
if (adcSym_IER_COMPE.getValue() == True):
interruptSet = True
if(interruptSet == True and interrupt == False):
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adcGetPeripheralClock():
peripheral_clk_freq = int(Database.getSymbolValue("core", adcInstanceName.getValue() + "_CLOCK_FREQUENCY"))
return peripheral_clk_freq
def adcPrescalWarning(symbol, event):
clock = adcGetPeripheralClock()
prescaler = adcSym_MR_PRESCAL.getValue() + 1
adcFreq = clock / (2 * prescaler)
if (adcFreq < 200000):
symbol.setLabel("ADC Frequency < 200,000 Hz. Decrease prescaler value. ")
symbol.setVisible(True)
elif (adcFreq > 20000000):
symbol.setLabel("ADC Frequency > 20,000,000 Hz. Increase prescaler value. ")
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adcFreqCalc(symbol, event):
clock = adcGetPeripheralClock()
prescaler = adcSym_MR_PRESCAL.getValue() + 1
adcFreq = clock / (2 * prescaler)
symbol.clearValue()
symbol.setValue(adcFreq, 2)
def adcCalcConversionTime(adcSym_CONV_TIME, event):
clock = adcGetPeripheralClock()
adcClockSourceInvalidSym.setVisible((clock == 0))
if (clock == 0):
clock = 1
prescaler = adcSym_MR_PRESCAL.getValue() + 1
over_sampling_rate = adcSym_EMR_OSR_VALUE.getSelectedKey()
multiplier = 1
if (over_sampling_rate == "NO_AVERAGE"):
multiplier = 1
elif (over_sampling_rate == "OSR4_SIN") or (over_sampling_rate == "OSR4_MUL"):
multiplier = 4
elif (over_sampling_rate == "OSR16_SIN") or (over_sampling_rate == "OSR16_MUL"):
multiplier = 16
elif (over_sampling_rate == "OSR64_SIN") or (over_sampling_rate == "OSR64_MUL"):
multiplier = 64
elif (over_sampling_rate == "OSR256_SIN") or (over_sampling_rate == "OSR256_MUL"):
multiplier = 256
conv_time = ((2 * prescaler) * 21.0 * 1000000.0 * multiplier) / clock
adcSym_CONV_TIME.setLabel("**** Conversion Time is "+str(conv_time)+" us ****")
def adcUserSeqVisible(adcSym_SEQR1_USCHLocal, event):
for channelID in range(0, 11):
adcSym_SEQR1_USCH[channelID].setVisible(event["value"])
def adcCHNameVisible(symbol, event):
id = []
#split as per "_" to get the channel number
id = symbol.getID().split("_")
channelID = int(id[1])
adcSym_CH_NAME[channelID].setVisible(event["value"])
def adcCHPosInpVisible(symbol, event):
id = []
#split as per "_" to get the channel number
id = symbol.getID().split("_")
channelID = int(id[1])
adcSym_CH_PositiveInput[channelID].setVisible(event["value"])
def adcCHNegInpVisible(symbol, event):
id = []
#split as per "_" to get the channel number
id = symbol.getID().split("_")
channelID = int(id[1])
adcSym_CH_NegativeInput[channelID].setVisible(event["value"])
def adcCHInterruptVisible(symbol, event):
id = []
#split as per "_" to get the channel number
id = symbol.getID().split("_")
channelID = int(id[1])
adcSym_CH_IER_EOC[channelID].setVisible(event["value"])
def adcCHEnable(symbol, event):
id = []
#split as per "_" to get the channel number
id = symbol.getID().split("_")
channelID = int(id[1])
#for diff mode, hide next odd channel
if(event["id"].find("_NEG_INP") > 0):
if(event["value"] == "AN"+str(channelID)):
adcCHMenu[channelID].setVisible(False)
else:
adcCHMenu[channelID].setVisible(True)
def adcTriggerVisible(symbol, event):
symObj = event["symbol"]
triggerVal = int(symObj.getSelectedValue())
if((triggerVal >= 1) and (triggerVal <= 3)):
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adcTriggerTimeVisible(symbol, event):
if(event["id"] == "ADC_TRGR_MODE" and event["value"] == 4):
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adcCalcTriggerPeriod(symbol, event):
trgper = int((adcSym_TRIGGER_TIME.getValue() * adcSym_Clock.getValue() / 1000.0) - 1) #Trigger time is in millisecond
if(event["id"] == "ADC_TRIGGER_TIME" or (event["id"] == "ADC_TRGR_MODE" and event["value"] == 4)):
symbol.setValue(trgper, 2)
else:
symbol.clearValue()
def adcSymbolVisible(symbol, event):
symbol.setVisible(event["value"])
###################################################################################################
########################### Component #################################
###################################################################################################
def instantiateComponent(adcComponent):
global adcInstanceName
global interruptSymbolEnable
global adcClockSourceInvalidSym
adcInstanceName = adcComponent.createStringSymbol("ADC_INSTANCE_NAME", None)
adcInstanceName.setVisible(False)
adcInstanceName.setDefaultValue(adcComponent.getID().upper())
Log.writeInfoMessage("Running " + adcInstanceName.getValue())
interruptLastNameEnable = "_INTERRUPT_ENABLE"
interruptSymbolEnable = adcInstanceName.getValue() + interruptLastNameEnable
#------------------------- ATDF Read -------------------------------------
availablePins = [] # array to save available pins
channel = ["False", "False", "False", "False", "False", "False", "False", "False", "False", "False", "False", "False"] #array to save available channels
adcChannelsValues = [] #array used for combo symbol
adcChannelsValues.append("NONE")
children = []
val = ATDF.getNode("/avr-tools-device-file/pinouts/pinout@[name=\"" + Database.getSymbolValue("core", "COMPONENT_PACKAGE") + "\"]")
children = val.getChildren()
for pad in range(0, len(children)):
availablePins.append(children[pad].getAttribute("pad"))
adc_signals = []
adc = ATDF.getNode("/avr-tools-device-file/devices/device/peripherals/module@[name=\"ADC\"]/instance@[name=\""+adcInstanceName.getValue()+"\"]/signals")
adc_signals = adc.getChildren()
for pad in range(0, len(adc_signals)):
group = adc_signals[pad].getAttribute("group")
if (("AD" in group) and ("index" in adc_signals[pad].getAttributeList())):
padSignal = adc_signals[pad].getAttribute("pad")
if padSignal in availablePins:
channel[int(adc_signals[pad].getAttribute("index"))] = "True"
adcChannelsValues.append("CH"+adc_signals[pad].getAttribute("index"))
adcSym_AvailableChannels = adcComponent.createComboSymbol("ADC_AVAILABLE_CHANNELS", None, channel)
adcSym_AvailableChannels.setVisible(False)
adcMenu = adcComponent.createMenuSymbol("ADC_MENU", None)
adcMenu.setLabel("ADC Configuration")
#max no of channels
adcSym_NUM_CHANNELS = adcComponent.createIntegerSymbol("ADC_NUM_CHANNELS", adcMenu)
adcSym_NUM_CHANNELS.setDefaultValue(12)
adcSym_NUM_CHANNELS.setVisible(False)
# Provide a source clock selection symbol for masks that supports it
valueGroupPath = "/avr-tools-device-file/modules/module@[name=\"ADC\"]/value-group@[name=\"ADC_EMR__SRCCLK\"]"
valueGroup = ATDF.getNode(valueGroupPath)
if valueGroup is not None:
adcSym_EMR_SRCCLK = adcComponent.createKeyValueSetSymbol("ADC_CLK_SRC", adcMenu)
adcSym_EMR_SRCCLK.setLabel(valueGroup.getAttribute("caption"))
values = valueGroup.getChildren()
for index in range(len(values)):
adcSym_EMR_SRCCLK.addKey(values[index].getAttribute("name"),
values[index].getAttribute("value"),
values[index].getAttribute("caption"))
adcSym_EMR_SRCCLK.setOutputMode("Key")
adcSym_EMR_SRCCLK.setDisplayMode("Key")
adcClockSourceInvalidSym = adcComponent.createCommentSymbol("ADC_CLK_SRC_INVALID_COMMENT", adcMenu)
adcClockSourceInvalidSym.setLabel("Warning!!! " + adcInstanceName.getValue() + " clock frequency is zero")
adcClockSourceInvalidSym.setVisible(False)
#Clock prescaler
global adcSym_MR_PRESCAL
adcSym_MR_PRESCAL = adcComponent.createIntegerSymbol("ADC_MR_PRESCAL", adcMenu)
adcSym_MR_PRESCAL.setLabel("Select Prescaler")
adcSym_MR_PRESCAL.setDefaultValue(9)
adcSym_MR_PRESCAL.setMin(0)
adcSym_MR_PRESCAL.setMax(255)
#clock selection
global adcSym_Clock
adcSym_Clock = adcComponent.createIntegerSymbol("ADC_CLK", adcMenu)
adcSym_Clock.setLabel("Clock Frequency (Hz)")
defaultAdcFreq = int(adcGetPeripheralClock() / (2 * (adcSym_MR_PRESCAL.getValue() + 1)))
adcSym_Clock.setDefaultValue(defaultAdcFreq)
adcSym_Clock.setVisible(True)
adcSym_Clock.setReadOnly(True)
adcSym_Clock.setDependencies(adcFreqCalc, ["ADC_MR_PRESCAL", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"])
adcSym_PRESCAL_WARNING = adcComponent.createCommentSymbol("ADC_PRESCAL_WARNING", adcMenu)
adcSym_PRESCAL_WARNING.setLabel("**** ADC Frequency = " + str(defaultAdcFreq) + " Hz. ****")
adcSym_PRESCAL_WARNING.setVisible(False)
adcSym_PRESCAL_WARNING.setDependencies(adcPrescalWarning, ["ADC_MR_PRESCAL", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"])
#Result resolution
#Added keys here as combining two bit-fields EMR_ASTE and EMR_OSR
global adcSym_EMR_OSR_VALUE
adcSym_EMR_OSR_VALUE = adcComponent.createKeyValueSetSymbol("ADC_EMR_OSR_VALUE", adcMenu)
adcSym_EMR_OSR_VALUE.setLabel("Result Resolution")
adcSym_EMR_OSR_VALUE.setDefaultValue(0)
adcSym_EMR_OSR_VALUE.setOutputMode("Value")
adcSym_EMR_OSR_VALUE.setDisplayMode("Description")
valueGroup = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"ADC\"]/value-group@[name=\"ADC_EMR__OSR\"]")
if valueGroup is not None:
osrValues = valueGroup.getChildren()
for index in range(len(osrValues)):
if osrValues[index].getAttribute("name") == "NO_AVERAGE":
adcSym_EMR_OSR_VALUE.addKey("NO_AVERAGE", "0", "12-bit")
elif osrValues[index].getAttribute("name") == "OSR4":
adcSym_EMR_OSR_VALUE.addKey("OSR4_SIN", "1", "13-bit - single trigger averaging")
adcSym_EMR_OSR_VALUE.addKey("OSR4_MUL", "2", "13-bit - multi trigger averaging")
elif osrValues[index].getAttribute("name") == "OSR16":
adcSym_EMR_OSR_VALUE.addKey("OSR16_SIN", "3", "14-bit - single trigger averaging")
adcSym_EMR_OSR_VALUE.addKey("OSR16_MUL", "4", "14-bit - multi trigger averaging")
elif osrValues[index].getAttribute("name") == "OSR64":
adcSym_EMR_OSR_VALUE.addKey("OSR64_SIN", "5", "15-bit - single trigger averaging")
adcSym_EMR_OSR_VALUE.addKey("OSR64_MUL", "6", "15-bit - multi trigger averaging")
elif osrValues[index].getAttribute("name") == "OSR256":
adcSym_EMR_OSR_VALUE.addKey("OSR256_SIN", "7", "16-bit - single trigger averaging")
adcSym_EMR_OSR_VALUE.addKey("OSR256_MUL", "8", "16-bit - multi trigger averaging")
#Conversion time
adcSym_CONV_TIME = adcComponent.createCommentSymbol("ADC_CONV_TIME", adcMenu)
defaultConvTime = ((2 * (adcSym_MR_PRESCAL.getValue() + 1)) * 21.0 * 1000000.0 * 1) / adcGetPeripheralClock()
adcSym_CONV_TIME.setLabel("**** Conversion Time is " + str(defaultConvTime) + " us ****")
adcSym_CONV_TIME.setDependencies(adcCalcConversionTime, ["ADC_MR_PRESCAL", "ADC_EMR_OSR_VALUE", "core." + adcInstanceName.getValue() + "_CLOCK_FREQUENCY"])
#Result sign
adcSym_EMR_SIGNMODE_VALUE = adcComponent.createKeyValueSetSymbol("ADC_EMR_SIGNMODE_VALUE", adcMenu)
adcSym_EMR_SIGNMODE_VALUE.setLabel("Result Sign")
adcSym_EMR_SIGNMODE_VALUE.setDefaultValue(0)
adcSym_EMR_SIGNMODE_VALUE.setOutputMode("Key")
adcSym_EMR_SIGNMODE_VALUE.setDisplayMode("Description")
adcSym_EMR_SIGNMODE_VALUE.addKey("SE_UNSG_DF_SIGN", "0", "Single Ended: Unsigned, Differential: Signed")
adcSym_EMR_SIGNMODE_VALUE.addKey("SE_SIGN_DF_UNSG", "1", "Single Ended: Signed, Differential: Unsigned")
adcSym_EMR_SIGNMODE_VALUE.addKey("ALL_UNSIGNED", "2", "All Unsigned")
adcSym_EMR_SIGNMODE_VALUE.addKey("ALL_SIGNED", "3", "All Signed")
#Trigger Mode
adcSym_TRGR_MODE = adcComponent.createKeyValueSetSymbol("ADC_TRGR_MODE", adcMenu)
adcSym_TRGR_MODE.setLabel("Trigger Mode")
adcSym_TRGR_MODE.setDefaultValue(5)
adcSym_TRGR_MODE.setOutputMode("Key")
adcSym_TRGR_MODE.setDisplayMode("Description")
adcSym_TRGR_MODE.addKey("TRGMOD_NO_TRIGGER", "0", "Software Trigger")
adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_RISE", "1", "External Trigger Rising Edge")
adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_FALL", "2", "External Trigger Falling Edge")
adcSym_TRGR_MODE.addKey("TRGMOD_EXT_TRIG_ANY", "3", "External Trigger Any Edge")
#adcSym_TRGR_MODE.addKey("TRGMOD_PEN_TRIG", "4", "Pen Detect Trigger") #For Touchscreen mode only
adcSym_TRGR_MODE.addKey("TRGMOD_PERIOD_TRIG", "4", "ADC Internal Periodic Trigger")
adcSym_TRGR_MODE.addKey("TRGMOD_CONTINUOUS", "5", "Continuous")
#External Trigger Mode
adcSym_MR_TRGSEL_VALUE = adcComponent.createKeyValueSetSymbol("ADC_MR_TRGSEL_VALUE", adcSym_TRGR_MODE)
adcSym_MR_TRGSEL_VALUE.setLabel("Select External Trigger Input")
adcSym_MR_TRGSEL_VALUE.setVisible(False)
adcSym_MR_TRGSEL_VALUE.setDefaultValue(1)
adcSym_MR_TRGSEL_VALUE.setOutputMode("Key")
adcSym_MR_TRGSEL_VALUE.setDisplayMode("Description")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG0", "0", "ADTRG")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG1", "1", "TIOA0")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG2", "2", "TIOA1")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG3", "3", "TIOA2")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG4", "4", "PWM event line 0")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG5", "5", "PWM event line 1")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG6", "6", "TIOA3")
adcSym_MR_TRGSEL_VALUE.addKey("TRGSEL_ADC_TRIG7", "7", "RTCOUT0")
adcSym_MR_TRGSEL_VALUE.setDependencies(adcTriggerVisible, ["ADC_TRGR_MODE"])
#ADC Internal Periodic Trigger
global adcSym_TRIGGER_TIME
adcSym_TRIGGER_TIME = adcComponent.createIntegerSymbol("ADC_TRIGGER_TIME", adcSym_TRGR_MODE)
adcSym_TRIGGER_TIME.setLabel("Trigger Period (ms)")
adcSym_TRIGGER_TIME.setDefaultValue(2)
adcSym_TRIGGER_TIME.setMin(1)
adcSym_TRIGGER_TIME.setMax(int((65536 * 1000.0) / adcSym_Clock.getValue()))
adcSym_TRIGGER_TIME.setVisible(False)
adcSym_TRIGGER_TIME.setDependencies(adcTriggerTimeVisible, ["ADC_TRGR_MODE"])
adcSym_TRGR_TRGPER = adcComponent.createIntegerSymbol("ADC_TRGR_TRIGGER_PERIOD", adcSym_TRIGGER_TIME)
adcSym_TRGR_TRGPER.setVisible(False)
adcSym_TRGR_TRGPER.setDependencies(adcCalcTriggerPeriod, ["ADC_TRIGGER_TIME", "ADC_TRGR_MODE"])
#Sleep Mode
adcSym_MR_SLEEP = adcComponent.createBooleanSymbol("ADC_MR_SLEEP", adcMenu)
adcSym_MR_SLEEP.setLabel("Sleep Mode")
adcSym_MR_SLEEP.setDefaultValue(False)
adcFastWakeupValues = ["OFF", "ON"]
adcSym_MR_FWUP = adcComponent.createComboSymbol("ADC_MR_FWUP", adcSym_MR_SLEEP, adcFastWakeupValues)
adcSym_MR_FWUP.setLabel("Fast Wakeup")
adcSym_MR_FWUP.setDefaultValue(adcFastWakeupValues[0])
adcSym_MR_FWUP.setVisible(False)
adcSym_MR_FWUP.setDependencies(adcSymbolVisible, ["ADC_MR_SLEEP"])
#Automatic Window Comparison
adcSym_COMP_WINDOW = adcComponent.createBooleanSymbol("ADC_COMP_WINDOW", adcMenu)
adcSym_COMP_WINDOW.setLabel("Automatic Window Comparison")
adcSym_COMP_WINDOW.setDefaultValue(False)
adcSym_EMR_CMPMODE = adcComponent.createKeyValueSetSymbol("ADC_EMR_CMPMODE", adcSym_COMP_WINDOW)
adcSym_EMR_CMPMODE.setLabel("Comparison Mode")
adcSym_EMR_CMPMODE.setDefaultValue(0)
adcSym_EMR_CMPMODE.setOutputMode("Key")
adcSym_EMR_CMPMODE.setDisplayMode("Description")
adcSym_EMR_CMPMODE.addKey("CMPMODE_LOW", "0", "Vin < VLo")
adcSym_EMR_CMPMODE.addKey("CMPMODE_HIGH", "1", "Vin < VHi")
adcSym_EMR_CMPMODE.addKey("CMPMODE_IN", "2", "VLo < Vin < VHi")
adcSym_EMR_CMPMODE.addKey("CMPMODE_OUT", "3", "VHi < Vin < VLo")
adcSym_EMR_CMPMODE.setVisible(False)
adcSym_EMR_CMPMODE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
adcSym_EMR_CMPTYPE = adcComponent.createKeyValueSetSymbol("ADC_EMR_CMPTYPE", adcSym_COMP_WINDOW)
adcSym_EMR_CMPTYPE.setLabel("Comparison Type")
adcSym_EMR_CMPTYPE.setDefaultValue(0)
adcSym_EMR_CMPTYPE.setOutputMode("Key")
adcSym_EMR_CMPTYPE.setDisplayMode("Description")
adcSym_EMR_CMPTYPE.addKey("CMPTYPE_FLAG_ONLY", "0", "0-No Comparison")
adcSym_EMR_CMPTYPE.addKey("CMPTYPE_START_CONDITION", "1", "1-Comparison match")
adcSym_EMR_CMPTYPE.setVisible(False)
adcSym_EMR_CMPTYPE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
adcCompSelectedChannelValues = adcChannelsValues[1:]
adcCompSelectedChannelValues.append("All");
adcSym_EMR_CMPSEL = adcComponent.createComboSymbol("ADC_EMR_CMPSEL", adcSym_COMP_WINDOW, adcCompSelectedChannelValues)
adcSym_EMR_CMPSEL.setLabel("Comparison Selected Channel")
adcSym_EMR_CMPSEL.setDefaultValue(adcCompSelectedChannelValues[0])
adcSym_EMR_CMPSEL.setVisible(False)
adcSym_EMR_CMPSEL.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
adcSym_CWR_LOWTHRES = adcComponent.createIntegerSymbol("ADC_CWR_LOWTHRES_VALUE", adcSym_COMP_WINDOW)
adcSym_CWR_LOWTHRES.setLabel("Low Threshold")
adcSym_CWR_LOWTHRES.setDefaultValue(0)
adcSym_CWR_LOWTHRES.setVisible(False)
adcSym_CWR_LOWTHRES.setMin(0)
adcSym_CWR_LOWTHRES.setMax(16383)
adcSym_CWR_LOWTHRES.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
adcSym_CWR_HIGHTHRES = adcComponent.createIntegerSymbol("ADC_CWR_HIGHTHRES_VALUE", adcSym_COMP_WINDOW)
adcSym_CWR_HIGHTHRES.setLabel("High Threshold")
adcSym_CWR_HIGHTHRES.setDefaultValue(0)
adcSym_CWR_HIGHTHRES.setVisible(False)
adcSym_CWR_HIGHTHRES.setMin(0)
adcSym_CWR_HIGHTHRES.setMax(16383)
adcSym_CWR_HIGHTHRES.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
global adcSym_IER_COMPE
adcSym_IER_COMPE = adcComponent.createBooleanSymbol("ADC_IER_COMPE", adcSym_COMP_WINDOW)
adcSym_IER_COMPE.setLabel("Comparison Event Interrupt")
adcSym_IER_COMPE.setDefaultValue(False)
adcSym_IER_COMPE.setVisible(False)
adcSym_IER_COMPE.setDependencies(adcSymbolVisible, ["ADC_COMP_WINDOW"])
#------------------------------------------------------------------------------------
#user sequence menu
adcUserSeq = adcComponent.createMenuSymbol("ADC_USER_SEQ", None)
adcUserSeq.setLabel("User Channel Sequence Configuration")
#user sequence comment
adcSym_USEQ_COMMENT = adcComponent.createCommentSymbol("ADC_USEQ_COMMENT", adcUserSeq)
adcSym_USEQ_COMMENT.setLabel("**** Configure selected channels in the Channel Configuration Menu ****")
#enable user sequence
adcSym_MR_USEQ = adcComponent.createBooleanSymbol("ADC_MR_USEQ", adcUserSeq)
adcSym_MR_USEQ.setLabel("Enable User Sequence Mode")
adcSym_MR_USEQ.setDefaultValue(False)
for channelID in range(0, len(channel)-1):
#channel selection for user sequence
adcSym_SEQR1_USCH.append(channelID)
adcSym_SEQR1_USCH[channelID] = adcComponent.createComboSymbol("ADC_SEQR1_USCH" + str(channelID + 1), adcSym_MR_USEQ, adcChannelsValues)
adcSym_SEQR1_USCH[channelID].setLabel("Select Channel for Sequence Number " + str(channelID + 1))
adcSym_SEQR1_USCH[channelID].setDefaultValue(adcChannelsValues[0])
adcSym_SEQR1_USCH[channelID].setVisible(False)
adcSym_SEQR1_USCH[channelID].setDependencies(adcUserSeqVisible, ["ADC_MR_USEQ"])
#--------------------------------------------------------------------------------------
adcCHConfMenu = adcComponent.createMenuSymbol("ADC_CH_CONF", None)
adcCHConfMenu.setLabel("Channel Configuration")
# Loop runs for 12 channels and visibility of the channel is controlled as per available pins
for channelID in range(0, len(channel)):
#Channel menu
global adcCHMenu
adcCHMenu.append(channelID)
adcCHMenu[channelID] = adcComponent.createMenuSymbol("CH"+str(channelID), adcCHConfMenu)
adcCHMenu[channelID].setLabel("Channel "+str(channelID))
#Show channels as per available pins in package
if (channel[channelID] == "False"):
adcCHMenu[channelID].setVisible(False)
#Channel enable
adcSym_CH_CHER.append(channelID)
adcSym_CH_CHER[channelID] = adcComponent.createBooleanSymbol("ADC_"+str(channelID)+"_CHER", adcCHMenu[channelID])
adcSym_CH_CHER[channelID].setLabel("Enable Channel " + str(channelID))
adcSym_CH_CHER[channelID].setDefaultValue(False)
#enable corresponding channel pair for diff mode, e.g. CH0 and CH1
if (channelID % 2 == 1):
adcSym_CH_CHER[channelID].setDependencies(adcCHEnable, ["ADC_"+str(channelID-1)+"_NEG_INP"])
#Channel name
adcSym_CH_NAME.append(channelID)
adcSym_CH_NAME[channelID] = adcComponent.createStringSymbol("ADC_"+str(channelID)+"_NAME", adcSym_CH_CHER[channelID])
adcSym_CH_NAME[channelID].setLabel("Name")
adcSym_CH_NAME[channelID].setDefaultValue("CHANNEL_"+str(channelID))
adcSym_CH_NAME[channelID].setVisible(False)
adcSym_CH_NAME[channelID].setDependencies(adcCHNameVisible, ["ADC_"+str(channelID)+"_CHER"])
#Channel positive input
adcSym_CH_PositiveInput.append(channelID)
adcSym_CH_PositiveInput[channelID] = adcComponent.createStringSymbol("ADC_"+str(channelID)+"_POS_INP", adcSym_CH_CHER[channelID])
adcSym_CH_PositiveInput[channelID].setLabel("Positive Input")
adcSym_CH_PositiveInput[channelID].setDefaultValue("AN"+str(channelID))
adcSym_CH_PositiveInput[channelID].setReadOnly(True)
adcSym_CH_PositiveInput[channelID].setVisible(False)
adcSym_CH_PositiveInput[channelID].setDependencies(adcCHPosInpVisible, ["ADC_"+str(channelID)+"_CHER"])
#Channel negative input
adcSym_CH_NegativeInput.append(channelID)
adc_EvenChNegInput = ["GND", "AN"+str(channelID+1)]
adc_OddChNegInput = ["GND"]
if (channelID % 2 == 1):
adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol("ADC_"+str(channelID)+"_NEG_INP", adcSym_CH_CHER[channelID], adc_OddChNegInput)
adcSym_CH_NegativeInput[channelID].setReadOnly(True)
else:
adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol("ADC_"+str(channelID)+"_NEG_INP", adcSym_CH_CHER[channelID], adc_EvenChNegInput)
if (channel[channelID + 1] == "False"):
adcSym_CH_NegativeInput[channelID].setReadOnly(True)
adcSym_CH_NegativeInput[channelID].setLabel("Negative Input")
adcSym_CH_NegativeInput[channelID].setDefaultValue("GND")
adcSym_CH_NegativeInput[channelID].setVisible(False)
adcSym_CH_NegativeInput[channelID].setDependencies(adcCHNegInpVisible, ["ADC_"+str(channelID)+"_CHER"])
#Channel interrupt
adcSym_CH_IER_EOC.append(channelID)
adcSym_CH_IER_EOC[channelID] = adcComponent.createBooleanSymbol("ADC_"+str(channelID)+"_IER_EOC", adcSym_CH_CHER[channelID])
adcSym_CH_IER_EOC[channelID].setLabel("End of conversion interrupt")
adcSym_CH_IER_EOC[channelID].setDefaultValue(False)
adcSym_CH_IER_EOC[channelID].setVisible(False)
adcSym_CH_IER_EOC[channelID].setDependencies(adcCHInterruptVisible, ["ADC_"+str(channelID)+"_CHER"])
# Clock dynamic settings
adcSym_ClockControl = adcComponent.createBooleanSymbol("ADC_CLOCK_ENABLE", None)
adcSym_ClockControl.setDependencies(adcClockControl, ["ADC_0_CHER", "ADC_1_CHER", "ADC_2_CHER", "ADC_3_CHER", "ADC_4_CHER", \
"ADC_5_CHER", "ADC_6_CHER", "ADC_7_CHER", "ADC_8_CHER", "ADC_9_CHER", "ADC_10_CHER", "ADC_11_CHER"])
adcSym_ClockControl.setVisible(False)
# Interrupt Dynamic settings
adcSym_InterruptControl = adcComponent.createBooleanSymbol("ADC_INTERRUPT_ENABLE", None)
adcSym_InterruptControl.setDependencies(adcInterruptEnableDisableCallback, ["ADC_0_IER_EOC", "ADC_1_IER_EOC", "ADC_2_IER_EOC", "ADC_3_IER_EOC", "ADC_4_IER_EOC",\
"ADC_5_IER_EOC", "ADC_6_IER_EOC", "ADC_7_IER_EOC", "ADC_8_IER_EOC", "ADC_9_IER_EOC", "ADC_10_IER_EOC", "ADC_11_IER_EOC", "ADC_IER_COMPE"])
adcSym_InterruptControl.setVisible(False)
# Dependency Status
adcSym_ClkEnComment = adcComponent.createCommentSymbol("ADC_CLK_ENABLE_COMMENT", None)
adcSym_ClkEnComment.setVisible(False)
adcSym_ClkEnComment.setLabel("Warning!!! " + adcInstanceName.getValue() + " Peripheral Clock is Disabled in Clock Manager")
adcSym_ClkEnComment.setDependencies(dependencyClockStatus, ["core." + adcInstanceName.getValue() + "_CLOCK_ENABLE", "ADC_0_CHER", "ADC_1_CHER", "ADC_2_CHER", "ADC_3_CHER", "ADC_4_CHER", \
"ADC_5_CHER", "ADC_6_CHER", "ADC_7_CHER", "ADC_8_CHER", "ADC_9_CHER", "ADC_10_CHER", "ADC_11_CHER"])
adcSym_IntEnComment = adcComponent.createCommentSymbol("ADC_INTERRUPT_ENABLE_COMMENT", None)
adcSym_IntEnComment.setVisible(False)
adcSym_IntEnComment.setLabel("Warning!!! " + adcInstanceName.getValue() + " Interrupt is Disabled in Interrupt Manager")
adcSym_IntEnComment.setDependencies(dependencyIntStatus, ["core." + interruptSymbolEnable, "ADC_0_IER_EOC", "ADC_1_IER_EOC", "ADC_2_IER_EOC", "ADC_3_IER_EOC", "ADC_4_IER_EOC",\
"ADC_5_IER_EOC", "ADC_6_IER_EOC", "ADC_7_IER_EOC", "ADC_8_IER_EOC", "ADC_9_IER_EOC", "ADC_10_IER_EOC", "ADC_11_IER_EOC", "ADC_IER_COMPE"])
#--------------------------------------------------------------------------------------
configName = Variables.get("__CONFIGURATION_NAME")
###################################################################################################
########################### Code Generation #################################
###################################################################################################
adc = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"ADC\"]")
adcID = adc.getAttribute("id")
adcHeaderFile = adcComponent.createFileSymbol("ADC_HEADER", None)
adcHeaderFile.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc.h.ftl")
adcHeaderFile.setOutputName("plib_" + adcInstanceName.getValue().lower() + ".h")
adcHeaderFile.setDestPath("peripheral/adc/")
adcHeaderFile.setProjectPath("config/" + configName +"/peripheral/adc/")
adcHeaderFile.setType("HEADER")
adcHeaderFile.setMarkup(True)
adcCommonHeaderFile = adcComponent.createFileSymbol("ADC_COMMON_HEADER", None)
adcCommonHeaderFile.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc_common.h")
adcCommonHeaderFile.setOutputName("plib_adc_common.h")
adcCommonHeaderFile.setDestPath("peripheral/adc/")
adcCommonHeaderFile.setProjectPath("config/" + configName +"/peripheral/adc/")
adcCommonHeaderFile.setType("HEADER")
adcSource1File = adcComponent.createFileSymbol("ADC_SOURCE", None)
adcSource1File.setSourcePath("../peripheral/adc_" + str(adcID) + "/templates/plib_adc.c.ftl")
adcSource1File.setOutputName("plib_" + adcInstanceName.getValue().lower() + ".c")
adcSource1File.setDestPath("peripheral/adc/")
adcSource1File.setProjectPath("config/" + configName +"/peripheral/adc/")
adcSource1File.setType("SOURCE")
adcSource1File.setMarkup(True)
adcSystemInitFile = adcComponent.createFileSymbol("ADC_INIT", None)
adcSystemInitFile.setType("STRING")
adcSystemInitFile.setOutputName("core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS")
adcSystemInitFile.setSourcePath("../peripheral/adc_"+str(adcID)+"/templates/system/initialization.c.ftl")
adcSystemInitFile.setMarkup(True)
adcSystemDefFile = adcComponent.createFileSymbol("ADC_DEF", None)
adcSystemDefFile.setType("STRING")
adcSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES")
adcSystemDefFile.setSourcePath("../peripheral/adc_"+str(adcID)+"/templates/system/definitions.h.ftl")
adcSystemDefFile.setMarkup(True)
| """*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
adc_sym_seqr1_usch = []
adc_ch_menu = []
adc_sym_ch_cher = []
adc_sym_ch_name = []
adc_sym_ch__positive_input = []
adc_sym_ch__negative_input = []
adc_sym_ch_ier_eoc = []
def adc_clock_control(symbol, event):
clock_set = False
Database.clearSymbolValue('core', adcInstanceName.getValue() + '_CLOCK_ENABLE')
for channel_id in range(0, 12):
if adcSym_CH_CHER[channelID].getValue() == True:
clock_set = True
if clockSet == True:
Database.setSymbolValue('core', adcInstanceName.getValue() + '_CLOCK_ENABLE', True, 2)
else:
Database.setSymbolValue('core', adcInstanceName.getValue() + '_CLOCK_ENABLE', False, 2)
def adc_interrupt_enable_disable_callback(symbol, event):
global interruptSymbolEnable
device_handler_last_name = '_InterruptHandler'
interrupt_last_name_handler = '_INTERRUPT_HANDLER'
interrupt_last_name_handler_lock = '_INTERRUPT_HANDLER_LOCK'
interrupt_namespace = 'core'
interrupt_symbol_handler = adcInstanceName.getValue() + interruptLastNameHandler
interrupt_symbol_handler_lock = adcInstanceName.getValue() + interruptLastNameHandlerLock
interrupt_set = False
Database.clearSymbolValue('core', interruptSymbolHandlerLock)
Database.clearSymbolValue('core', interruptSymbolEnable)
Database.clearSymbolValue('core', interruptSymbolHandler)
for channel_id in range(0, 12):
if adcSym_CH_IER_EOC[channelID].getValue() == True:
interrupt_set = True
if adcSym_IER_COMPE.getValue() == True:
interrupt_set = True
if interruptSet == True:
Database.setSymbolValue(interruptNamespace, interruptSymbolEnable, True, 2)
Database.setSymbolValue(interruptNamespace, interruptSymbolHandler, adcInstanceName.getValue() + deviceHandlerLastName, 2)
Database.setSymbolValue(interruptNamespace, interruptSymbolHandlerLock, True, 2)
else:
Database.setSymbolValue(interruptNamespace, interruptSymbolHandlerLock, False, 2)
Database.setSymbolValue(interruptNamespace, interruptSymbolEnable, False, 2)
def dependency_clock_status(symbol, event):
clock_set = False
clock = bool(Database.getSymbolValue('core', adcInstanceName.getValue() + '_CLOCK_ENABLE'))
for channel_id in range(0, 12):
if adcSym_CH_CHER[channelID].getValue() == True:
clock_set = True
if clockSet == True and clock == False:
symbol.setVisible(True)
else:
symbol.setVisible(False)
def dependency_int_status(symbol, event):
global interruptSymbolEnable
interrupt_set = False
interrupt = bool(Database.getSymbolValue('core', interruptSymbolEnable))
for channel_id in range(0, 12):
if adcSym_CH_IER_EOC[channelID].getValue() == True:
interrupt_set = True
if adcSym_IER_COMPE.getValue() == True:
interrupt_set = True
if interruptSet == True and interrupt == False:
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adc_get_peripheral_clock():
peripheral_clk_freq = int(Database.getSymbolValue('core', adcInstanceName.getValue() + '_CLOCK_FREQUENCY'))
return peripheral_clk_freq
def adc_prescal_warning(symbol, event):
clock = adc_get_peripheral_clock()
prescaler = adcSym_MR_PRESCAL.getValue() + 1
adc_freq = clock / (2 * prescaler)
if adcFreq < 200000:
symbol.setLabel('ADC Frequency < 200,000 Hz. Decrease prescaler value. ')
symbol.setVisible(True)
elif adcFreq > 20000000:
symbol.setLabel('ADC Frequency > 20,000,000 Hz. Increase prescaler value. ')
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adc_freq_calc(symbol, event):
clock = adc_get_peripheral_clock()
prescaler = adcSym_MR_PRESCAL.getValue() + 1
adc_freq = clock / (2 * prescaler)
symbol.clearValue()
symbol.setValue(adcFreq, 2)
def adc_calc_conversion_time(adcSym_CONV_TIME, event):
clock = adc_get_peripheral_clock()
adcClockSourceInvalidSym.setVisible(clock == 0)
if clock == 0:
clock = 1
prescaler = adcSym_MR_PRESCAL.getValue() + 1
over_sampling_rate = adcSym_EMR_OSR_VALUE.getSelectedKey()
multiplier = 1
if over_sampling_rate == 'NO_AVERAGE':
multiplier = 1
elif over_sampling_rate == 'OSR4_SIN' or over_sampling_rate == 'OSR4_MUL':
multiplier = 4
elif over_sampling_rate == 'OSR16_SIN' or over_sampling_rate == 'OSR16_MUL':
multiplier = 16
elif over_sampling_rate == 'OSR64_SIN' or over_sampling_rate == 'OSR64_MUL':
multiplier = 64
elif over_sampling_rate == 'OSR256_SIN' or over_sampling_rate == 'OSR256_MUL':
multiplier = 256
conv_time = 2 * prescaler * 21.0 * 1000000.0 * multiplier / clock
adcSym_CONV_TIME.setLabel('**** Conversion Time is ' + str(conv_time) + ' us ****')
def adc_user_seq_visible(adcSym_SEQR1_USCHLocal, event):
for channel_id in range(0, 11):
adcSym_SEQR1_USCH[channelID].setVisible(event['value'])
def adc_ch_name_visible(symbol, event):
id = []
id = symbol.getID().split('_')
channel_id = int(id[1])
adcSym_CH_NAME[channelID].setVisible(event['value'])
def adc_ch_pos_inp_visible(symbol, event):
id = []
id = symbol.getID().split('_')
channel_id = int(id[1])
adcSym_CH_PositiveInput[channelID].setVisible(event['value'])
def adc_ch_neg_inp_visible(symbol, event):
id = []
id = symbol.getID().split('_')
channel_id = int(id[1])
adcSym_CH_NegativeInput[channelID].setVisible(event['value'])
def adc_ch_interrupt_visible(symbol, event):
id = []
id = symbol.getID().split('_')
channel_id = int(id[1])
adcSym_CH_IER_EOC[channelID].setVisible(event['value'])
def adc_ch_enable(symbol, event):
id = []
id = symbol.getID().split('_')
channel_id = int(id[1])
if event['id'].find('_NEG_INP') > 0:
if event['value'] == 'AN' + str(channelID):
adcCHMenu[channelID].setVisible(False)
else:
adcCHMenu[channelID].setVisible(True)
def adc_trigger_visible(symbol, event):
sym_obj = event['symbol']
trigger_val = int(symObj.getSelectedValue())
if triggerVal >= 1 and triggerVal <= 3:
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adc_trigger_time_visible(symbol, event):
if event['id'] == 'ADC_TRGR_MODE' and event['value'] == 4:
symbol.setVisible(True)
else:
symbol.setVisible(False)
def adc_calc_trigger_period(symbol, event):
trgper = int(adcSym_TRIGGER_TIME.getValue() * adcSym_Clock.getValue() / 1000.0 - 1)
if event['id'] == 'ADC_TRIGGER_TIME' or (event['id'] == 'ADC_TRGR_MODE' and event['value'] == 4):
symbol.setValue(trgper, 2)
else:
symbol.clearValue()
def adc_symbol_visible(symbol, event):
symbol.setVisible(event['value'])
def instantiate_component(adcComponent):
global adcInstanceName
global interruptSymbolEnable
global adcClockSourceInvalidSym
adc_instance_name = adcComponent.createStringSymbol('ADC_INSTANCE_NAME', None)
adcInstanceName.setVisible(False)
adcInstanceName.setDefaultValue(adcComponent.getID().upper())
Log.writeInfoMessage('Running ' + adcInstanceName.getValue())
interrupt_last_name_enable = '_INTERRUPT_ENABLE'
interrupt_symbol_enable = adcInstanceName.getValue() + interruptLastNameEnable
available_pins = []
channel = ['False', 'False', 'False', 'False', 'False', 'False', 'False', 'False', 'False', 'False', 'False', 'False']
adc_channels_values = []
adcChannelsValues.append('NONE')
children = []
val = ATDF.getNode('/avr-tools-device-file/pinouts/pinout@[name="' + Database.getSymbolValue('core', 'COMPONENT_PACKAGE') + '"]')
children = val.getChildren()
for pad in range(0, len(children)):
availablePins.append(children[pad].getAttribute('pad'))
adc_signals = []
adc = ATDF.getNode('/avr-tools-device-file/devices/device/peripherals/module@[name="ADC"]/instance@[name="' + adcInstanceName.getValue() + '"]/signals')
adc_signals = adc.getChildren()
for pad in range(0, len(adc_signals)):
group = adc_signals[pad].getAttribute('group')
if 'AD' in group and 'index' in adc_signals[pad].getAttributeList():
pad_signal = adc_signals[pad].getAttribute('pad')
if padSignal in availablePins:
channel[int(adc_signals[pad].getAttribute('index'))] = 'True'
adcChannelsValues.append('CH' + adc_signals[pad].getAttribute('index'))
adc_sym__available_channels = adcComponent.createComboSymbol('ADC_AVAILABLE_CHANNELS', None, channel)
adcSym_AvailableChannels.setVisible(False)
adc_menu = adcComponent.createMenuSymbol('ADC_MENU', None)
adcMenu.setLabel('ADC Configuration')
adc_sym_num_channels = adcComponent.createIntegerSymbol('ADC_NUM_CHANNELS', adcMenu)
adcSym_NUM_CHANNELS.setDefaultValue(12)
adcSym_NUM_CHANNELS.setVisible(False)
value_group_path = '/avr-tools-device-file/modules/module@[name="ADC"]/value-group@[name="ADC_EMR__SRCCLK"]'
value_group = ATDF.getNode(valueGroupPath)
if valueGroup is not None:
adc_sym_emr_srcclk = adcComponent.createKeyValueSetSymbol('ADC_CLK_SRC', adcMenu)
adcSym_EMR_SRCCLK.setLabel(valueGroup.getAttribute('caption'))
values = valueGroup.getChildren()
for index in range(len(values)):
adcSym_EMR_SRCCLK.addKey(values[index].getAttribute('name'), values[index].getAttribute('value'), values[index].getAttribute('caption'))
adcSym_EMR_SRCCLK.setOutputMode('Key')
adcSym_EMR_SRCCLK.setDisplayMode('Key')
adc_clock_source_invalid_sym = adcComponent.createCommentSymbol('ADC_CLK_SRC_INVALID_COMMENT', adcMenu)
adcClockSourceInvalidSym.setLabel('Warning!!! ' + adcInstanceName.getValue() + ' clock frequency is zero')
adcClockSourceInvalidSym.setVisible(False)
global adcSym_MR_PRESCAL
adc_sym_mr_prescal = adcComponent.createIntegerSymbol('ADC_MR_PRESCAL', adcMenu)
adcSym_MR_PRESCAL.setLabel('Select Prescaler')
adcSym_MR_PRESCAL.setDefaultValue(9)
adcSym_MR_PRESCAL.setMin(0)
adcSym_MR_PRESCAL.setMax(255)
global adcSym_Clock
adc_sym__clock = adcComponent.createIntegerSymbol('ADC_CLK', adcMenu)
adcSym_Clock.setLabel('Clock Frequency (Hz)')
default_adc_freq = int(adc_get_peripheral_clock() / (2 * (adcSym_MR_PRESCAL.getValue() + 1)))
adcSym_Clock.setDefaultValue(defaultAdcFreq)
adcSym_Clock.setVisible(True)
adcSym_Clock.setReadOnly(True)
adcSym_Clock.setDependencies(adcFreqCalc, ['ADC_MR_PRESCAL', 'core.' + adcInstanceName.getValue() + '_CLOCK_FREQUENCY'])
adc_sym_prescal_warning = adcComponent.createCommentSymbol('ADC_PRESCAL_WARNING', adcMenu)
adcSym_PRESCAL_WARNING.setLabel('**** ADC Frequency = ' + str(defaultAdcFreq) + ' Hz. ****')
adcSym_PRESCAL_WARNING.setVisible(False)
adcSym_PRESCAL_WARNING.setDependencies(adcPrescalWarning, ['ADC_MR_PRESCAL', 'core.' + adcInstanceName.getValue() + '_CLOCK_FREQUENCY'])
global adcSym_EMR_OSR_VALUE
adc_sym_emr_osr_value = adcComponent.createKeyValueSetSymbol('ADC_EMR_OSR_VALUE', adcMenu)
adcSym_EMR_OSR_VALUE.setLabel('Result Resolution')
adcSym_EMR_OSR_VALUE.setDefaultValue(0)
adcSym_EMR_OSR_VALUE.setOutputMode('Value')
adcSym_EMR_OSR_VALUE.setDisplayMode('Description')
value_group = ATDF.getNode('/avr-tools-device-file/modules/module@[name="ADC"]/value-group@[name="ADC_EMR__OSR"]')
if valueGroup is not None:
osr_values = valueGroup.getChildren()
for index in range(len(osrValues)):
if osrValues[index].getAttribute('name') == 'NO_AVERAGE':
adcSym_EMR_OSR_VALUE.addKey('NO_AVERAGE', '0', '12-bit')
elif osrValues[index].getAttribute('name') == 'OSR4':
adcSym_EMR_OSR_VALUE.addKey('OSR4_SIN', '1', '13-bit - single trigger averaging')
adcSym_EMR_OSR_VALUE.addKey('OSR4_MUL', '2', '13-bit - multi trigger averaging')
elif osrValues[index].getAttribute('name') == 'OSR16':
adcSym_EMR_OSR_VALUE.addKey('OSR16_SIN', '3', '14-bit - single trigger averaging')
adcSym_EMR_OSR_VALUE.addKey('OSR16_MUL', '4', '14-bit - multi trigger averaging')
elif osrValues[index].getAttribute('name') == 'OSR64':
adcSym_EMR_OSR_VALUE.addKey('OSR64_SIN', '5', '15-bit - single trigger averaging')
adcSym_EMR_OSR_VALUE.addKey('OSR64_MUL', '6', '15-bit - multi trigger averaging')
elif osrValues[index].getAttribute('name') == 'OSR256':
adcSym_EMR_OSR_VALUE.addKey('OSR256_SIN', '7', '16-bit - single trigger averaging')
adcSym_EMR_OSR_VALUE.addKey('OSR256_MUL', '8', '16-bit - multi trigger averaging')
adc_sym_conv_time = adcComponent.createCommentSymbol('ADC_CONV_TIME', adcMenu)
default_conv_time = 2 * (adcSym_MR_PRESCAL.getValue() + 1) * 21.0 * 1000000.0 * 1 / adc_get_peripheral_clock()
adcSym_CONV_TIME.setLabel('**** Conversion Time is ' + str(defaultConvTime) + ' us ****')
adcSym_CONV_TIME.setDependencies(adcCalcConversionTime, ['ADC_MR_PRESCAL', 'ADC_EMR_OSR_VALUE', 'core.' + adcInstanceName.getValue() + '_CLOCK_FREQUENCY'])
adc_sym_emr_signmode_value = adcComponent.createKeyValueSetSymbol('ADC_EMR_SIGNMODE_VALUE', adcMenu)
adcSym_EMR_SIGNMODE_VALUE.setLabel('Result Sign')
adcSym_EMR_SIGNMODE_VALUE.setDefaultValue(0)
adcSym_EMR_SIGNMODE_VALUE.setOutputMode('Key')
adcSym_EMR_SIGNMODE_VALUE.setDisplayMode('Description')
adcSym_EMR_SIGNMODE_VALUE.addKey('SE_UNSG_DF_SIGN', '0', 'Single Ended: Unsigned, Differential: Signed')
adcSym_EMR_SIGNMODE_VALUE.addKey('SE_SIGN_DF_UNSG', '1', 'Single Ended: Signed, Differential: Unsigned')
adcSym_EMR_SIGNMODE_VALUE.addKey('ALL_UNSIGNED', '2', 'All Unsigned')
adcSym_EMR_SIGNMODE_VALUE.addKey('ALL_SIGNED', '3', 'All Signed')
adc_sym_trgr_mode = adcComponent.createKeyValueSetSymbol('ADC_TRGR_MODE', adcMenu)
adcSym_TRGR_MODE.setLabel('Trigger Mode')
adcSym_TRGR_MODE.setDefaultValue(5)
adcSym_TRGR_MODE.setOutputMode('Key')
adcSym_TRGR_MODE.setDisplayMode('Description')
adcSym_TRGR_MODE.addKey('TRGMOD_NO_TRIGGER', '0', 'Software Trigger')
adcSym_TRGR_MODE.addKey('TRGMOD_EXT_TRIG_RISE', '1', 'External Trigger Rising Edge')
adcSym_TRGR_MODE.addKey('TRGMOD_EXT_TRIG_FALL', '2', 'External Trigger Falling Edge')
adcSym_TRGR_MODE.addKey('TRGMOD_EXT_TRIG_ANY', '3', 'External Trigger Any Edge')
adcSym_TRGR_MODE.addKey('TRGMOD_PERIOD_TRIG', '4', 'ADC Internal Periodic Trigger')
adcSym_TRGR_MODE.addKey('TRGMOD_CONTINUOUS', '5', 'Continuous')
adc_sym_mr_trgsel_value = adcComponent.createKeyValueSetSymbol('ADC_MR_TRGSEL_VALUE', adcSym_TRGR_MODE)
adcSym_MR_TRGSEL_VALUE.setLabel('Select External Trigger Input')
adcSym_MR_TRGSEL_VALUE.setVisible(False)
adcSym_MR_TRGSEL_VALUE.setDefaultValue(1)
adcSym_MR_TRGSEL_VALUE.setOutputMode('Key')
adcSym_MR_TRGSEL_VALUE.setDisplayMode('Description')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG0', '0', 'ADTRG')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG1', '1', 'TIOA0')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG2', '2', 'TIOA1')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG3', '3', 'TIOA2')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG4', '4', 'PWM event line 0')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG5', '5', 'PWM event line 1')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG6', '6', 'TIOA3')
adcSym_MR_TRGSEL_VALUE.addKey('TRGSEL_ADC_TRIG7', '7', 'RTCOUT0')
adcSym_MR_TRGSEL_VALUE.setDependencies(adcTriggerVisible, ['ADC_TRGR_MODE'])
global adcSym_TRIGGER_TIME
adc_sym_trigger_time = adcComponent.createIntegerSymbol('ADC_TRIGGER_TIME', adcSym_TRGR_MODE)
adcSym_TRIGGER_TIME.setLabel('Trigger Period (ms)')
adcSym_TRIGGER_TIME.setDefaultValue(2)
adcSym_TRIGGER_TIME.setMin(1)
adcSym_TRIGGER_TIME.setMax(int(65536 * 1000.0 / adcSym_Clock.getValue()))
adcSym_TRIGGER_TIME.setVisible(False)
adcSym_TRIGGER_TIME.setDependencies(adcTriggerTimeVisible, ['ADC_TRGR_MODE'])
adc_sym_trgr_trgper = adcComponent.createIntegerSymbol('ADC_TRGR_TRIGGER_PERIOD', adcSym_TRIGGER_TIME)
adcSym_TRGR_TRGPER.setVisible(False)
adcSym_TRGR_TRGPER.setDependencies(adcCalcTriggerPeriod, ['ADC_TRIGGER_TIME', 'ADC_TRGR_MODE'])
adc_sym_mr_sleep = adcComponent.createBooleanSymbol('ADC_MR_SLEEP', adcMenu)
adcSym_MR_SLEEP.setLabel('Sleep Mode')
adcSym_MR_SLEEP.setDefaultValue(False)
adc_fast_wakeup_values = ['OFF', 'ON']
adc_sym_mr_fwup = adcComponent.createComboSymbol('ADC_MR_FWUP', adcSym_MR_SLEEP, adcFastWakeupValues)
adcSym_MR_FWUP.setLabel('Fast Wakeup')
adcSym_MR_FWUP.setDefaultValue(adcFastWakeupValues[0])
adcSym_MR_FWUP.setVisible(False)
adcSym_MR_FWUP.setDependencies(adcSymbolVisible, ['ADC_MR_SLEEP'])
adc_sym_comp_window = adcComponent.createBooleanSymbol('ADC_COMP_WINDOW', adcMenu)
adcSym_COMP_WINDOW.setLabel('Automatic Window Comparison')
adcSym_COMP_WINDOW.setDefaultValue(False)
adc_sym_emr_cmpmode = adcComponent.createKeyValueSetSymbol('ADC_EMR_CMPMODE', adcSym_COMP_WINDOW)
adcSym_EMR_CMPMODE.setLabel('Comparison Mode')
adcSym_EMR_CMPMODE.setDefaultValue(0)
adcSym_EMR_CMPMODE.setOutputMode('Key')
adcSym_EMR_CMPMODE.setDisplayMode('Description')
adcSym_EMR_CMPMODE.addKey('CMPMODE_LOW', '0', 'Vin < VLo')
adcSym_EMR_CMPMODE.addKey('CMPMODE_HIGH', '1', 'Vin < VHi')
adcSym_EMR_CMPMODE.addKey('CMPMODE_IN', '2', 'VLo < Vin < VHi')
adcSym_EMR_CMPMODE.addKey('CMPMODE_OUT', '3', 'VHi < Vin < VLo')
adcSym_EMR_CMPMODE.setVisible(False)
adcSym_EMR_CMPMODE.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
adc_sym_emr_cmptype = adcComponent.createKeyValueSetSymbol('ADC_EMR_CMPTYPE', adcSym_COMP_WINDOW)
adcSym_EMR_CMPTYPE.setLabel('Comparison Type')
adcSym_EMR_CMPTYPE.setDefaultValue(0)
adcSym_EMR_CMPTYPE.setOutputMode('Key')
adcSym_EMR_CMPTYPE.setDisplayMode('Description')
adcSym_EMR_CMPTYPE.addKey('CMPTYPE_FLAG_ONLY', '0', '0-No Comparison')
adcSym_EMR_CMPTYPE.addKey('CMPTYPE_START_CONDITION', '1', '1-Comparison match')
adcSym_EMR_CMPTYPE.setVisible(False)
adcSym_EMR_CMPTYPE.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
adc_comp_selected_channel_values = adcChannelsValues[1:]
adcCompSelectedChannelValues.append('All')
adc_sym_emr_cmpsel = adcComponent.createComboSymbol('ADC_EMR_CMPSEL', adcSym_COMP_WINDOW, adcCompSelectedChannelValues)
adcSym_EMR_CMPSEL.setLabel('Comparison Selected Channel')
adcSym_EMR_CMPSEL.setDefaultValue(adcCompSelectedChannelValues[0])
adcSym_EMR_CMPSEL.setVisible(False)
adcSym_EMR_CMPSEL.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
adc_sym_cwr_lowthres = adcComponent.createIntegerSymbol('ADC_CWR_LOWTHRES_VALUE', adcSym_COMP_WINDOW)
adcSym_CWR_LOWTHRES.setLabel('Low Threshold')
adcSym_CWR_LOWTHRES.setDefaultValue(0)
adcSym_CWR_LOWTHRES.setVisible(False)
adcSym_CWR_LOWTHRES.setMin(0)
adcSym_CWR_LOWTHRES.setMax(16383)
adcSym_CWR_LOWTHRES.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
adc_sym_cwr_highthres = adcComponent.createIntegerSymbol('ADC_CWR_HIGHTHRES_VALUE', adcSym_COMP_WINDOW)
adcSym_CWR_HIGHTHRES.setLabel('High Threshold')
adcSym_CWR_HIGHTHRES.setDefaultValue(0)
adcSym_CWR_HIGHTHRES.setVisible(False)
adcSym_CWR_HIGHTHRES.setMin(0)
adcSym_CWR_HIGHTHRES.setMax(16383)
adcSym_CWR_HIGHTHRES.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
global adcSym_IER_COMPE
adc_sym_ier_compe = adcComponent.createBooleanSymbol('ADC_IER_COMPE', adcSym_COMP_WINDOW)
adcSym_IER_COMPE.setLabel('Comparison Event Interrupt')
adcSym_IER_COMPE.setDefaultValue(False)
adcSym_IER_COMPE.setVisible(False)
adcSym_IER_COMPE.setDependencies(adcSymbolVisible, ['ADC_COMP_WINDOW'])
adc_user_seq = adcComponent.createMenuSymbol('ADC_USER_SEQ', None)
adcUserSeq.setLabel('User Channel Sequence Configuration')
adc_sym_useq_comment = adcComponent.createCommentSymbol('ADC_USEQ_COMMENT', adcUserSeq)
adcSym_USEQ_COMMENT.setLabel('**** Configure selected channels in the Channel Configuration Menu ****')
adc_sym_mr_useq = adcComponent.createBooleanSymbol('ADC_MR_USEQ', adcUserSeq)
adcSym_MR_USEQ.setLabel('Enable User Sequence Mode')
adcSym_MR_USEQ.setDefaultValue(False)
for channel_id in range(0, len(channel) - 1):
adcSym_SEQR1_USCH.append(channelID)
adcSym_SEQR1_USCH[channelID] = adcComponent.createComboSymbol('ADC_SEQR1_USCH' + str(channelID + 1), adcSym_MR_USEQ, adcChannelsValues)
adcSym_SEQR1_USCH[channelID].setLabel('Select Channel for Sequence Number ' + str(channelID + 1))
adcSym_SEQR1_USCH[channelID].setDefaultValue(adcChannelsValues[0])
adcSym_SEQR1_USCH[channelID].setVisible(False)
adcSym_SEQR1_USCH[channelID].setDependencies(adcUserSeqVisible, ['ADC_MR_USEQ'])
adc_ch_conf_menu = adcComponent.createMenuSymbol('ADC_CH_CONF', None)
adcCHConfMenu.setLabel('Channel Configuration')
for channel_id in range(0, len(channel)):
global adcCHMenu
adcCHMenu.append(channelID)
adcCHMenu[channelID] = adcComponent.createMenuSymbol('CH' + str(channelID), adcCHConfMenu)
adcCHMenu[channelID].setLabel('Channel ' + str(channelID))
if channel[channelID] == 'False':
adcCHMenu[channelID].setVisible(False)
adcSym_CH_CHER.append(channelID)
adcSym_CH_CHER[channelID] = adcComponent.createBooleanSymbol('ADC_' + str(channelID) + '_CHER', adcCHMenu[channelID])
adcSym_CH_CHER[channelID].setLabel('Enable Channel ' + str(channelID))
adcSym_CH_CHER[channelID].setDefaultValue(False)
if channelID % 2 == 1:
adcSym_CH_CHER[channelID].setDependencies(adcCHEnable, ['ADC_' + str(channelID - 1) + '_NEG_INP'])
adcSym_CH_NAME.append(channelID)
adcSym_CH_NAME[channelID] = adcComponent.createStringSymbol('ADC_' + str(channelID) + '_NAME', adcSym_CH_CHER[channelID])
adcSym_CH_NAME[channelID].setLabel('Name')
adcSym_CH_NAME[channelID].setDefaultValue('CHANNEL_' + str(channelID))
adcSym_CH_NAME[channelID].setVisible(False)
adcSym_CH_NAME[channelID].setDependencies(adcCHNameVisible, ['ADC_' + str(channelID) + '_CHER'])
adcSym_CH_PositiveInput.append(channelID)
adcSym_CH_PositiveInput[channelID] = adcComponent.createStringSymbol('ADC_' + str(channelID) + '_POS_INP', adcSym_CH_CHER[channelID])
adcSym_CH_PositiveInput[channelID].setLabel('Positive Input')
adcSym_CH_PositiveInput[channelID].setDefaultValue('AN' + str(channelID))
adcSym_CH_PositiveInput[channelID].setReadOnly(True)
adcSym_CH_PositiveInput[channelID].setVisible(False)
adcSym_CH_PositiveInput[channelID].setDependencies(adcCHPosInpVisible, ['ADC_' + str(channelID) + '_CHER'])
adcSym_CH_NegativeInput.append(channelID)
adc__even_ch_neg_input = ['GND', 'AN' + str(channelID + 1)]
adc__odd_ch_neg_input = ['GND']
if channelID % 2 == 1:
adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol('ADC_' + str(channelID) + '_NEG_INP', adcSym_CH_CHER[channelID], adc_OddChNegInput)
adcSym_CH_NegativeInput[channelID].setReadOnly(True)
else:
adcSym_CH_NegativeInput[channelID] = adcComponent.createComboSymbol('ADC_' + str(channelID) + '_NEG_INP', adcSym_CH_CHER[channelID], adc_EvenChNegInput)
if channel[channelID + 1] == 'False':
adcSym_CH_NegativeInput[channelID].setReadOnly(True)
adcSym_CH_NegativeInput[channelID].setLabel('Negative Input')
adcSym_CH_NegativeInput[channelID].setDefaultValue('GND')
adcSym_CH_NegativeInput[channelID].setVisible(False)
adcSym_CH_NegativeInput[channelID].setDependencies(adcCHNegInpVisible, ['ADC_' + str(channelID) + '_CHER'])
adcSym_CH_IER_EOC.append(channelID)
adcSym_CH_IER_EOC[channelID] = adcComponent.createBooleanSymbol('ADC_' + str(channelID) + '_IER_EOC', adcSym_CH_CHER[channelID])
adcSym_CH_IER_EOC[channelID].setLabel('End of conversion interrupt')
adcSym_CH_IER_EOC[channelID].setDefaultValue(False)
adcSym_CH_IER_EOC[channelID].setVisible(False)
adcSym_CH_IER_EOC[channelID].setDependencies(adcCHInterruptVisible, ['ADC_' + str(channelID) + '_CHER'])
adc_sym__clock_control = adcComponent.createBooleanSymbol('ADC_CLOCK_ENABLE', None)
adcSym_ClockControl.setDependencies(adcClockControl, ['ADC_0_CHER', 'ADC_1_CHER', 'ADC_2_CHER', 'ADC_3_CHER', 'ADC_4_CHER', 'ADC_5_CHER', 'ADC_6_CHER', 'ADC_7_CHER', 'ADC_8_CHER', 'ADC_9_CHER', 'ADC_10_CHER', 'ADC_11_CHER'])
adcSym_ClockControl.setVisible(False)
adc_sym__interrupt_control = adcComponent.createBooleanSymbol('ADC_INTERRUPT_ENABLE', None)
adcSym_InterruptControl.setDependencies(adcInterruptEnableDisableCallback, ['ADC_0_IER_EOC', 'ADC_1_IER_EOC', 'ADC_2_IER_EOC', 'ADC_3_IER_EOC', 'ADC_4_IER_EOC', 'ADC_5_IER_EOC', 'ADC_6_IER_EOC', 'ADC_7_IER_EOC', 'ADC_8_IER_EOC', 'ADC_9_IER_EOC', 'ADC_10_IER_EOC', 'ADC_11_IER_EOC', 'ADC_IER_COMPE'])
adcSym_InterruptControl.setVisible(False)
adc_sym__clk_en_comment = adcComponent.createCommentSymbol('ADC_CLK_ENABLE_COMMENT', None)
adcSym_ClkEnComment.setVisible(False)
adcSym_ClkEnComment.setLabel('Warning!!! ' + adcInstanceName.getValue() + ' Peripheral Clock is Disabled in Clock Manager')
adcSym_ClkEnComment.setDependencies(dependencyClockStatus, ['core.' + adcInstanceName.getValue() + '_CLOCK_ENABLE', 'ADC_0_CHER', 'ADC_1_CHER', 'ADC_2_CHER', 'ADC_3_CHER', 'ADC_4_CHER', 'ADC_5_CHER', 'ADC_6_CHER', 'ADC_7_CHER', 'ADC_8_CHER', 'ADC_9_CHER', 'ADC_10_CHER', 'ADC_11_CHER'])
adc_sym__int_en_comment = adcComponent.createCommentSymbol('ADC_INTERRUPT_ENABLE_COMMENT', None)
adcSym_IntEnComment.setVisible(False)
adcSym_IntEnComment.setLabel('Warning!!! ' + adcInstanceName.getValue() + ' Interrupt is Disabled in Interrupt Manager')
adcSym_IntEnComment.setDependencies(dependencyIntStatus, ['core.' + interruptSymbolEnable, 'ADC_0_IER_EOC', 'ADC_1_IER_EOC', 'ADC_2_IER_EOC', 'ADC_3_IER_EOC', 'ADC_4_IER_EOC', 'ADC_5_IER_EOC', 'ADC_6_IER_EOC', 'ADC_7_IER_EOC', 'ADC_8_IER_EOC', 'ADC_9_IER_EOC', 'ADC_10_IER_EOC', 'ADC_11_IER_EOC', 'ADC_IER_COMPE'])
config_name = Variables.get('__CONFIGURATION_NAME')
adc = ATDF.getNode('/avr-tools-device-file/modules/module@[name="ADC"]')
adc_id = adc.getAttribute('id')
adc_header_file = adcComponent.createFileSymbol('ADC_HEADER', None)
adcHeaderFile.setSourcePath('../peripheral/adc_' + str(adcID) + '/templates/plib_adc.h.ftl')
adcHeaderFile.setOutputName('plib_' + adcInstanceName.getValue().lower() + '.h')
adcHeaderFile.setDestPath('peripheral/adc/')
adcHeaderFile.setProjectPath('config/' + configName + '/peripheral/adc/')
adcHeaderFile.setType('HEADER')
adcHeaderFile.setMarkup(True)
adc_common_header_file = adcComponent.createFileSymbol('ADC_COMMON_HEADER', None)
adcCommonHeaderFile.setSourcePath('../peripheral/adc_' + str(adcID) + '/templates/plib_adc_common.h')
adcCommonHeaderFile.setOutputName('plib_adc_common.h')
adcCommonHeaderFile.setDestPath('peripheral/adc/')
adcCommonHeaderFile.setProjectPath('config/' + configName + '/peripheral/adc/')
adcCommonHeaderFile.setType('HEADER')
adc_source1_file = adcComponent.createFileSymbol('ADC_SOURCE', None)
adcSource1File.setSourcePath('../peripheral/adc_' + str(adcID) + '/templates/plib_adc.c.ftl')
adcSource1File.setOutputName('plib_' + adcInstanceName.getValue().lower() + '.c')
adcSource1File.setDestPath('peripheral/adc/')
adcSource1File.setProjectPath('config/' + configName + '/peripheral/adc/')
adcSource1File.setType('SOURCE')
adcSource1File.setMarkup(True)
adc_system_init_file = adcComponent.createFileSymbol('ADC_INIT', None)
adcSystemInitFile.setType('STRING')
adcSystemInitFile.setOutputName('core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS')
adcSystemInitFile.setSourcePath('../peripheral/adc_' + str(adcID) + '/templates/system/initialization.c.ftl')
adcSystemInitFile.setMarkup(True)
adc_system_def_file = adcComponent.createFileSymbol('ADC_DEF', None)
adcSystemDefFile.setType('STRING')
adcSystemDefFile.setOutputName('core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES')
adcSystemDefFile.setSourcePath('../peripheral/adc_' + str(adcID) + '/templates/system/definitions.h.ftl')
adcSystemDefFile.setMarkup(True) |
def intdiv(a, b):
return a // b
if __name__ == "__main__":
print("Hi, I can calculate the integer division of two numers")
a = int(input("a = "))
b = int(input("b = "))
print(f"a // b = {intdiv(a, b)}")
print("Bye!")
| def intdiv(a, b):
return a // b
if __name__ == '__main__':
print('Hi, I can calculate the integer division of two numers')
a = int(input('a = '))
b = int(input('b = '))
print(f'a // b = {intdiv(a, b)}')
print('Bye!') |
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
q = [(target, [])]
candidates = sorted(candidates)
result = []
while q:
num, history = q.pop(0)
if num == 0:
result.append(history)
else:
if not history:
if num < candidates[0]:
continue
idx = 0
else:
idx = history[-1][0] + 1
if idx >= len(candidates):
continue
if candidates[idx] > num:
continue
while True:
cnt = 1
while num >= cnt * candidates[idx]:
newnum = num - cnt * candidates[idx]
newhistory = history[:]
newhistory.append((idx, cnt))
q.append((newnum, newhistory))
cnt += 1
idx += 1
if idx >= len(candidates) or candidates[idx] > num:
break
ret = []
for r in result:
l = []
for idx, cnt in r:
l.extend([candidates[idx]] * cnt)
ret.append(l)
return ret
| class Solution(object):
def combination_sum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
q = [(target, [])]
candidates = sorted(candidates)
result = []
while q:
(num, history) = q.pop(0)
if num == 0:
result.append(history)
else:
if not history:
if num < candidates[0]:
continue
idx = 0
else:
idx = history[-1][0] + 1
if idx >= len(candidates):
continue
if candidates[idx] > num:
continue
while True:
cnt = 1
while num >= cnt * candidates[idx]:
newnum = num - cnt * candidates[idx]
newhistory = history[:]
newhistory.append((idx, cnt))
q.append((newnum, newhistory))
cnt += 1
idx += 1
if idx >= len(candidates) or candidates[idx] > num:
break
ret = []
for r in result:
l = []
for (idx, cnt) in r:
l.extend([candidates[idx]] * cnt)
ret.append(l)
return ret |
def power_consumption():
pass
def deadlines():
pass
def idle_cranes():
pass
def idle_machines():
pass
def buffer_usage():
pass
def material_pickup():
pass
| def power_consumption():
pass
def deadlines():
pass
def idle_cranes():
pass
def idle_machines():
pass
def buffer_usage():
pass
def material_pickup():
pass |
def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_
+ ".tests": [
"coveragerc",
"data/*.h5",
"data/*.dat",
"data/*.npy",
"integration_tests/*/*.yml",
"integration_tests/*/*.dat",
]
}
| def get_package_data():
return {_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*.h5', 'data/*.dat', 'data/*.npy', 'integration_tests/*/*.yml', 'integration_tests/*/*.dat']} |
#
# Exercism.io
# Python track
# Problem #1 - Hello World
# github.com/marnovo/Exercism
#
name = input("Tell your name: ")
def hello(name=''):
if name == '':
message = "Hello, World!"
else:
message = "Hello, " + name + "!"
return message
print(hello(name))
| name = input('Tell your name: ')
def hello(name=''):
if name == '':
message = 'Hello, World!'
else:
message = 'Hello, ' + name + '!'
return message
print(hello(name)) |
#Challenge042
v1 = float(input(' medida 1: '))
v2 = float(input(' medida 2: '))
v3 = float(input(' medida 3: '))
#if v1+v2+v3 == 180:
if v1 == v2 == v3:
print('Triangulo equilatero: com todos os lados iguais')
elif (v1 == v2 or v3) and (v2 == v1 or v3 ):
print('tringulo isoceles dois lados iguais')
elif (v1 != v2 or v3) and (v2 != v1 or v3) and (v3 != v1 or v2):
print('escaleno')
else:
print('nao e um triangulo') | v1 = float(input(' medida 1: '))
v2 = float(input(' medida 2: '))
v3 = float(input(' medida 3: '))
if v1 == v2 == v3:
print('Triangulo equilatero: com todos os lados iguais')
elif (v1 == v2 or v3) and (v2 == v1 or v3):
print('tringulo isoceles dois lados iguais')
elif (v1 != v2 or v3) and (v2 != v1 or v3) and (v3 != v1 or v2):
print('escaleno')
else:
print('nao e um triangulo') |
# -*- coding: UTF-8 -*-
##############################################################################
# #
# Copyright (c) 2007-2010 Bernd Kreuss <prof7bit@gmail.com> #
# #
# Translation file for TorChat #
# #
##############################################################################
LANGUAGE_CODE = u"en"
LANGUAGE_NAME = u"English"
LANGUAGE_NAME_ENGLISH = u"English"
TRANSLATOR_NAMES = []
#buttons
BTN_CANCEL = u"Cancel"
BTN_OK = u"Ok"
BTN_SAVE_AS = u"Save as..."
BTN_CLOSE = u"Close"
#status
ST_AVAILABLE = u"Available"
ST_AWAY = u"Away"
ST_EXTENDED_AWAY = u"Extended away"
ST_OFFLINE = u"Offline"
#TaskbarMenu
MTB_SHOW_HIDE_TORCHAT = u"Show/Hide TorChat"
MTB_QUIT = u"Quit"
#popup menu
MPOP_CHAT = u"Chat..."
MPOP_SEND_FILE = u"Send file..."
MPOP_EDIT_CONTACT = u"Edit contact..."
MPOP_DELETE_CONTACT = u"Delete contact..."
MPOP_SHOW_OFFLINE_MESSAGES = u"Show queued offline messages"
MPOP_CLEAR_OFFLINE_MESSAGES = u"Clear queued offline messages"
MPOP_ACTIVATE_LOG = u"Activate logging to file"
MPOP_STOP_LOG = u"Stop logging"
MPOP_DELETE_EXISTING_LOG = u"Delete existing log file"
MPOP_DELETE_AND_STOP_LOG = u"Delete log and stop logging"
MPOP_ADD_CONTACT = u"Add contact..."
MPOP_ABOUT = u"About TorChat"
MPOP_ASK_AUTHOR = u"Ask %s..."
MPOP_SETTINGS = u"Settings..."
MPOP_EDIT_MY_PROFILE = u"Edit my profile..."
MPOP_COPY_ID_TO_CLIPBOARD=u"Copy ID to clipboard"
#chat window popup menu
CPOP_COPY = u"Copy"
#confirm delete message box
D_CONFIRM_DELETE_TITLE = u"Confirm deletion"
D_CONFIRM_DELETE_MESSAGE = u"Really delete this contact?\n(%s %s)"
#warning about log
D_LOG_WARNING_TITLE = u"TorChat: Logging is active"
D_LOG_WARNING_MESSAGE = u"Logging to file is activated!\n\nLog File: %s\n\nRemember to delete the log file if you have finished debugging because the log file may contain sensitive information."
#warning about used port
D_WARN_USED_PORT_TITLE = u"TorChat: Port already in use"
D_WARN_USED_PORT_MESSAGE = u"Something, probably another TorChat instance, is already listening at %s:%s. You must create another profile using different ports to be able to start TorChat a second time."
#warnig about unread messages
D_WARN_UNREAD_TITLE = u"TorChat: Unread messages"
D_WARN_UNREAD_MESSAGE = u"There are unread messages.\nThey will be lost forever!\n\nDo you really want to exit TorChat now?"
#warning about offline buddy
D_WARN_BUDDY_OFFLINE_TITLE = u"TorChat: Buddy is offline"
D_WARN_BUDDY_OFFLINE_MESSAGE = u"This operation is not possible with offline buddies"
#warning about multiple files
D_WARN_FILE_ONLY_ONE_TITLE = u"TorChat: Multiple files"
D_WARN_FILE_ONLY_ONE_MESSAGE = u"You may not start multiple file transfers with one operation. Start the transfers individually or send a zip-file instead"
#warning about file save error
D_WARN_FILE_SAVE_ERROR_TITLE = u"TorChat: Error saving file"
D_WARN_FILE_SAVE_ERROR_MESSAGE = u"The file '%s' could not be created.\n\n%s"
#warning about file already exists
D_WARN_FILE_ALREADY_EXISTS_TITLE = u"TorChat: File exists"
D_WARN_FILE_ALREADY_EXISTS_MESSAGE = u"The file '%s' already exists.\nOverwrite it?"
#dialog: add/edit contact
DEC_TITLE_ADD = u"Add new contact"
DEC_TITLE_EDIT = u"Edit contact"
DEC_TORCHAT_ID = u"TorChat ID"
DEC_DISPLAY_NAME = u"Display name"
DEC_INTRODUCTION = u"Introduction"
DEC_MSG_16_CHARACTERS = u"The address must be 16 characters long, not %i."
DEC_MSG_ONLY_ALPANUM = u"The address must only contain numbers and lowercase letters"
DEC_MSG_ALREADY_ON_LIST = u"%s is already on your list"
#dialog: edit my profile
DEP_TITLE = u"Edit my profile"
DEP_NAME = u"Name"
DEP_TEXT = u"Text"
DEP_SET_AVATAR = u"Set Avatar"
DEP_REMOVE_AVATAR = u"Remove Avatar"
DEP_AVATAR_SELECT_PNG = u"Select .PNG file to use as your avatar (will be scaled to 64*64, may contain transparency)"
DEP_PNG_FILES = u"PNG files"
DEP_ALL_FILES = u"All files"
DEP_WARN_TITLE = u"Avatar selection not possible"
DEP_WARN_IS_ALREADY = u"This is already the current avatar"
DEP_WARN_MUST_BE_PNG = u"The avatar must be a .png file"
#file transfer window
DFT_FILE_OPEN_TITLE = u"Send file to %s"
DFT_FILE_SAVE_TITLE = u"Save file from %s"
DFT_SEND = u"Sending %s\nto %s\n%04.1f%% (%i of %i bytes)"
DFT_RECEIVE = u"Receiving %s\nfrom %s\n%04.1f%% (%i of %i bytes)"
DFT_WAITING = u"waiting for connection"
DFT_STARTING = u"starting transfer"
DFT_ABORTED = u"transfer aborted"
DFT_COMPLETE = u"transfer complete"
DFT_ERROR = u"error"
#settings dialaog
DSET_TITLE = u"TorChat configuration"
DSET_NET_TITLE = u"Network"
DSET_NET_ACTIVE = u"active"
DSET_NET_INACTIVE = u"inactive"
DSET_NET_TOR_ADDRESS = u"Tor proxy address"
DSET_NET_TOR_SOCKS = u"Socks port"
DSET_NET_TOR_CONTROL = u"Control port"
DSET_NET_OWN_HOSTNAME = u"Own TorChat-ID"
DSET_NET_LISTEN_INTERFACE = u"Listen interface"
DSET_NET_LISTEN_PORT = u"Listen port"
DSET_GUI_TITLE = u"User interface"
DSET_GUI_LANGUAGE = u"Language"
DSET_GUI_OPEN_MAIN_HIDDEN = u"Start with minimized main window"
DSET_GUI_OPEN_CHAT_HIDDEN = u"Don't automatically open new windows"
DSET_GUI_NOTIFICATION_POPUP = u"Notification pop-up"
DSET_GUI_NOTIFICATION_METHOD = u"Notification method"
DSET_GUI_FLASH_WINDOW = u"Flash window title on new message"
DSET_MISC_TITLE = u"Misc"
DSET_MISC_TEMP_IN_DATA = u"Store temporary files inside data directory"
DSET_MISC_TEMP_CUSTOM_DIR = u"Temporary directory (leave empty for OS-default)"
#notices in the chat window (those in square brackets)
NOTICE_DELAYED_MSG_WAITING = u"delayed messages waiting to be sent"
NOTICE_DELAYED_MSG_SENT = u"delayed messages have been sent"
NOTICE_DELAYED = u"delayed"
#messagebox for offline messages
MSG_OFFLINE_TITLE = u"TorChat: queued messages"
MSG_OFFLINE_EMPTY = u"there are no (more) queued messages for %s"
MSG_OFFLINE_QUEUED = u"queued offline messages for %s:\n\n%s"
#buddy list mouse hover popup
BPOP_BUDDY_IS_OFFLINE = u"Buddy is offline"
BPOP_CONNECTED_AWAITING_RETURN_CONN = u"Connected, awaiting return connection..."
BPOP_CLIENT_SOFTWARE = u"Client: %s %s"
#logging of conversations to file
LOG_HEADER = u"This log file is not signed and has no cogency of proof"
LOG_STARTED = u"Logging started"
LOG_STOPPED = u"Logging stopped"
LOG_DELETED = u"Log files have been deleted"
LOG_IS_ACTIVATED = u"Logging to file is activated:\n%s"
LOG_IS_STOPPED_OLD_LOG_FOUND = u"Logging is stopped but old log file still exists:\n%s"
#about box
ABOUT_TITLE = u"About TorChat"
ABOUT_TEXT = u"""TorChat %(version)s (svn: r%(svn)s)
%(copyright)s
Translations:
%(translators)s
Runtime environment:
Python: %(python)s
wx: %(wx)s
TorChat is free software: you can redistribute it and/or \
modify it under the terms of the GNU General Public \
License as published by the Free Software Foundation, \
either version 3 of the License, or (at your option) \
any later version.
TorChat is distributed in the hope that it will be useful, \
but WITHOUT ANY WARRANTY; without even the implied \
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \
See the GNU General Public License for more details.
*
And now for something completely different:
If you happen to run a software company near Hannover, Germany and \
are in need of a new coder, feel free to regard this little program \
as my application documents and drop me a mail with your answer.
"""
| language_code = u'en'
language_name = u'English'
language_name_english = u'English'
translator_names = []
btn_cancel = u'Cancel'
btn_ok = u'Ok'
btn_save_as = u'Save as...'
btn_close = u'Close'
st_available = u'Available'
st_away = u'Away'
st_extended_away = u'Extended away'
st_offline = u'Offline'
mtb_show_hide_torchat = u'Show/Hide TorChat'
mtb_quit = u'Quit'
mpop_chat = u'Chat...'
mpop_send_file = u'Send file...'
mpop_edit_contact = u'Edit contact...'
mpop_delete_contact = u'Delete contact...'
mpop_show_offline_messages = u'Show queued offline messages'
mpop_clear_offline_messages = u'Clear queued offline messages'
mpop_activate_log = u'Activate logging to file'
mpop_stop_log = u'Stop logging'
mpop_delete_existing_log = u'Delete existing log file'
mpop_delete_and_stop_log = u'Delete log and stop logging'
mpop_add_contact = u'Add contact...'
mpop_about = u'About TorChat'
mpop_ask_author = u'Ask %s...'
mpop_settings = u'Settings...'
mpop_edit_my_profile = u'Edit my profile...'
mpop_copy_id_to_clipboard = u'Copy ID to clipboard'
cpop_copy = u'Copy'
d_confirm_delete_title = u'Confirm deletion'
d_confirm_delete_message = u'Really delete this contact?\n(%s %s)'
d_log_warning_title = u'TorChat: Logging is active'
d_log_warning_message = u'Logging to file is activated!\n\nLog File: %s\n\nRemember to delete the log file if you have finished debugging because the log file may contain sensitive information.'
d_warn_used_port_title = u'TorChat: Port already in use'
d_warn_used_port_message = u'Something, probably another TorChat instance, is already listening at %s:%s. You must create another profile using different ports to be able to start TorChat a second time.'
d_warn_unread_title = u'TorChat: Unread messages'
d_warn_unread_message = u'There are unread messages.\nThey will be lost forever!\n\nDo you really want to exit TorChat now?'
d_warn_buddy_offline_title = u'TorChat: Buddy is offline'
d_warn_buddy_offline_message = u'This operation is not possible with offline buddies'
d_warn_file_only_one_title = u'TorChat: Multiple files'
d_warn_file_only_one_message = u'You may not start multiple file transfers with one operation. Start the transfers individually or send a zip-file instead'
d_warn_file_save_error_title = u'TorChat: Error saving file'
d_warn_file_save_error_message = u"The file '%s' could not be created.\n\n%s"
d_warn_file_already_exists_title = u'TorChat: File exists'
d_warn_file_already_exists_message = u"The file '%s' already exists.\nOverwrite it?"
dec_title_add = u'Add new contact'
dec_title_edit = u'Edit contact'
dec_torchat_id = u'TorChat ID'
dec_display_name = u'Display name'
dec_introduction = u'Introduction'
dec_msg_16_characters = u'The address must be 16 characters long, not %i.'
dec_msg_only_alpanum = u'The address must only contain numbers and lowercase letters'
dec_msg_already_on_list = u'%s is already on your list'
dep_title = u'Edit my profile'
dep_name = u'Name'
dep_text = u'Text'
dep_set_avatar = u'Set Avatar'
dep_remove_avatar = u'Remove Avatar'
dep_avatar_select_png = u'Select .PNG file to use as your avatar (will be scaled to 64*64, may contain transparency)'
dep_png_files = u'PNG files'
dep_all_files = u'All files'
dep_warn_title = u'Avatar selection not possible'
dep_warn_is_already = u'This is already the current avatar'
dep_warn_must_be_png = u'The avatar must be a .png file'
dft_file_open_title = u'Send file to %s'
dft_file_save_title = u'Save file from %s'
dft_send = u'Sending %s\nto %s\n%04.1f%% (%i of %i bytes)'
dft_receive = u'Receiving %s\nfrom %s\n%04.1f%% (%i of %i bytes)'
dft_waiting = u'waiting for connection'
dft_starting = u'starting transfer'
dft_aborted = u'transfer aborted'
dft_complete = u'transfer complete'
dft_error = u'error'
dset_title = u'TorChat configuration'
dset_net_title = u'Network'
dset_net_active = u'active'
dset_net_inactive = u'inactive'
dset_net_tor_address = u'Tor proxy address'
dset_net_tor_socks = u'Socks port'
dset_net_tor_control = u'Control port'
dset_net_own_hostname = u'Own TorChat-ID'
dset_net_listen_interface = u'Listen interface'
dset_net_listen_port = u'Listen port'
dset_gui_title = u'User interface'
dset_gui_language = u'Language'
dset_gui_open_main_hidden = u'Start with minimized main window'
dset_gui_open_chat_hidden = u"Don't automatically open new windows"
dset_gui_notification_popup = u'Notification pop-up'
dset_gui_notification_method = u'Notification method'
dset_gui_flash_window = u'Flash window title on new message'
dset_misc_title = u'Misc'
dset_misc_temp_in_data = u'Store temporary files inside data directory'
dset_misc_temp_custom_dir = u'Temporary directory (leave empty for OS-default)'
notice_delayed_msg_waiting = u'delayed messages waiting to be sent'
notice_delayed_msg_sent = u'delayed messages have been sent'
notice_delayed = u'delayed'
msg_offline_title = u'TorChat: queued messages'
msg_offline_empty = u'there are no (more) queued messages for %s'
msg_offline_queued = u'queued offline messages for %s:\n\n%s'
bpop_buddy_is_offline = u'Buddy is offline'
bpop_connected_awaiting_return_conn = u'Connected, awaiting return connection...'
bpop_client_software = u'Client: %s %s'
log_header = u'This log file is not signed and has no cogency of proof'
log_started = u'Logging started'
log_stopped = u'Logging stopped'
log_deleted = u'Log files have been deleted'
log_is_activated = u'Logging to file is activated:\n%s'
log_is_stopped_old_log_found = u'Logging is stopped but old log file still exists:\n%s'
about_title = u'About TorChat'
about_text = u'TorChat %(version)s (svn: r%(svn)s)\n %(copyright)s\n\nTranslations:\n %(translators)s\n\nRuntime environment:\n Python: %(python)s\n wx: %(wx)s\n\nTorChat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nTorChat is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\n*\n\nAnd now for something completely different:\n\nIf you happen to run a software company near Hannover, Germany and are in need of a new coder, feel free to regard this little program as my application documents and drop me a mail with your answer.\n' |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class CaseTwoItem(object):
def __init__(self, ts, nginx_pods, running_trainers, collector):
self.ts = ts
self.nginx_pods = nginx_pods
self.running_trainers = running_trainers
self.cpu_utils = collector.cpu_utils()
self.gpu_utils = collector.gpu_utils()
#def values(self):
# return [str(self.times), str(self.nginx_pods), str(self.running_trainers), str(self.cpu_utils)]
class CaseTwoReport(object):
def __init__(self):
self.items = []
self.avg_cpu_utils = 0.0
self.cnt = 0
def append_item(self, item):
# append new item only if Nginx pods changed
if not self.items or \
self.items[-1].nginx_pods != item.nginx_pods or \
self.items[-1].running_trainers != item.running_trainers:
self.items.append(item)
self.avg_cpu_utils += float(item.cpu_utils)
self.cnt += 1
def title(self):
return ['TIME', 'NGINX PODS', 'RUNNING TRAINERS', 'CLUSTER CPU UTILS']
def to_csv(self, fn):
self.avg_cpu_utils /= self.cnt
with open(fn, 'w') as f:
f.write('|'.join(self.title()) + '\n')
for item in self.items:
f.write('|'.join([
str(item.ts), str(item.nginx_pods), str(
item.running_trainers), item.cpu_utils
]) + '\n')
| class Casetwoitem(object):
def __init__(self, ts, nginx_pods, running_trainers, collector):
self.ts = ts
self.nginx_pods = nginx_pods
self.running_trainers = running_trainers
self.cpu_utils = collector.cpu_utils()
self.gpu_utils = collector.gpu_utils()
class Casetworeport(object):
def __init__(self):
self.items = []
self.avg_cpu_utils = 0.0
self.cnt = 0
def append_item(self, item):
if not self.items or self.items[-1].nginx_pods != item.nginx_pods or self.items[-1].running_trainers != item.running_trainers:
self.items.append(item)
self.avg_cpu_utils += float(item.cpu_utils)
self.cnt += 1
def title(self):
return ['TIME', 'NGINX PODS', 'RUNNING TRAINERS', 'CLUSTER CPU UTILS']
def to_csv(self, fn):
self.avg_cpu_utils /= self.cnt
with open(fn, 'w') as f:
f.write('|'.join(self.title()) + '\n')
for item in self.items:
f.write('|'.join([str(item.ts), str(item.nginx_pods), str(item.running_trainers), item.cpu_utils]) + '\n') |
def isDigit(symbol):
'''
Determine if the given character is a digit or not.
'''
return symbol.isdigit()
| def is_digit(symbol):
"""
Determine if the given character is a digit or not.
"""
return symbol.isdigit() |
a = list(" " * 9)
step = 0
def printgame():
print('-' * 9)
for i in range(3):
print("| {} {} {} |".format(a[0 + 3 * i], a[1 + 3 * i], a[2 + 3 * i]))
print('-' * 9)
while " " in a:
playx, playy = input("Enter the coordinates:").split()
if (int(playx) or int(playy)) not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print("You should enter numbers!")
elif (int(playx) or int(playy)) not in [1, 2, 3]:
print("Coordinates should be from 1 to 3!")
elif a[(int(playx) - 1) + abs(int(playy) - 3) * 3] != " ":
print("This cell is occupied! Choose another one!")
else:
if step == 0:
a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "X"
step = 1
elif step == 1:
a[(int(playx) - 1) + abs(int(playy) - 3) * 3] = "O"
step = 0
printgame()
rule = [a[:3], a[3:6], a[6:], a[0:9:3], a[1:9:3], a[2:9:3], a[0:9:4], a[2:7:2]]
if ['X', 'X', 'X'] in rule:
print("X wins")
elif ['O', 'O', 'O'] in rule:
print("O wins")
elif a.count(" ") == 0:
print("Draw") | a = list(' ' * 9)
step = 0
def printgame():
print('-' * 9)
for i in range(3):
print('| {} {} {} |'.format(a[0 + 3 * i], a[1 + 3 * i], a[2 + 3 * i]))
print('-' * 9)
while ' ' in a:
(playx, playy) = input('Enter the coordinates:').split()
if (int(playx) or int(playy)) not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print('You should enter numbers!')
elif (int(playx) or int(playy)) not in [1, 2, 3]:
print('Coordinates should be from 1 to 3!')
elif a[int(playx) - 1 + abs(int(playy) - 3) * 3] != ' ':
print('This cell is occupied! Choose another one!')
else:
if step == 0:
a[int(playx) - 1 + abs(int(playy) - 3) * 3] = 'X'
step = 1
elif step == 1:
a[int(playx) - 1 + abs(int(playy) - 3) * 3] = 'O'
step = 0
printgame()
rule = [a[:3], a[3:6], a[6:], a[0:9:3], a[1:9:3], a[2:9:3], a[0:9:4], a[2:7:2]]
if ['X', 'X', 'X'] in rule:
print('X wins')
elif ['O', 'O', 'O'] in rule:
print('O wins')
elif a.count(' ') == 0:
print('Draw') |
#!/usr/bin/python3
def new_in_list(my_list, idx, element):
list1 = my_list.copy()
leng = len(my_list)
if idx < 0:
return list1
if idx >= leng:
return list1
list1[idx] = element
return list1
| def new_in_list(my_list, idx, element):
list1 = my_list.copy()
leng = len(my_list)
if idx < 0:
return list1
if idx >= leng:
return list1
list1[idx] = element
return list1 |
'''
Leap year is an year with 366 days. Leap Year should be divisible by 4.
Also it should be divisible by 400 and not divisible by 100.
'''
def checkLeapYear(year):
if year % 400 == 0:
return 1
if year % 100 == 0:
return 0
if year % 4 == 0:
return 1
return 0
year1 = int(input("Enter the first year:\n"))
year2 = int(input("Enter the second year:\n"))
print("The leap years between %d and %d are:" % (year1, year2))
for year in range(year1, year2):
if checkLeapYear(year) == 1:
print(year)
'''
Input:
2000
2050
Output:
The leap years between 2000 and 2050 are:
2000
2004
2008
2012
2016
2020
2024
2028
2032
2036
2040
2044
2048
'''
| """
Leap year is an year with 366 days. Leap Year should be divisible by 4.
Also it should be divisible by 400 and not divisible by 100.
"""
def check_leap_year(year):
if year % 400 == 0:
return 1
if year % 100 == 0:
return 0
if year % 4 == 0:
return 1
return 0
year1 = int(input('Enter the first year:\n'))
year2 = int(input('Enter the second year:\n'))
print('The leap years between %d and %d are:' % (year1, year2))
for year in range(year1, year2):
if check_leap_year(year) == 1:
print(year)
'\nInput:\n2000\n2050\n\nOutput:\nThe leap years between 2000 and 2050 are:\n2000\n2004\n2008\n2012\n2016\n2020\n2024\n2028\n2032\n2036\n2040\n2044\n2048\n' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def Eq(field, value):
return {'_field': field, '_value': value}
def Gt(field, value):
return {'_gt': {field: value}}
def Gte(field, value):
return {'_gte': {field: value}}
def Lt(field, value):
return {'_lt': {field: value}}
def Lte(field, value):
return {'_lte': {field: value}}
def And(*criteria):
return {'_and': criteria}
def Or(*criteria):
return {'_or': criteria}
def Not(criterion):
return {'_not': criterion}
def In(field, values):
return {'_in': {'_field': field, '_values': values}}
def Contains(field):
return {'_contains': field}
def Id(id):
return {'_id': id}
def Between(field, from_value, to_value):
return {'_between': {'_field': field, '_from': from_value, '_to': to_value}}
def ParentId(tpe, id):
return {'_parent': {'_type': tpe, '_id': id}}
def Parent(tpe, criterion):
return {'_parent': {'_type': tpe, '_query': criterion}}
def Child(tpe, criterion):
return {'_child': {'_type': tpe, '_query': criterion}}
def Type(tpe):
return {'_type': tpe}
def String(query_string):
return {'_string': query_string}
| def eq(field, value):
return {'_field': field, '_value': value}
def gt(field, value):
return {'_gt': {field: value}}
def gte(field, value):
return {'_gte': {field: value}}
def lt(field, value):
return {'_lt': {field: value}}
def lte(field, value):
return {'_lte': {field: value}}
def and(*criteria):
return {'_and': criteria}
def or(*criteria):
return {'_or': criteria}
def not(criterion):
return {'_not': criterion}
def in(field, values):
return {'_in': {'_field': field, '_values': values}}
def contains(field):
return {'_contains': field}
def id(id):
return {'_id': id}
def between(field, from_value, to_value):
return {'_between': {'_field': field, '_from': from_value, '_to': to_value}}
def parent_id(tpe, id):
return {'_parent': {'_type': tpe, '_id': id}}
def parent(tpe, criterion):
return {'_parent': {'_type': tpe, '_query': criterion}}
def child(tpe, criterion):
return {'_child': {'_type': tpe, '_query': criterion}}
def type(tpe):
return {'_type': tpe}
def string(query_string):
return {'_string': query_string} |
class LinkNodeIter:
def __init__(self, link):
self._link = link
def __iter__(self):
return self
def __next__(self):
next_value = self._link
if next_value is not None:
self._link = next_value.next_link
else:
raise StopIteration
return next_value
| class Linknodeiter:
def __init__(self, link):
self._link = link
def __iter__(self):
return self
def __next__(self):
next_value = self._link
if next_value is not None:
self._link = next_value.next_link
else:
raise StopIteration
return next_value |
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
count = 0
for index in range(len(points)-1):
count += max(abs(points[index][0]-points[index+1][0]), abs(points[index][1]-points[index+1][1]))
return count
| class Solution:
def min_time_to_visit_all_points(self, points: List[List[int]]) -> int:
count = 0
for index in range(len(points) - 1):
count += max(abs(points[index][0] - points[index + 1][0]), abs(points[index][1] - points[index + 1][1]))
return count |
async def db_get(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
async for row in cursor:
yield dict(row)
async def db_get_one(db, column, query, **parameters):
async for row in db_get(db, query, **parameters):
return row.get(column, None)
else:
return None
async def db_get_first(db, query, **parameters):
async for row in db_get(db, query, **parameters):
return row
else:
return None
async def insert_one(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
return cursor.lastrowid
| async def db_get(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
async for row in cursor:
yield dict(row)
async def db_get_one(db, column, query, **parameters):
async for row in db_get(db, query, **parameters):
return row.get(column, None)
else:
return None
async def db_get_first(db, query, **parameters):
async for row in db_get(db, query, **parameters):
return row
else:
return None
async def insert_one(db, query, **parameters):
async with db.execute(query, parameters) as cursor:
return cursor.lastrowid |
def test_line_highlight_fragments(test_env):
slide = test_env.slide
img = test_env.data_path("testimage.svg")
slide.image(img)
b = slide.box(x="[90%]", y="[30%]", width="30%", height="30%", show="4+")
b.rect("black", bg_color="white")
b2 = b.box(width="fill")
b2.update_style("default", size=15, color="white")
b2.rect(bg_color="black")
b2.box(padding=10).text("Scaling and placing images")
b.fbox().image(img, show_begin=4)
test_env.check("imagefrag", 6)
def test_line_highlight_no_fragments(test_env):
slide = test_env.slide
img = test_env.data_path("testimage.svg")
slide.image(img, fragments=False)
b = slide.box(x="[90%]", y="[30%]", width="30%", height="30%")
b.rect("black", bg_color="white")
b2 = b.box(width="fill")
b2.update_style("default", size=15, color="white")
b2.rect(bg_color="black")
b2.box(padding=10).text("Scaling and placing images")
b.fbox().image(img, fragments=False)
test_env.check("imagenofrag")
def test_image_show(test_env):
""" Regresion test for show attribute when element has no childs """
slide = test_env.slide
slide.image(test_env.data_path("testimage2.svg"))
test_env.check("imageshowx", 3)
def test_image_no_fragments_show_begin(test_env):
slide = test_env.slide
img = test_env.data_path("testimage.svg")
slide.image(img, fragments=False, show_begin=3)
test_env.check("nofrag_showbegin", 3) | def test_line_highlight_fragments(test_env):
slide = test_env.slide
img = test_env.data_path('testimage.svg')
slide.image(img)
b = slide.box(x='[90%]', y='[30%]', width='30%', height='30%', show='4+')
b.rect('black', bg_color='white')
b2 = b.box(width='fill')
b2.update_style('default', size=15, color='white')
b2.rect(bg_color='black')
b2.box(padding=10).text('Scaling and placing images')
b.fbox().image(img, show_begin=4)
test_env.check('imagefrag', 6)
def test_line_highlight_no_fragments(test_env):
slide = test_env.slide
img = test_env.data_path('testimage.svg')
slide.image(img, fragments=False)
b = slide.box(x='[90%]', y='[30%]', width='30%', height='30%')
b.rect('black', bg_color='white')
b2 = b.box(width='fill')
b2.update_style('default', size=15, color='white')
b2.rect(bg_color='black')
b2.box(padding=10).text('Scaling and placing images')
b.fbox().image(img, fragments=False)
test_env.check('imagenofrag')
def test_image_show(test_env):
""" Regresion test for show attribute when element has no childs """
slide = test_env.slide
slide.image(test_env.data_path('testimage2.svg'))
test_env.check('imageshowx', 3)
def test_image_no_fragments_show_begin(test_env):
slide = test_env.slide
img = test_env.data_path('testimage.svg')
slide.image(img, fragments=False, show_begin=3)
test_env.check('nofrag_showbegin', 3) |
red = "#c91111"
orange = "#e09401"
pale_blue = "#13aed5"
dark_blue = "#1321d8"
purple = "#642197"
| red = '#c91111'
orange = '#e09401'
pale_blue = '#13aed5'
dark_blue = '#1321d8'
purple = '#642197' |
"""Wagtail Live Exceptions."""
class RequestVerificationError(Exception):
pass
class WebhookSetupError(Exception):
pass
| """Wagtail Live Exceptions."""
class Requestverificationerror(Exception):
pass
class Webhooksetuperror(Exception):
pass |
# -*- coding: UTF-8 -*-
logger.info("Loading 8 objects to table lists_list...")
# fields: id, ref, designation, list_type, remarks
loader.save(create_lists_list(1,None,['Announcements', 'Ank\xfcndigungen', 'Announcements'],1,u''))
loader.save(create_lists_list(2,None,['Weekly newsletter', 'Weekly newsletter', 'Weekly newsletter'],1,u''))
loader.save(create_lists_list(3,None,['General discussion', 'General discussion', 'General discussion'],2,u''))
loader.save(create_lists_list(4,None,['Beginners forum', 'Beginners forum', 'Beginners forum'],2,u''))
loader.save(create_lists_list(5,None,['Developers forum', 'Developers forum', 'Developers forum'],2,u''))
loader.save(create_lists_list(6,None,['PyCon 2014', 'PyCon 2014', 'PyCon 2014'],3,u''))
loader.save(create_lists_list(7,None,['Free Software Day 2014', 'Free Software Day 2014', 'Free Software Day 2014'],3,u''))
loader.save(create_lists_list(8,None,['Schools', 'Schulen', 'Schools'],3,u''))
loader.flush_deferred_objects()
| logger.info('Loading 8 objects to table lists_list...')
loader.save(create_lists_list(1, None, ['Announcements', 'Ankündigungen', 'Announcements'], 1, u''))
loader.save(create_lists_list(2, None, ['Weekly newsletter', 'Weekly newsletter', 'Weekly newsletter'], 1, u''))
loader.save(create_lists_list(3, None, ['General discussion', 'General discussion', 'General discussion'], 2, u''))
loader.save(create_lists_list(4, None, ['Beginners forum', 'Beginners forum', 'Beginners forum'], 2, u''))
loader.save(create_lists_list(5, None, ['Developers forum', 'Developers forum', 'Developers forum'], 2, u''))
loader.save(create_lists_list(6, None, ['PyCon 2014', 'PyCon 2014', 'PyCon 2014'], 3, u''))
loader.save(create_lists_list(7, None, ['Free Software Day 2014', 'Free Software Day 2014', 'Free Software Day 2014'], 3, u''))
loader.save(create_lists_list(8, None, ['Schools', 'Schulen', 'Schools'], 3, u''))
loader.flush_deferred_objects() |
if __name__ == '__main__':
N = int(input())
elements = []
posicion = ""
dato = ""
for i in range(N):
commands = input()
longitud = len(commands)
if commands[0:6] == "insert" :
if(commands[8] == " "):
posicion = commands[7]
dato = commands[9:longitud+1]
elif commands[9] == " ":
posicion = commands[7:8]
dato = commands[10:longitud+1]
elements.insert(int(posicion),int(dato))
elif commands == "print":
print(elements)
elif commands[0:6] == "remove":
elements.remove(int(commands[7:longitud+1]))
elif commands[0:6] == "append":
elements.append(int(commands[7:longitud+1]))
elif commands == "sort":
elements.sort()
elif commands == "pop":
elements.pop()
else:
elements.reverse()
| if __name__ == '__main__':
n = int(input())
elements = []
posicion = ''
dato = ''
for i in range(N):
commands = input()
longitud = len(commands)
if commands[0:6] == 'insert':
if commands[8] == ' ':
posicion = commands[7]
dato = commands[9:longitud + 1]
elif commands[9] == ' ':
posicion = commands[7:8]
dato = commands[10:longitud + 1]
elements.insert(int(posicion), int(dato))
elif commands == 'print':
print(elements)
elif commands[0:6] == 'remove':
elements.remove(int(commands[7:longitud + 1]))
elif commands[0:6] == 'append':
elements.append(int(commands[7:longitud + 1]))
elif commands == 'sort':
elements.sort()
elif commands == 'pop':
elements.pop()
else:
elements.reverse() |
IMG_HEIGHT = 480
IMG_WIDTH = 640
CLASS_NUM = 3
ANCHORS_GROUP = {
32:[[730,145],[288,190],[216,540]],
16:[[365,73],[144,95],[108,270]],
8:[[180,37],[72,44],[54,135]]
}
ANCHORS_GROUP_AREA = {
32: [x * y for x, y in ANCHORS_GROUP[32]],
16: [x * y for x, y in ANCHORS_GROUP[16]],
8: [x * y for x, y in ANCHORS_GROUP[8]],
}
color=['#ff0000','#0000ff','#00ff00']
| img_height = 480
img_width = 640
class_num = 3
anchors_group = {32: [[730, 145], [288, 190], [216, 540]], 16: [[365, 73], [144, 95], [108, 270]], 8: [[180, 37], [72, 44], [54, 135]]}
anchors_group_area = {32: [x * y for (x, y) in ANCHORS_GROUP[32]], 16: [x * y for (x, y) in ANCHORS_GROUP[16]], 8: [x * y for (x, y) in ANCHORS_GROUP[8]]}
color = ['#ff0000', '#0000ff', '#00ff00'] |
def devedor(*args):
try:
telaDevedores = args[0]
telaErro = args[1]
cursor = args[2]
banco10 = args[3]
data = args[4]
id = telaDevedores.codigo.text()
sql = ("select id from gerenciarPedido where id = %s and dataa = %s")
values = (id, data)
cursor.execute(sql, values)
dados2 = cursor.fetchall()
id2 = dados2[0][0]
sql = ("select dataa, hora, nome, telefone, valorTotal from gerenciarPedido where id = %s and dataa = %s")
values = (id2, data)
cursor.execute(sql, values)
inf_cliente = cursor.fetchall()
motivo = telaDevedores.motivo_dever.text()
sql = "insert into devedores(id, dataa, hora, nome, telefone, valor, motivo) values (%s, %s, %s, %s, %s, %s, %s)"
insert = (str(id2), str(inf_cliente[0][0]), str(inf_cliente[0][1]),
str(inf_cliente[0][2]), str(inf_cliente[0][3]),
str(inf_cliente[0][4]), str(motivo))
cursor.execute(sql, insert)
banco10.commit()
telaDevedores.hide()
except:
telaErro.show()
telaErro.label.setText('Codigo invalido, tente novamente!') | def devedor(*args):
try:
tela_devedores = args[0]
tela_erro = args[1]
cursor = args[2]
banco10 = args[3]
data = args[4]
id = telaDevedores.codigo.text()
sql = 'select id from gerenciarPedido where id = %s and dataa = %s'
values = (id, data)
cursor.execute(sql, values)
dados2 = cursor.fetchall()
id2 = dados2[0][0]
sql = 'select dataa, hora, nome, telefone, valorTotal from gerenciarPedido where id = %s and dataa = %s'
values = (id2, data)
cursor.execute(sql, values)
inf_cliente = cursor.fetchall()
motivo = telaDevedores.motivo_dever.text()
sql = 'insert into devedores(id, dataa, hora, nome, telefone, valor, motivo) values (%s, %s, %s, %s, %s, %s, %s)'
insert = (str(id2), str(inf_cliente[0][0]), str(inf_cliente[0][1]), str(inf_cliente[0][2]), str(inf_cliente[0][3]), str(inf_cliente[0][4]), str(motivo))
cursor.execute(sql, insert)
banco10.commit()
telaDevedores.hide()
except:
telaErro.show()
telaErro.label.setText('Codigo invalido, tente novamente!') |
name1_0_0_0_1_1_0 = None
name1_0_0_0_1_1_1 = None
name1_0_0_0_1_1_2 = None
name1_0_0_0_1_1_3 = None
name1_0_0_0_1_1_4 = None | name1_0_0_0_1_1_0 = None
name1_0_0_0_1_1_1 = None
name1_0_0_0_1_1_2 = None
name1_0_0_0_1_1_3 = None
name1_0_0_0_1_1_4 = None |
LOCATIONemojis = {
"fastbackwards": "<:fast_forward_left:870781340692402226>",
"backwards": "<:left_arrow:870781340990197860>",
"close": "<:Cross:863313854069997578>",
"forwards": "<:right_arrow:870781340314898473>",
"fastforwards": "<:fast_forward_right:870781340839202837>",
}
COGemojis = {
"JesterInfo": 863075610048987166,
"Feedback": 863075610851147777,
"Music": 863075611320647719,
"Snipe": 863075611269791794,
"Fun": 863075609781075968,
"Mod": 863075610784301068,
"Games": 863075611329167380,
"Utils": 863075611161788478,
"Images": 863075611277656124,
"Economy": 863075610913800233,
"Misc": 863075610979729409,
"Levels": 863075611182628895,
"Config": 863075611169259550,
"Love": 863075611374125056,
"JesterJokes": 873327129016811528,
"Cryptocurrency": 872473402764570624,
"Countries": 872473402638762025,
"ChatBot": 872473402693259324,
"DiscordTogether": 872473402840076288,
"UrbanDictionary": 924074967673503796,
"Random": 924074967405051965,
"Trivia": 924152372001910834,
"Crime": 924411072729985046,
"Docs": 925222917946605629,
}
CLOSE = "<:Cross:863313854069997578>"
HOME = "<:Arrow:863313854040506379>"
LINK = "<:links:870781340700782612>"
CATEGORIES = "<:menus:870781340746932225>"
TRASHCAN = "<:trashbin:873564727006089287>"
j = "<:J_:863313855286607932>"
e = "<:E_:863313854150606848>"
s = "<:S:863313855061164062>"
t = "<:T:863313855399329812>"
r = "<:R_:863313855119360022>"
| locatio_nemojis = {'fastbackwards': '<:fast_forward_left:870781340692402226>', 'backwards': '<:left_arrow:870781340990197860>', 'close': '<:Cross:863313854069997578>', 'forwards': '<:right_arrow:870781340314898473>', 'fastforwards': '<:fast_forward_right:870781340839202837>'}
co_gemojis = {'JesterInfo': 863075610048987166, 'Feedback': 863075610851147777, 'Music': 863075611320647719, 'Snipe': 863075611269791794, 'Fun': 863075609781075968, 'Mod': 863075610784301068, 'Games': 863075611329167380, 'Utils': 863075611161788478, 'Images': 863075611277656124, 'Economy': 863075610913800233, 'Misc': 863075610979729409, 'Levels': 863075611182628895, 'Config': 863075611169259550, 'Love': 863075611374125056, 'JesterJokes': 873327129016811528, 'Cryptocurrency': 872473402764570624, 'Countries': 872473402638762025, 'ChatBot': 872473402693259324, 'DiscordTogether': 872473402840076288, 'UrbanDictionary': 924074967673503796, 'Random': 924074967405051965, 'Trivia': 924152372001910834, 'Crime': 924411072729985046, 'Docs': 925222917946605629}
close = '<:Cross:863313854069997578>'
home = '<:Arrow:863313854040506379>'
link = '<:links:870781340700782612>'
categories = '<:menus:870781340746932225>'
trashcan = '<:trashbin:873564727006089287>'
j = '<:J_:863313855286607932>'
e = '<:E_:863313854150606848>'
s = '<:S:863313855061164062>'
t = '<:T:863313855399329812>'
r = '<:R_:863313855119360022>' |
#!/usr/local/bin/python
# Think Like a Programmer Chapter 2: Pure Puzzles exercises
def main():
test_pound_shapes = False
test_base_conversion = True
if test_pound_shapes:
poundV()
print()
poundDiamond()
if test_base_conversion:
tests = [
# [1, 1, 2, 1], # ValueError test
# ['G', 17, 10, 17], # ValueError test
# [15, 10, 10, '15'],
# ['101', 2, 10, '5'],
# ['1000', 2, 10, '8'],
# ['A', 16, 10, '10'],
# ['10', 16, 10, '16'],
[11, 10, 16, 'B'],
['1100', 2, 16, 'C']
]
for t in tests:
print("Testing baseConversion({}, {}, {})"
.format(t[0], t[1], t[2]))
try:
res = baseConversion(t[0], t[1], t[2])
if t[3] == res:
print("PASSED: baseConversion({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print("FAILED: baseConversion({}, {}, {}) returned {}, "
"answer: {}".format(t[0], t[1], t[2], res, t[3]))
except ValueError:
print("PASSED: ValueError test")
def poundV():
'''
Using only single output statements of a space, pound, or new line, create:
########
######
####
##
'''
n = 4
space = ' '
pound = '#'
for i in range(n, 0, -1):
print((space * (n - i)) + (pound * i * 2) + (space * (n - i)))
def poundDiamond():
'''
Using only single output statements of a space, pound, or new line, create:
##
####
######
########
########
######
####
##
'''
n = 4
space = ' '
pound = '#'
rangeItem = list(range(1, n + 1))
for i in rangeItem + rangeItem[::-1]:
print((space * (n - i)) + (pound * i * 2) + (space * (n - i)))
def baseConversion(num, s_base, t_base):
'''
Takes a number num as str or int. Converts it from the source base (s_base,
an int) into the target base (t_base, an int) and returns new number
as a string.
Source and target bases must be between 2 and 16.
Input: num (str), s_base (int), t_base (int)
Output: str
'''
num = str(num)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']
# Input checking
if type(s_base) is not int or type(t_base) is not int:
raise ValueError
if (s_base < 2 or s_base > 16 or t_base < 2 or t_base > 16):
raise ValueError
# Convert number to base 10
if s_base == 10:
# print("Num in base 10 already: {}".format(num))
base_10 = int(num)
else:
# print("Converting {} to base 10 from base {}".format(num, s_base))
base_10 = sum([digits.index(ch) * (s_base ** i) for i, ch in
enumerate(list(num)[::-1])])
# print("Num in base 10 is: {}".format(base_10))
# Convert base-10 number to target base
converted = ''
if t_base == 10:
converted = str(base_10)
else:
while base_10 > 0:
r = base_10 % t_base
converted = digits[r] + converted
# print("Num: {}, num/{}: {}, digit: {}"
# .format(base_10, t_base, r, digits[r]))
base_10 //= t_base
return converted
if __name__ == '__main__':
main()
| def main():
test_pound_shapes = False
test_base_conversion = True
if test_pound_shapes:
pound_v()
print()
pound_diamond()
if test_base_conversion:
tests = [[11, 10, 16, 'B'], ['1100', 2, 16, 'C']]
for t in tests:
print('Testing baseConversion({}, {}, {})'.format(t[0], t[1], t[2]))
try:
res = base_conversion(t[0], t[1], t[2])
if t[3] == res:
print('PASSED: baseConversion({}, {}, {}) returned {}'.format(t[0], t[1], t[2], res))
else:
print('FAILED: baseConversion({}, {}, {}) returned {}, answer: {}'.format(t[0], t[1], t[2], res, t[3]))
except ValueError:
print('PASSED: ValueError test')
def pound_v():
"""
Using only single output statements of a space, pound, or new line, create:
########
######
####
##
"""
n = 4
space = ' '
pound = '#'
for i in range(n, 0, -1):
print(space * (n - i) + pound * i * 2 + space * (n - i))
def pound_diamond():
"""
Using only single output statements of a space, pound, or new line, create:
##
####
######
########
########
######
####
##
"""
n = 4
space = ' '
pound = '#'
range_item = list(range(1, n + 1))
for i in rangeItem + rangeItem[::-1]:
print(space * (n - i) + pound * i * 2 + space * (n - i))
def base_conversion(num, s_base, t_base):
"""
Takes a number num as str or int. Converts it from the source base (s_base,
an int) into the target base (t_base, an int) and returns new number
as a string.
Source and target bases must be between 2 and 16.
Input: num (str), s_base (int), t_base (int)
Output: str
"""
num = str(num)
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
if type(s_base) is not int or type(t_base) is not int:
raise ValueError
if s_base < 2 or s_base > 16 or t_base < 2 or (t_base > 16):
raise ValueError
if s_base == 10:
base_10 = int(num)
else:
base_10 = sum([digits.index(ch) * s_base ** i for (i, ch) in enumerate(list(num)[::-1])])
converted = ''
if t_base == 10:
converted = str(base_10)
else:
while base_10 > 0:
r = base_10 % t_base
converted = digits[r] + converted
base_10 //= t_base
return converted
if __name__ == '__main__':
main() |
class Table(object):
def __init__(self):
self.rows = []
def to_ascii_table(self):
if not self.rows:
return ""
lines = []
def print_row(row):
line = ""
for column, l in zip(row, lens):
if column is None:
s = ""
else:
s = str(column)
line += "| " + s + " " * (l - len(s)) + " "
line += "|\n"
lines.append(line)
lens = []
for i, column in enumerate(self.rows[0]):
lens.append(max(len(str(r[i]))
for r in self.rows if r[i] is not None))
width = sum(lens) + 3 * len(self.rows[0]) + 1
separator = ("-" * width) + "\n"
lines.append(separator)
print_row(self.rows[0])
lines.append(separator)
if len(self.rows) == 1:
return
for row in self.rows[1:]:
print_row(row)
lines.append(separator)
return "".join(lines)
def transpose(self):
if not self.rows:
return
table = Table()
for i in xrange(len(self.rows[0])):
table.add_row([r[i] for r in self.rows])
return table
def add_row(self, data):
self.rows.append(data)
def add_rows(self, rows):
self.rows.extend(rows)
def add_dictionaries(self, items, columns):
self.add_row(columns)
for item in items:
row = [item.get(column) for column in columns]
self.add_row(row)
| class Table(object):
def __init__(self):
self.rows = []
def to_ascii_table(self):
if not self.rows:
return ''
lines = []
def print_row(row):
line = ''
for (column, l) in zip(row, lens):
if column is None:
s = ''
else:
s = str(column)
line += '| ' + s + ' ' * (l - len(s)) + ' '
line += '|\n'
lines.append(line)
lens = []
for (i, column) in enumerate(self.rows[0]):
lens.append(max((len(str(r[i])) for r in self.rows if r[i] is not None)))
width = sum(lens) + 3 * len(self.rows[0]) + 1
separator = '-' * width + '\n'
lines.append(separator)
print_row(self.rows[0])
lines.append(separator)
if len(self.rows) == 1:
return
for row in self.rows[1:]:
print_row(row)
lines.append(separator)
return ''.join(lines)
def transpose(self):
if not self.rows:
return
table = table()
for i in xrange(len(self.rows[0])):
table.add_row([r[i] for r in self.rows])
return table
def add_row(self, data):
self.rows.append(data)
def add_rows(self, rows):
self.rows.extend(rows)
def add_dictionaries(self, items, columns):
self.add_row(columns)
for item in items:
row = [item.get(column) for column in columns]
self.add_row(row) |
class DeviceSelectCredential:
def __init__(self, number):
pass
def __call__(self, status):
pass
| class Deviceselectcredential:
def __init__(self, number):
pass
def __call__(self, status):
pass |
expected_output={
"rlist_id": {
"0xf0001ae8": {
"flags": "0x0",
"packets": 38793,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001ae9": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001aea": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
},
"0xf0001aeb": {
"flags": "0x0",
"packets": 0,
"pps": 0,
"remote_ifs": 0,
"state": 1,
"status": "OK"
}
}
}
| expected_output = {'rlist_id': {'0xf0001ae8': {'flags': '0x0', 'packets': 38793, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001ae9': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001aea': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}, '0xf0001aeb': {'flags': '0x0', 'packets': 0, 'pps': 0, 'remote_ifs': 0, 'state': 1, 'status': 'OK'}}} |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
v = self.gf(l1) + self.gf(l2)
ll = ListNode(str(v)[::-1][0])
t = ll
for i in str(v)[::-1][1:]:
t.next = ListNode(i)
t = t.next
return ll
def gf(self, l: ListNode):
s = 0
c = 1
while l.next:
s += l.val * c
c *= 10
l = l.next
s += l.val * c
return s
def ii(ll):
l = ListNode(ll[0])
t = l
for i in ll[1:]:
print(i)
t.next = ListNode(i)
t = t.next
return l
def p(lll):
print("=====")
while lll.next:
print(lll.val)
lll = lll.next
print(lll.val)
if __name__ == "__main__":
ll1 = [2, 4, 3]
ll2 = [5, 6, 4]
p(ii(ll1))
# ss = Solution()
| class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
v = self.gf(l1) + self.gf(l2)
ll = list_node(str(v)[::-1][0])
t = ll
for i in str(v)[::-1][1:]:
t.next = list_node(i)
t = t.next
return ll
def gf(self, l: ListNode):
s = 0
c = 1
while l.next:
s += l.val * c
c *= 10
l = l.next
s += l.val * c
return s
def ii(ll):
l = list_node(ll[0])
t = l
for i in ll[1:]:
print(i)
t.next = list_node(i)
t = t.next
return l
def p(lll):
print('=====')
while lll.next:
print(lll.val)
lll = lll.next
print(lll.val)
if __name__ == '__main__':
ll1 = [2, 4, 3]
ll2 = [5, 6, 4]
p(ii(ll1)) |
def get_fs(client):
"""Return the db containing file system metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection fs
"""
#get the MongoDb collection called "fs"
metadatafs = client['metadatafs']
return metadatafs['fs']
def get_users(client):
"""Return the db containing users metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users
"""
#get the MongoDb collection called "users"
metadatafs = client['metadatafs']
return metadatafs['users']
def get_groups(client):
"""Return the db containing groups metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection groups
"""
#get the MongoDb collection called "groups"
metadatafs = client['metadatafs']
return metadatafs['groups']
def get_trash(client):
"""Return the db containing trash chunks to delete.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection trash
"""
#get the MongoDb collection called "trash"
metadatafs = client['metadatafs']
return metadatafs['trash']
| def get_fs(client):
"""Return the db containing file system metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection fs
"""
metadatafs = client['metadatafs']
return metadatafs['fs']
def get_users(client):
"""Return the db containing users metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection users
"""
metadatafs = client['metadatafs']
return metadatafs['users']
def get_groups(client):
"""Return the db containing groups metadata.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection groups
"""
metadatafs = client['metadatafs']
return metadatafs['groups']
def get_trash(client):
"""Return the db containing trash chunks to delete.
Parameters
----------
client --> pymongo.mongo_client.MongoClient class, MongoDB client
Returns
-------
metadatafs['fs'] --> pymongo.collection.Collection, reference to collection trash
"""
metadatafs = client['metadatafs']
return metadatafs['trash'] |
"""BLE/LSL interfacing parameters for specific devices.
TODO:
* Simple class (or specification/template) for device parameters
"""
| """BLE/LSL interfacing parameters for specific devices.
TODO:
* Simple class (or specification/template) for device parameters
""" |
file = open('rosalind_cons.txt', 'r')
target = file.read()
d_list = []
class DNAcon:
def __init__(self):
self.A = 0
self.C = 0
self.G = 0
self.T = 0
def add_A(self, value):
self.A += value
def add_C(self, value):
self.C += value
def add_G(self, value):
self.G += value
def add_T(self, value):
self.T += value
def inserter(target_str, target_list):
raw = target_str
while not raw.isspace() or len(raw) == 0:
if raw[0] == '>':
raw = raw[raw.index('\n') + 1:]
try:
loc = raw[0: raw.index('>')]
loc = loc.replace('\n', '')
target_list.append(loc)
except:
loc = raw[0:]
loc = loc.replace('\n', '')
target_list.append(loc)
return
raw = raw[raw.index('>'):]
else:
return
inserter(target, d_list)
maxlen = 0
for con in d_list:
see = len(con)
if see >= maxlen:
maxlen = see
matrix = []
for i in range(maxlen):
target = DNAcon()
for con in d_list:
try:
val = con[i]
if val == 'A':
target.add_A(1)
elif val == 'C':
target.add_C(1)
elif val == 'G':
target.add_G(1)
elif val == 'T':
target.add_T(1)
except:
continue
matrix.append(target)
consensus = ''
for dna in matrix:
maximum = 0
val = ''
if dna.A >= maximum:
maximum = dna.A
val = 'A'
if dna.C >= maximum:
maximum = dna.C
val = 'C'
if dna.G >= maximum:
maximum = dna.G
val = 'G'
if dna.T >= maximum:
maximum = dna.T
val = 'T'
consensus += val
print(consensus)
for i in range(4):
if i == 0:
print('A:', end=' ')
for dna in matrix:
print(dna.A, end=' ')
elif i == 1:
print('C:', end=' ')
for dna in matrix:
print(dna.C, end=' ')
elif i == 2:
print('G:', end=' ')
for dna in matrix:
print(dna.G, end=' ')
elif i == 3:
print('T:', end=' ')
for dna in matrix:
print(dna.T, end=' ')
print()
| file = open('rosalind_cons.txt', 'r')
target = file.read()
d_list = []
class Dnacon:
def __init__(self):
self.A = 0
self.C = 0
self.G = 0
self.T = 0
def add_a(self, value):
self.A += value
def add_c(self, value):
self.C += value
def add_g(self, value):
self.G += value
def add_t(self, value):
self.T += value
def inserter(target_str, target_list):
raw = target_str
while not raw.isspace() or len(raw) == 0:
if raw[0] == '>':
raw = raw[raw.index('\n') + 1:]
try:
loc = raw[0:raw.index('>')]
loc = loc.replace('\n', '')
target_list.append(loc)
except:
loc = raw[0:]
loc = loc.replace('\n', '')
target_list.append(loc)
return
raw = raw[raw.index('>'):]
else:
return
inserter(target, d_list)
maxlen = 0
for con in d_list:
see = len(con)
if see >= maxlen:
maxlen = see
matrix = []
for i in range(maxlen):
target = dn_acon()
for con in d_list:
try:
val = con[i]
if val == 'A':
target.add_A(1)
elif val == 'C':
target.add_C(1)
elif val == 'G':
target.add_G(1)
elif val == 'T':
target.add_T(1)
except:
continue
matrix.append(target)
consensus = ''
for dna in matrix:
maximum = 0
val = ''
if dna.A >= maximum:
maximum = dna.A
val = 'A'
if dna.C >= maximum:
maximum = dna.C
val = 'C'
if dna.G >= maximum:
maximum = dna.G
val = 'G'
if dna.T >= maximum:
maximum = dna.T
val = 'T'
consensus += val
print(consensus)
for i in range(4):
if i == 0:
print('A:', end=' ')
for dna in matrix:
print(dna.A, end=' ')
elif i == 1:
print('C:', end=' ')
for dna in matrix:
print(dna.C, end=' ')
elif i == 2:
print('G:', end=' ')
for dna in matrix:
print(dna.G, end=' ')
elif i == 3:
print('T:', end=' ')
for dna in matrix:
print(dna.T, end=' ')
print() |
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
x3, y3 = list(map(int, input().split()))
x4 = 0
y4 = 0
if x1 == x2:
x4 = x3
elif x2 == x3:
x4 = x1
else:
x4 = x2
if y1 == y2:
y4 = y3
elif y2 == y3:
y4 = y1
else:
y4 = y2
print("{0} {1}".format(x4, y4))
| (x1, y1) = list(map(int, input().split()))
(x2, y2) = list(map(int, input().split()))
(x3, y3) = list(map(int, input().split()))
x4 = 0
y4 = 0
if x1 == x2:
x4 = x3
elif x2 == x3:
x4 = x1
else:
x4 = x2
if y1 == y2:
y4 = y3
elif y2 == y3:
y4 = y1
else:
y4 = y2
print('{0} {1}'.format(x4, y4)) |
# -*- coding: utf-8 -*-
"""
longboxed.comics
~~~~~~~~~~~~~~~~
longboxed comics package
""" | """
longboxed.comics
~~~~~~~~~~~~~~~~
longboxed comics package
""" |
def non_repeating(data):
state = dict()
for i in data:
if i not in state:
state[i] = 1
else:
state[i] = state[i] + 1
for i in data:
if state[i] == 1:
return i
return None
if __name__ == "__main__":
print(non_repeating("aaabbcdde"))
print(non_repeating("aaabbeddc"))
print(non_repeating("aabb"))
| def non_repeating(data):
state = dict()
for i in data:
if i not in state:
state[i] = 1
else:
state[i] = state[i] + 1
for i in data:
if state[i] == 1:
return i
return None
if __name__ == '__main__':
print(non_repeating('aaabbcdde'))
print(non_repeating('aaabbeddc'))
print(non_repeating('aabb')) |
# Databricks notebook source
# MAGIC %md # CCU002_02-D01-event_counts
# MAGIC
# MAGIC **Description** This notebook calculates the number of primary events from HES and death records for events.
# MAGIC
# MAGIC **Author(s)** Venexia Walker, Tom Bolton
# COMMAND ----------
# MAGIC %md ## Define functions
# COMMAND ----------
# Define create table function by Sam Hollings
# Source: Workspaces/dars_nic_391419_j3w9t_collab/DATA_CURATION_wrang000_functions
def create_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', select_sql_script:str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database."""
spark.conf.set("spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation","true")
if select_sql_script is None:
select_sql_script = f"SELECT * FROM global_temp.{table_name}"
spark.sql(f"""CREATE TABLE {database_name}.{table_name} AS
{select_sql_script}
""")
spark.sql(f"ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}")
def drop_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', if_exists=True):
if if_exists:
IF_EXISTS = 'IF EXISTS'
else:
IF_EXISTS = ''
spark.sql(f"DROP TABLE {IF_EXISTS} {database_name}.{table_name}")
# COMMAND ----------
# MAGIC %md ## Refresh tables
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Remove cached HES table
# MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Remove cached deaths table
# MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Remove cached skinny table
# MAGIC REFRESH TABLE dars_nic_391419_j3w9t_collab.curr302_patient_skinny_record
# COMMAND ----------
# MAGIC %md ## Define event codes
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Record the codes that define each event of interest
# MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW event_codes AS
# MAGIC SELECT
# MAGIC *
# MAGIC FROM VALUES
# MAGIC ('I21','incident myocardial infarction',0),
# MAGIC ('I22','incident myocardial infarction',0),
# MAGIC ('I23','incident myocardial infarction',0),
# MAGIC ('H34','retinal infarction',0),
# MAGIC ('I630','ischaemic stroke',0),
# MAGIC ('I631','ischaemic stroke',0),
# MAGIC ('I632','ischaemic stroke',0),
# MAGIC ('I633','ischaemic stroke',0),
# MAGIC ('I634','ischaemic stroke',0),
# MAGIC ('I635','ischaemic stroke',0),
# MAGIC ('I637','ischaemic stroke',0),
# MAGIC ('I638','ischaemic stroke',0),
# MAGIC ('I639','ischaemic stroke',0),
# MAGIC ('I63X','ischaemic stroke',0),
# MAGIC ('I64','stroke of unknown type',0),
# MAGIC ('I60','stroke, subarachnoid haemorrhage',0),
# MAGIC ('I74','other arterial embolism',0),
# MAGIC ('I260','pulmonary embolism',0),
# MAGIC ('I269','pulmonary embolism',0),
# MAGIC ('I80','deep vein thrombosis',0),
# MAGIC ('I81','portal vein thrombosis',0),
# MAGIC ('I820','other deep vein thrombosis',0),
# MAGIC ('I822','other deep vein thrombosis',0),
# MAGIC ('I823','other deep vein thrombosis',0),
# MAGIC ('I828','other deep vein thrombosis',0),
# MAGIC ('I829','other deep vein thrombosis',0),
# MAGIC ('O223','thrombosis during pregnancy and puerperium',1),
# MAGIC ('O871','thrombosis during pregnancy and puerperium',1),
# MAGIC ('O879','thrombosis during pregnancy and puerperium',1),
# MAGIC ('O882','thrombosis during pregnancy and puerperium',1),
# MAGIC ('O225','cerebral venous thrombosis',1),
# MAGIC ('O873','cerebral venous thrombosis',1),
# MAGIC ('G08','cerebral venous thrombosis',0),
# MAGIC ('I676','cerebral venous thrombosis',0),
# MAGIC ('I636','cerebral venous thrombosis',0),
# MAGIC ('D693','thrombocytopenia',0),
# MAGIC ('D694','thrombocytopenia',0),
# MAGIC ('D695','thrombocytopenia',0),
# MAGIC ('D696','thrombocytopenia',0),
# MAGIC ('D65','disseminated intravascular coagulation',0),
# MAGIC ('M311','thrombotic thrombocytopenic purpura',0),
# MAGIC ('K559','mesenteric thrombus',0),
# MAGIC ('K550','mesenteric thrombus',0),
# MAGIC ('I61','intracerebral haemorrhage',0),
# MAGIC ('G951','spinal stroke',0)
# MAGIC AS tab(CODE, EVENT, WOMEN_ONLY)
# COMMAND ----------
# MAGIC %md ## Restrict skinny table
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Create a reduced skinny table with just sex, date_of_birth and date_of_death
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW skinny_distinct AS
# MAGIC SELECT DISTINCT NHS_NUMBER_DEID,
# MAGIC SEX,
# MAGIC DATE_OF_BIRTH,
# MAGIC DATE_OF_DEATH
# MAGIC FROM dars_nic_391419_j3w9t_collab.curr302_patient_skinny_record
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL
# MAGIC AND SEX IS NOT NULL
# MAGIC AND DATE_OF_BIRTH IS NOT NULL
# COMMAND ----------
# MAGIC %md ## Extract all events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Extract all records that contain a relevant event
# MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW all_events AS
# MAGIC --- from HES APC (4 digit codes)
# MAGIC SELECT DISTINCT PERSON_ID_DEID,
# MAGIC YEAR(ADMIDATE) AS YEAR,
# MAGIC ADMIDATE,
# MAGIC DIAG_4_01 AS CODE,
# MAGIC "HES_APC" AS SOURCE
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years
# MAGIC WHERE PERSON_ID_DEID IS NOT NULL
# MAGIC AND ADMIDATE >= '2018-01-01'
# MAGIC AND ADMIDATE <= '2020-12-31'
# MAGIC AND DIAG_4_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4)
# MAGIC --- from HES APC (3 digit codes)
# MAGIC UNION ALL
# MAGIC SELECT DISTINCT PERSON_ID_DEID,
# MAGIC YEAR(ADMIDATE) AS YEAR,
# MAGIC ADMIDATE,
# MAGIC DIAG_3_01 AS CODE,
# MAGIC "HES_APC" AS SOURCE
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years
# MAGIC WHERE PERSON_ID_DEID IS NOT NULL
# MAGIC AND ADMIDATE >= '2018-01-01'
# MAGIC AND ADMIDATE <= '2020-12-31'
# MAGIC AND DIAG_3_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3)
# MAGIC --- from DEATHS (4 digit codes)
# MAGIC UNION ALL
# MAGIC SELECT DISTINCT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS PERSON_ID_DEID,
# MAGIC left(REG_DATE_OF_DEATH,4) AS YEAR,
# MAGIC to_date(REG_DATE_OF_DEATH, 'yyyyMMdd') AS ADMIDATE,
# MAGIC S_UNDERLYING_COD_ICD10 AS CODE,
# MAGIC "DEATHS" AS SOURCE
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t
# MAGIC WHERE DEC_CONF_NHS_NUMBER_CLEAN_DEID IS NOT NULL
# MAGIC AND left(REG_DATE_OF_DEATH,4) >= 2018
# MAGIC AND left(REG_DATE_OF_DEATH,4) <= 2020
# MAGIC AND S_UNDERLYING_COD_ICD10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4)
# MAGIC --- from DEATHS (3 digit codes)
# MAGIC UNION ALL
# MAGIC SELECT DISTINCT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS PERSON_ID_DEID,
# MAGIC left(REG_DATE_OF_DEATH,4) AS YEAR,
# MAGIC to_date(REG_DATE_OF_DEATH, 'yyyyMMdd') AS ADMIDATE,
# MAGIC left(S_UNDERLYING_COD_ICD10,3) AS CODE,
# MAGIC "DEATHS" AS SOURCE
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_deaths_dars_nic_391419_j3w9t
# MAGIC WHERE DEC_CONF_NHS_NUMBER_CLEAN_DEID IS NOT NULL
# MAGIC AND left(REG_DATE_OF_DEATH,4) >= 2018
# MAGIC AND left(REG_DATE_OF_DEATH,4) <= 2020
# MAGIC AND left(S_UNDERLYING_COD_ICD10,3) IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3)
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Add event names to codes
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated AS
# MAGIC SELECT x.*,
# MAGIC y.EVENT,
# MAGIC y.WOMEN_ONLY
# MAGIC FROM global_temp.all_events AS x
# MAGIC LEFT JOIN global_temp.event_codes AS y ON x.CODE = y.CODE
# COMMAND ----------
# MAGIC %md ## Add skinny table information to all events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Add skinny table information to events
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated_skinny AS
# MAGIC SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC ADMIDATE,
# MAGIC CODE,
# MAGIC SOURCE,
# MAGIC EVENT,
# MAGIC ind_death28days,
# MAGIC SEX,
# MAGIC DATE_OF_BIRTH,
# MAGIC DATE_OF_DEATH
# MAGIC FROM(SELECT x.*,
# MAGIC y.SEX,
# MAGIC y.DATE_OF_BIRTH,
# MAGIC y.DATE_OF_DEATH,
# MAGIC CASE WHEN (DATEDIFF(y.DATE_OF_DEATH,x.ADMIDATE)<29) THEN 1 ELSE 0 END AS ind_death28days
# MAGIC FROM global_temp.all_events_annotated AS x
# MAGIC LEFT JOIN global_temp.skinny_distinct AS y on x.PERSON_ID_DEID = y.NHS_NUMBER_DEID)
# MAGIC WHERE ((WOMEN_ONLY=1 AND SEX=2) OR (WOMEN_ONLY=0))
# MAGIC AND SEX IS NOT NULL
# MAGIC AND DATE_OF_BIRTH IS NOT NULL
# COMMAND ----------
# MAGIC %md ## Extract thrombocytopenia events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Create table containing unique non-primary thrombocytopenia events from HES APC
# MAGIC CREATE OR REPLACE GLOBAL TEMPORARY VIEW thrombocytopenia AS
# MAGIC SELECT DISTINCT PERSON_ID_DEID,
# MAGIC ADMIDATE,
# MAGIC "HES_APC" AS SOURCE,
# MAGIC 1 as thrombocytopenia
# MAGIC FROM (SELECT *
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years
# MAGIC WHERE ADMIDATE >= '2018-01-01'
# MAGIC AND ADMIDATE <= '2020-12-31'
# MAGIC AND ((DIAG_4_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_02 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_03 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_04 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_05 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_06 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_07 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_08 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_09 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_11 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_12 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_13 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_14 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_15 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_16 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_17 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_18 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_19 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_4_20 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=4 AND EVENT='thrombocytopenia')))
# MAGIC UNION ALL
# MAGIC SELECT *
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_vac_hes_apc_all_years
# MAGIC WHERE ADMIDATE >= '2018-01-01'
# MAGIC AND ADMIDATE <= '2020-12-31'
# MAGIC AND ((DIAG_3_01 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_02 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_03 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_04 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_05 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_06 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_07 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_08 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_09 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_10 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_11 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_12 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_13 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_14 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_15 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_16 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_17 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_18 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_19 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))
# MAGIC OR (DIAG_3_20 IN (SELECT CODE FROM global_temp.event_codes WHERE length(code)=3 AND EVENT='thrombocytopenia'))))
# MAGIC WHERE PERSON_ID_DEID IS NOT NULL
# MAGIC AND ADMIDATE IS NOT NULL
# COMMAND ----------
# MAGIC %md ## Add thrombocytopenia flag
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Using the skinny table as master: inner join all events, annotate events and define indicators
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW all_events_annotated_skinny_thrombocytopenia AS
# MAGIC SELECT x.*,
# MAGIC CASE WHEN (y.thrombocytopenia=1 AND x.EVENT!='thrombocytopenia' AND x.SOURCE='HES_APC') THEN 1 ELSE 0 END AS ind_thrombocytopenia
# MAGIC FROM global_temp.all_events_annotated_skinny AS x
# MAGIC LEFT JOIN global_temp.thrombocytopenia AS y on x.PERSON_ID_DEID = y.PERSON_ID_DEID AND x.ADMIDATE = y.ADMIDATE AND x.SOURCE = y.SOURCE
# COMMAND ----------
# MAGIC %md ## Determine source record
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Determine for each year which patients have events in HES_APC only, DEATHS only, or both
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW source_record AS
# MAGIC SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC EVENT,
# MAGIC CASE WHEN SUM(HES_APC)>0 AND SUM(DEATHS)>0 THEN 'HES_APC + DEATHS'
# MAGIC WHEN SUM(HES_APC)>0 AND SUM(DEATHS)=0 THEN 'HES_APC only'
# MAGIC WHEN SUM(HES_APC)=0 AND SUM(DEATHS)>0 THEN 'DEATHS only' END RECORD
# MAGIC FROM (SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC SOURCE,
# MAGIC EVENT,
# MAGIC CASE WHEN SOURCE="HES_APC" THEN 1 ELSE 0 END AS HES_APC,
# MAGIC CASE WHEN SOURCE="DEATHS" THEN 1 ELSE 0 END AS DEATHS
# MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia
# MAGIC WHERE PERSON_ID_DEID IS NOT null)
# MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT
# COMMAND ----------
# MAGIC %md ## Determine first events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Select first event from all events
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events AS
# MAGIC SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC EVENT,
# MAGIC "event with thrombocytopenia" AS EVENT_WITH,
# MAGIC min(ADMIDATE) as ADMIDATE,
# MAGIC SEX,
# MAGIC DATE_OF_BIRTH,
# MAGIC DATE_OF_DEATH
# MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia
# MAGIC WHERE ind_thrombocytopenia=1
# MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH
# MAGIC UNION ALL
# MAGIC SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC EVENT,
# MAGIC "event with death in 28 days" AS EVENT_WITH,
# MAGIC min(ADMIDATE) as ADMIDATE,
# MAGIC SEX,
# MAGIC DATE_OF_BIRTH,
# MAGIC DATE_OF_DEATH
# MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia
# MAGIC WHERE ind_death28days=1
# MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH
# MAGIC UNION ALL
# MAGIC SELECT PERSON_ID_DEID,
# MAGIC YEAR,
# MAGIC EVENT,
# MAGIC "event only" AS EVENT_WITH,
# MAGIC min(ADMIDATE) as ADMIDATE,
# MAGIC SEX,
# MAGIC DATE_OF_BIRTH,
# MAGIC DATE_OF_DEATH
# MAGIC FROM global_temp.all_events_annotated_skinny_thrombocytopenia
# MAGIC GROUP BY PERSON_ID_DEID, YEAR, EVENT, EVENT_WITH, SEX, DATE_OF_BIRTH, DATE_OF_DEATH
# COMMAND ----------
# MAGIC %md ## Add record information to first events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Add record information to first events table and determine death within 28 days
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events_source AS
# MAGIC SELECT DISTINCT x.*,
# MAGIC z.RECORD
# MAGIC FROM global_temp.first_events AS x
# MAGIC INNER JOIN global_temp.source_record AS z ON z.PERSON_ID_DEID = x.PERSON_ID_DEID AND z.YEAR = x.YEAR AND z.EVENT = x.EVENT
# COMMAND ----------
# MAGIC %md ## Add age bands to first events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Determine age and assign age bands
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW first_events_source_ageband AS
# MAGIC SELECT *,
# MAGIC CASE WHEN AGE>=0 AND AGE<19 THEN '0-18'
# MAGIC WHEN AGE>=19 AND AGE<31 THEN '19-30'
# MAGIC WHEN AGE>=31 AND AGE<40 THEN '31-39'
# MAGIC WHEN AGE>=40 AND AGE<50 THEN '40-49'
# MAGIC WHEN AGE>=50 AND AGE<60 THEN '50-59'
# MAGIC WHEN AGE>=60 AND AGE<70 THEN '60-69'
# MAGIC WHEN AGE>=70 AND AGE<80 THEN '70-79'
# MAGIC WHEN AGE>=80 AND AGE<90 THEN '80-89'
# MAGIC WHEN AGE>=90 AND AGE<116 THEN '90+'
# MAGIC WHEN AGE>=116 THEN null END AGE_BAND
# MAGIC FROM (SELECT PERSON_ID_DEID,
# MAGIC SEX,
# MAGIC YEAR,
# MAGIC RECORD,
# MAGIC EVENT,
# MAGIC EVENT_WITH,
# MAGIC (DATEDIFF(ADMIDATE, DATE_OF_BIRTH)/365.25) AS AGE
# MAGIC FROM global_temp.first_events_source)
# COMMAND ----------
# MAGIC %md ## Count number of first events
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Count number of patients in each sex/year/event/age_band/record combination
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_vacc_event_counts AS
# MAGIC SELECT YEAR,
# MAGIC CASE WHEN SEX=1 THEN 'Men'
# MAGIC WHEN SEX=2 THEN 'Women' END SEX,
# MAGIC RECORD,
# MAGIC EVENT,
# MAGIC EVENT_WITH,
# MAGIC AGE_BAND,
# MAGIC COUNT(PERSON_ID_DEID) AS N
# MAGIC FROM global_temp.first_events_source_ageband
# MAGIC GROUP BY YEAR, SEX, RECORD, EVENT, EVENT_WITH, AGE_BAND
# COMMAND ----------
# MAGIC %md ## Export table
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Export cell
# MAGIC SELECT *
# MAGIC FROM global_temp.ccu002_vacc_event_counts
# COMMAND ----------
# MAGIC %md ## Save table
# COMMAND ----------
# Save table
drop_table('ccu002_vacc_event_counts')
create_table('ccu002_vacc_event_counts')
| def create_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', select_sql_script: str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database."""
spark.conf.set('spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation', 'true')
if select_sql_script is None:
select_sql_script = f'SELECT * FROM global_temp.{table_name}'
spark.sql(f'CREATE TABLE {database_name}.{table_name} AS\n {select_sql_script}\n ')
spark.sql(f'ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}')
def drop_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', if_exists=True):
if if_exists:
if_exists = 'IF EXISTS'
else:
if_exists = ''
spark.sql(f'DROP TABLE {IF_EXISTS} {database_name}.{table_name}')
drop_table('ccu002_vacc_event_counts')
create_table('ccu002_vacc_event_counts') |
"""
Q1 Program to find max from 5 numbers
"""
'''
#way1
max = 0
list = [100,20,15,500,5]
for i in range (0,5):
if max < list[i]:
max =list[i]
print('Max no out of list is',max)
'''
#while list[0] == list[-1]: # list[-1] helps you get the last element of the list
'''
#Way 2
max = 0
list = [100, 20, 15, 500, 5]
i = 0
while i < len(list):
if max < list[i]:
max = list[i]
i=i+1
print('Max no out of list is', max)
'''
"""
Q2write a code to find minimum number from 5 values
"""
"""
list_min = [20, 45, 15, 10, 90, 200, 56, 5]
length = len(list_min)
minimum = list_min[1]
for i in range(0, length):
if minimum > list_min[i]:
minimum = list_min[i]
print(i,minimum)
print("Min no in the list is",minimum)
"""
"""
creating pattern no 4
"""
"""
for i in range(0, 6):
print(" ")
symbol = i % 2
print(symbol, end=" ")
for j in range(0, i):
if symbol == 1:
symbol = 0
print(symbol, end=" ")
else:
symbol = 1
print(symbol, end=" ")
"""
"""
Q5 pattern
"""
"""
for i in range(0, 6):
print(" ")
symbol = 1
print(symbol, end=" ")
for j in range(0, i):
if symbol==1:
symbol=0
print(symbol, end=" " )
else:
symbol=1
print(symbol, end=" " )
"""
"""
Q6 pattern
"""
"""
for i in range(0,5):
print(" ")
for j in range(1,6):
print(j, end=" ")
"""
"""
Q7 Pattern
"""
"""
count = 1
for i in range(0, 5):
print(" ")
for j in range(0, 5):
print("%02d" % count, end=" ")
count += 1
"""
"""
Q8 Pattern
"""
for i in range(5,0,-1):
symbol = i%2
print(" ")
print(symbol, end=" ")
for j in range(1, i):
if symbol == 1:
symbol = 0
print(symbol, end=" ")
else:
symbol = 1
print(symbol, end=" ")
| """
Q1 Program to find max from 5 numbers
"""
"\n#way1\nmax = 0\nlist = [100,20,15,500,5]\nfor i in range (0,5):\n if max < list[i]:\n max =list[i]\nprint('Max no out of list is',max)\n"
"\n#Way 2\nmax = 0\nlist = [100, 20, 15, 500, 5]\ni = 0\nwhile i < len(list):\n if max < list[i]:\n max = list[i]\n i=i+1\nprint('Max no out of list is', max)\n"
'\nQ2write a code to find minimum number from 5 values\n'
'\nlist_min = [20, 45, 15, 10, 90, 200, 56, 5]\nlength = len(list_min)\nminimum = list_min[1]\nfor i in range(0, length):\n if minimum > list_min[i]:\n minimum = list_min[i]\n print(i,minimum)\nprint("Min no in the list is",minimum)\n'
'\ncreating pattern no 4\n'
'\nfor i in range(0, 6):\n print(" ")\n symbol = i % 2\n print(symbol, end=" ")\n for j in range(0, i):\n if symbol == 1:\n symbol = 0\n print(symbol, end=" ")\n else:\n symbol = 1\n print(symbol, end=" ")\n'
'\nQ5 pattern\n'
'\nfor i in range(0, 6):\n print(" ")\n symbol = 1\n print(symbol, end=" ")\n for j in range(0, i):\n if symbol==1:\n symbol=0\n print(symbol, end=" " )\n else:\n symbol=1\n print(symbol, end=" " )\n'
'\nQ6 pattern\n'
'\nfor i in range(0,5):\n print(" ")\n for j in range(1,6):\n print(j, end=" ")\n'
'\nQ7 Pattern\n'
'\ncount = 1\nfor i in range(0, 5):\n print(" ")\n for j in range(0, 5):\n print("%02d" % count, end=" ")\n count += 1\n'
'\nQ8 Pattern\n'
for i in range(5, 0, -1):
symbol = i % 2
print(' ')
print(symbol, end=' ')
for j in range(1, i):
if symbol == 1:
symbol = 0
print(symbol, end=' ')
else:
symbol = 1
print(symbol, end=' ') |
# 200090310
sm.warp(200000141, 0)
sm.dispose()
| sm.warp(200000141, 0)
sm.dispose() |
'''
1) Implement the Node class to create
a binary search tree. The constructor
should initialize values 'data', 'left',
and 'right'.
2) Implement the 'insert' method for the
Node class. Insert should accept an argument
'data', then create a new node at the appropriate
location in the tree.
3) Implement the 'contains' method for the Node
class. Contains should accept a 'data' argument
and return the Node in the tree with the same value.
'''
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(self, data):
if data == self.data:
raise NotImplemented
elif data < self.data and self.left is None:
self.left = Node(data)
elif data > self.data and self.right is None:
self.right = Node(data)
elif data < self.data:
self.left.insert(data)
elif data > self.data:
self.right.insert(data)
else:
raise Exception('Unexpected edge case')
def contains(self, data):
if data == self.data:
return self
elif data < self.data and self.left is not None:
return self.left.contains(data)
elif data > self.data and self.right is not None:
return self.right.contains(data)
return None
| """
1) Implement the Node class to create
a binary search tree. The constructor
should initialize values 'data', 'left',
and 'right'.
2) Implement the 'insert' method for the
Node class. Insert should accept an argument
'data', then create a new node at the appropriate
location in the tree.
3) Implement the 'contains' method for the Node
class. Contains should accept a 'data' argument
and return the Node in the tree with the same value.
"""
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(self, data):
if data == self.data:
raise NotImplemented
elif data < self.data and self.left is None:
self.left = node(data)
elif data > self.data and self.right is None:
self.right = node(data)
elif data < self.data:
self.left.insert(data)
elif data > self.data:
self.right.insert(data)
else:
raise exception('Unexpected edge case')
def contains(self, data):
if data == self.data:
return self
elif data < self.data and self.left is not None:
return self.left.contains(data)
elif data > self.data and self.right is not None:
return self.right.contains(data)
return None |
NO_SUCH_OPTION_ERROR_TEMPLATE = "Error: no such option: {}"
NO_SUCH_COMMAND_ERROR_TEMPLATE = "Error: No such command \"{}\""
MISSING_COMMAND_ERROR_TEMPLATE = "Error: Missing command."
| no_such_option_error_template = 'Error: no such option: {}'
no_such_command_error_template = 'Error: No such command "{}"'
missing_command_error_template = 'Error: Missing command.' |
property_value_alias_age_long_to_short = {
"Unassigned": "NA",
"V10_0": "10.0",
"V11_0": "11.0",
"V12_0": "12.0",
"V12_1": "12.1",
"V13_0": "13.0",
"V1_1": "1.1",
"V2_0": "2.0",
"V2_1": "2.1",
"V3_0": "3.0",
"V3_1": "3.1",
"V3_2": "3.2",
"V4_0": "4.0",
"V4_1": "4.1",
"V5_0": "5.0",
"V5_1": "5.1",
"V5_2": "5.2",
"V6_0": "6.0",
"V6_1": "6.1",
"V6_2": "6.2",
"V6_3": "6.3",
"V7_0": "7.0",
"V8_0": "8.0",
"V9_0": "9.0",
}
| property_value_alias_age_long_to_short = {'Unassigned': 'NA', 'V10_0': '10.0', 'V11_0': '11.0', 'V12_0': '12.0', 'V12_1': '12.1', 'V13_0': '13.0', 'V1_1': '1.1', 'V2_0': '2.0', 'V2_1': '2.1', 'V3_0': '3.0', 'V3_1': '3.1', 'V3_2': '3.2', 'V4_0': '4.0', 'V4_1': '4.1', 'V5_0': '5.0', 'V5_1': '5.1', 'V5_2': '5.2', 'V6_0': '6.0', 'V6_1': '6.1', 'V6_2': '6.2', 'V6_3': '6.3', 'V7_0': '7.0', 'V8_0': '8.0', 'V9_0': '9.0'} |
""" The BaseGem class is the framework for all gems and fusions.
Base Gem holds all the stats of a gem or fusion in a dict, this dict is
modified through helper funcitons, these functions also return the end value.
Eventually we might keep ability functions here as well. We are still
utilizing child classes.
"""
class BaseGem():
def __init__(self): # add weapon size, possible abilities
self.__attributes = dict(
serial=None,
stone=None,
era=None,
health=36,
size=1,
movement_speed=8,
flight_movement_speed=0,
arms=2,
caste_rank=None,
action_slots=2,
PP=31,
SPR=0,
homo=False,
hetro=False,
CPR=0,
attacking=False,
blocking=False,
disarming=False,
onePR=0,
twoPR=0,
threePR=0,
certs=[]
)
#
#
# ~~~~~~~~~~~~~~~HELPER CLASSES FOR ACCESSING AND MODIFYING STATS~~~~~~~~~~~~~~
def set_serial(self, new_serial=None):
if new_serial is not None:
self.__attributes['serial'] = new_serial
return self.__attributes['serial']
def set_stone(self, new_stone=None):
if new_stone is not None:
self.__attributes['stone'] = new_stone
return self.__attributes['stone']
def set_era(self, new_era=None):
if new_era is not None:
self.__attributes['era'] = new_era
return self.__attributes['era']
def add_health(self, health_mod=None):
if health_mod is not None:
self.__attributes['health'] += health_mod
return self.__attributes['health']
# size should probably always be powers of 2
# this also modifies movement_speed
def set_size(self, new_size=None):
if new_size is not None:
self.__attributes['size'] = new_size
self.__attributes['movemen_speed'] = new_size * 8
return self.__attributes['size']
def get_movement_speed(self):
return self.__attributes['movement_speed']
def add_flight_movement_speed(self, f_movement_speed_mod=None):
if f_movement_speed_mod is not None:
self.__attributes['flight_movement_speed'] += f_movement_speed_mod
return self.__attributes['flight_movement_speed']
def add_arms(self, arms_mod=None):
if arms_mod is not None:
self.__attributes['arms'] += arms_mod
return self.__attributes['arms']
def add_caste_rank(self, caste_rank_mod=None):
if caste_rank_mod is not None:
self.__attributes['caste_rank'] += caste_rank_mod
return self.__attributes['caste_rank']
def add_action_slots(self, action_slots_mod=None):
if action_slots_mod is not None:
self.__attributes['action_slots'] += action_slots_mod
return self.__attributes['action_slots']
def add_PP(self, PP_mod=None):
if PP_mod is not None:
self.__attributes['PP'] += PP_mod
return self.__attributes['PP']
def add_SPR(self, SPR_mod=None):
if SPR_mod is not None:
self.__attributes['SPR'] += SPR_mod
return self.__attributes['SPR']
def set_homo(self, new_homo=None):
if new_homo is not None:
self.__attributes['homo'] = new_homo
return self.__attributes['homo']
def set_hetro(self, new_hetro=None):
if new_hetro is not None:
self.__attributes['hetro'] = new_hetro
return self.__attributes['hetro']
def add_CPR(self, CPR_mod=None):
if CPR_mod is not None:
self.__attributes['CPR'] += CPR_mod
return self.__attributes['CPR']
def set_attacking(self, new_attacking=None):
if new_attacking is not None:
self.__attributes['attacking'] = new_attacking
return self.__attributes['attacking']
def set_blocking(self, new_blocking=None):
if new_blocking is not None:
self.__attributes['blocking'] = new_blocking
return self.__attributes['blocking']
def set_disarming(self, new_disarming=None):
if new_disarming is not None:
self.__attributes['disarming'] = new_disarming
return self.__attributes['disarming']
def add_onePR(self, onePR_mod=None):
if onePR_mod is not None:
self.__attributes['onePR'] += onePR_mod
return self.__attributes['onePR']
def add_twoPR(self, twoPR_mod=None):
if twoPR_mod is not None:
self.__attributes['twoPR'] += twoPR_mod
return self.__attributes['twoPR']
def add_threePR(self, threePR_mod=None):
if threePR_mod is not None:
self.__attributes['threePR'] += threePR_mod
return self.__attributes['threePR']
def add_cert(self, new_cert=None):
if new_cert is not None:
self.__attributes['certs'].append(new_cert)
return self.__attributes['certs']
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~END OF HELPER CLASSES~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#
| """ The BaseGem class is the framework for all gems and fusions.
Base Gem holds all the stats of a gem or fusion in a dict, this dict is
modified through helper funcitons, these functions also return the end value.
Eventually we might keep ability functions here as well. We are still
utilizing child classes.
"""
class Basegem:
def __init__(self):
self.__attributes = dict(serial=None, stone=None, era=None, health=36, size=1, movement_speed=8, flight_movement_speed=0, arms=2, caste_rank=None, action_slots=2, PP=31, SPR=0, homo=False, hetro=False, CPR=0, attacking=False, blocking=False, disarming=False, onePR=0, twoPR=0, threePR=0, certs=[])
def set_serial(self, new_serial=None):
if new_serial is not None:
self.__attributes['serial'] = new_serial
return self.__attributes['serial']
def set_stone(self, new_stone=None):
if new_stone is not None:
self.__attributes['stone'] = new_stone
return self.__attributes['stone']
def set_era(self, new_era=None):
if new_era is not None:
self.__attributes['era'] = new_era
return self.__attributes['era']
def add_health(self, health_mod=None):
if health_mod is not None:
self.__attributes['health'] += health_mod
return self.__attributes['health']
def set_size(self, new_size=None):
if new_size is not None:
self.__attributes['size'] = new_size
self.__attributes['movemen_speed'] = new_size * 8
return self.__attributes['size']
def get_movement_speed(self):
return self.__attributes['movement_speed']
def add_flight_movement_speed(self, f_movement_speed_mod=None):
if f_movement_speed_mod is not None:
self.__attributes['flight_movement_speed'] += f_movement_speed_mod
return self.__attributes['flight_movement_speed']
def add_arms(self, arms_mod=None):
if arms_mod is not None:
self.__attributes['arms'] += arms_mod
return self.__attributes['arms']
def add_caste_rank(self, caste_rank_mod=None):
if caste_rank_mod is not None:
self.__attributes['caste_rank'] += caste_rank_mod
return self.__attributes['caste_rank']
def add_action_slots(self, action_slots_mod=None):
if action_slots_mod is not None:
self.__attributes['action_slots'] += action_slots_mod
return self.__attributes['action_slots']
def add_pp(self, PP_mod=None):
if PP_mod is not None:
self.__attributes['PP'] += PP_mod
return self.__attributes['PP']
def add_spr(self, SPR_mod=None):
if SPR_mod is not None:
self.__attributes['SPR'] += SPR_mod
return self.__attributes['SPR']
def set_homo(self, new_homo=None):
if new_homo is not None:
self.__attributes['homo'] = new_homo
return self.__attributes['homo']
def set_hetro(self, new_hetro=None):
if new_hetro is not None:
self.__attributes['hetro'] = new_hetro
return self.__attributes['hetro']
def add_cpr(self, CPR_mod=None):
if CPR_mod is not None:
self.__attributes['CPR'] += CPR_mod
return self.__attributes['CPR']
def set_attacking(self, new_attacking=None):
if new_attacking is not None:
self.__attributes['attacking'] = new_attacking
return self.__attributes['attacking']
def set_blocking(self, new_blocking=None):
if new_blocking is not None:
self.__attributes['blocking'] = new_blocking
return self.__attributes['blocking']
def set_disarming(self, new_disarming=None):
if new_disarming is not None:
self.__attributes['disarming'] = new_disarming
return self.__attributes['disarming']
def add_one_pr(self, onePR_mod=None):
if onePR_mod is not None:
self.__attributes['onePR'] += onePR_mod
return self.__attributes['onePR']
def add_two_pr(self, twoPR_mod=None):
if twoPR_mod is not None:
self.__attributes['twoPR'] += twoPR_mod
return self.__attributes['twoPR']
def add_three_pr(self, threePR_mod=None):
if threePR_mod is not None:
self.__attributes['threePR'] += threePR_mod
return self.__attributes['threePR']
def add_cert(self, new_cert=None):
if new_cert is not None:
self.__attributes['certs'].append(new_cert)
return self.__attributes['certs'] |
def fib(num):
output = [1,1]
before_previous_num = 1
previous_num = 1
for i in range(1,num+1):
new_num = before_previous_num + previous_num
output.append(new_num)
before_previous_num = previous_num
previous_num = new_num
nth = output[num-1]
return nth
'''
Powers of 2 for some reason :X
output = []
i = 0
last_num = 0
new_num = 1
while i < 10:
last_num = new_num
new_num = last_num+new_num
output.append(new_num)
i+=1
print(output)
'''
| def fib(num):
output = [1, 1]
before_previous_num = 1
previous_num = 1
for i in range(1, num + 1):
new_num = before_previous_num + previous_num
output.append(new_num)
before_previous_num = previous_num
previous_num = new_num
nth = output[num - 1]
return nth
'\nPowers of 2 for some reason :X\n\noutput = []\ni = 0\nlast_num = 0\nnew_num = 1\nwhile i < 10:\n last_num = new_num\n new_num = last_num+new_num\n output.append(new_num)\n i+=1\nprint(output)\n' |
class Score:
def __init__(self):
self.score = 0
def get_score_text(self):
score_text = f"Score: {self.score}"
return score_text
def add_score(self, points):
self.score += points
| class Score:
def __init__(self):
self.score = 0
def get_score_text(self):
score_text = f'Score: {self.score}'
return score_text
def add_score(self, points):
self.score += points |
# -*- coding: utf-8 -*-
""" Default Constants Used for the Australian Senate Election Audit. """
# The modes in which to run the senate election audit.
SIMULATION_MODE = 'simulation'
QUICK_MODE = 'quick'
REAL_MODE = 'real'
# The Australian states with senate election data available to audit.
STATES = [
'ACT',
'NSW',
'NT',
'QLD',
'SA',
'TAS',
'VIC',
'WA',
]
# The default number of cast ballots in a simulated senate election audit.
DEFAULT_SIMULATED_SENATE_ELECTION_NUM_BALLOTS = 1000000
# The default number of candidates in a simulated senate election audit.
DEFAULT_SIMULATED_SENATE_ELECTION_NUM_CANDIDATES = 100
# The default upper bound on the fraction of trials a candidate must lose in a round of an audit to be considered
# unpopular.
DEFAULT_UNPOPULAR_FREQUENCY_THRESHOLD = 0.03
# The default number of ballots to add to a growing sample at the start of an audit stage.
DEFAULT_SAMPLE_INCREMENT_SIZE = 1000
# The default random number seed value.
DEFAULT_SEED_VALUE = 1
# The number of header lines in a formal preferences CSV file.
FORMAL_PREFERENCES_CSV_NUM_HEADER_LINES = 2
# The keys of the audit configuration JSON.
AUDIT_STAGE_KEY = 'audit_stage'
SAMPLE_SIZE_KEY = 'sample_size'
# The default file name for the election configuration file.
CONFIG_FILE_PATH = 'aec_fed2016.json'
# The names of files created by the aus-senate-audit software.
AUDIT_DIR_NAME = 'audit_{}_seed_{}'
ROUND_DIR_NAME = 'stages'
AUDIT_INFO_FILE_NAME = 'info.json'
AUDIT_ROUND_FILE_NAME = '{}/stage_{}.csv'
AGGREGATE_BALLOTS_FILE_NAME = 'aggregate.csv'
SELECTED_BALLOTS_FILE_NAME = 'selected_ballots.csv'
RESULT_OUTPUT = '{}_result.txt'
# The column headers of a formal preferences file (first header line).
COLUMN_HEADERS = [
'ElectorateNm',
'VoteCollectionPointNm',
'VoteCollectionPointId',
'BatchNo',
'PaperNo',
'Preferences',
]
# The column header delimiters of a formal preferences file (second header line).
COLUMN_HEADER_DELIMS = [
'------------',
'---------------------',
'---------------------',
'-------',
'-------',
'-----------',
]
# The column headers used to track preference matches between electronic ballots and paper ballot interpretations.
MATCH_HEADERS = [
'Match',
'PreferencesAfterAudit',
]
| """ Default Constants Used for the Australian Senate Election Audit. """
simulation_mode = 'simulation'
quick_mode = 'quick'
real_mode = 'real'
states = ['ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA']
default_simulated_senate_election_num_ballots = 1000000
default_simulated_senate_election_num_candidates = 100
default_unpopular_frequency_threshold = 0.03
default_sample_increment_size = 1000
default_seed_value = 1
formal_preferences_csv_num_header_lines = 2
audit_stage_key = 'audit_stage'
sample_size_key = 'sample_size'
config_file_path = 'aec_fed2016.json'
audit_dir_name = 'audit_{}_seed_{}'
round_dir_name = 'stages'
audit_info_file_name = 'info.json'
audit_round_file_name = '{}/stage_{}.csv'
aggregate_ballots_file_name = 'aggregate.csv'
selected_ballots_file_name = 'selected_ballots.csv'
result_output = '{}_result.txt'
column_headers = ['ElectorateNm', 'VoteCollectionPointNm', 'VoteCollectionPointId', 'BatchNo', 'PaperNo', 'Preferences']
column_header_delims = ['------------', '---------------------', '---------------------', '-------', '-------', '-----------']
match_headers = ['Match', 'PreferencesAfterAudit'] |
data = (
'k', # 0x00
'kh', # 0x01
'g', # 0x02
'gh', # 0x03
'ng', # 0x04
'c', # 0x05
'ch', # 0x06
'j', # 0x07
'jh', # 0x08
'ny', # 0x09
'nny', # 0x0a
'tt', # 0x0b
'tth', # 0x0c
'dd', # 0x0d
'ddh', # 0x0e
'nn', # 0x0f
'tt', # 0x10
'th', # 0x11
'd', # 0x12
'dh', # 0x13
'n', # 0x14
'p', # 0x15
'ph', # 0x16
'b', # 0x17
'bh', # 0x18
'm', # 0x19
'y', # 0x1a
'r', # 0x1b
'l', # 0x1c
'w', # 0x1d
's', # 0x1e
'h', # 0x1f
'll', # 0x20
'a', # 0x21
'[?]', # 0x22
'i', # 0x23
'ii', # 0x24
'u', # 0x25
'uu', # 0x26
'e', # 0x27
'[?]', # 0x28
'o', # 0x29
'au', # 0x2a
'[?]', # 0x2b
'aa', # 0x2c
'i', # 0x2d
'ii', # 0x2e
'u', # 0x2f
'uu', # 0x30
'e', # 0x31
'ai', # 0x32
'[?]', # 0x33
'[?]', # 0x34
'[?]', # 0x35
'N', # 0x36
'\'', # 0x37
':', # 0x38
'', # 0x39
'[?]', # 0x3a
'[?]', # 0x3b
'[?]', # 0x3c
'[?]', # 0x3d
'[?]', # 0x3e
'[?]', # 0x3f
'0', # 0x40
'1', # 0x41
'2', # 0x42
'3', # 0x43
'4', # 0x44
'5', # 0x45
'6', # 0x46
'7', # 0x47
'8', # 0x48
'9', # 0x49
' / ', # 0x4a
' // ', # 0x4b
'n*', # 0x4c
'r*', # 0x4d
'l*', # 0x4e
'e*', # 0x4f
'sh', # 0x50
'ss', # 0x51
'R', # 0x52
'RR', # 0x53
'L', # 0x54
'LL', # 0x55
'R', # 0x56
'RR', # 0x57
'L', # 0x58
'LL', # 0x59
'[?]', # 0x5a
'[?]', # 0x5b
'[?]', # 0x5c
'[?]', # 0x5d
'[?]', # 0x5e
'[?]', # 0x5f
'[?]', # 0x60
'[?]', # 0x61
'[?]', # 0x62
'[?]', # 0x63
'[?]', # 0x64
'[?]', # 0x65
'[?]', # 0x66
'[?]', # 0x67
'[?]', # 0x68
'[?]', # 0x69
'[?]', # 0x6a
'[?]', # 0x6b
'[?]', # 0x6c
'[?]', # 0x6d
'[?]', # 0x6e
'[?]', # 0x6f
'[?]', # 0x70
'[?]', # 0x71
'[?]', # 0x72
'[?]', # 0x73
'[?]', # 0x74
'[?]', # 0x75
'[?]', # 0x76
'[?]', # 0x77
'[?]', # 0x78
'[?]', # 0x79
'[?]', # 0x7a
'[?]', # 0x7b
'[?]', # 0x7c
'[?]', # 0x7d
'[?]', # 0x7e
'[?]', # 0x7f
'[?]', # 0x80
'[?]', # 0x81
'[?]', # 0x82
'[?]', # 0x83
'[?]', # 0x84
'[?]', # 0x85
'[?]', # 0x86
'[?]', # 0x87
'[?]', # 0x88
'[?]', # 0x89
'[?]', # 0x8a
'[?]', # 0x8b
'[?]', # 0x8c
'[?]', # 0x8d
'[?]', # 0x8e
'[?]', # 0x8f
'[?]', # 0x90
'[?]', # 0x91
'[?]', # 0x92
'[?]', # 0x93
'[?]', # 0x94
'[?]', # 0x95
'[?]', # 0x96
'[?]', # 0x97
'[?]', # 0x98
'[?]', # 0x99
'[?]', # 0x9a
'[?]', # 0x9b
'[?]', # 0x9c
'[?]', # 0x9d
'[?]', # 0x9e
'[?]', # 0x9f
'A', # 0xa0
'B', # 0xa1
'G', # 0xa2
'D', # 0xa3
'E', # 0xa4
'V', # 0xa5
'Z', # 0xa6
'T`', # 0xa7
'I', # 0xa8
'K', # 0xa9
'L', # 0xaa
'M', # 0xab
'N', # 0xac
'O', # 0xad
'P', # 0xae
'Zh', # 0xaf
'R', # 0xb0
'S', # 0xb1
'T', # 0xb2
'U', # 0xb3
'P`', # 0xb4
'K`', # 0xb5
'G\'', # 0xb6
'Q', # 0xb7
'Sh', # 0xb8
'Ch`', # 0xb9
'C`', # 0xba
'Z\'', # 0xbb
'C', # 0xbc
'Ch', # 0xbd
'X', # 0xbe
'J', # 0xbf
'H', # 0xc0
'E', # 0xc1
'Y', # 0xc2
'W', # 0xc3
'Xh', # 0xc4
'OE', # 0xc5
'[?]', # 0xc6
'[?]', # 0xc7
'[?]', # 0xc8
'[?]', # 0xc9
'[?]', # 0xca
'[?]', # 0xcb
'[?]', # 0xcc
'[?]', # 0xcd
'[?]', # 0xce
'[?]', # 0xcf
'a', # 0xd0
'b', # 0xd1
'g', # 0xd2
'd', # 0xd3
'e', # 0xd4
'v', # 0xd5
'z', # 0xd6
't`', # 0xd7
'i', # 0xd8
'k', # 0xd9
'l', # 0xda
'm', # 0xdb
'n', # 0xdc
'o', # 0xdd
'p', # 0xde
'zh', # 0xdf
'r', # 0xe0
's', # 0xe1
't', # 0xe2
'u', # 0xe3
'p`', # 0xe4
'k`', # 0xe5
'g\'', # 0xe6
'q', # 0xe7
'sh', # 0xe8
'ch`', # 0xe9
'c`', # 0xea
'z\'', # 0xeb
'c', # 0xec
'ch', # 0xed
'x', # 0xee
'j', # 0xef
'h', # 0xf0
'e', # 0xf1
'y', # 0xf2
'w', # 0xf3
'xh', # 0xf4
'oe', # 0xf5
'f', # 0xf6
'[?]', # 0xf7
'[?]', # 0xf8
'[?]', # 0xf9
'[?]', # 0xfa
' // ', # 0xfb
'[?]', # 0xfc
'[?]', # 0xfd
'[?]', # 0xfe
)
| data = ('k', 'kh', 'g', 'gh', 'ng', 'c', 'ch', 'j', 'jh', 'ny', 'nny', 'tt', 'tth', 'dd', 'ddh', 'nn', 'tt', 'th', 'd', 'dh', 'n', 'p', 'ph', 'b', 'bh', 'm', 'y', 'r', 'l', 'w', 's', 'h', 'll', 'a', '[?]', 'i', 'ii', 'u', 'uu', 'e', '[?]', 'o', 'au', '[?]', 'aa', 'i', 'ii', 'u', 'uu', 'e', 'ai', '[?]', '[?]', '[?]', 'N', "'", ':', '', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' / ', ' // ', 'n*', 'r*', 'l*', 'e*', 'sh', 'ss', 'R', 'RR', 'L', 'LL', 'R', 'RR', 'L', 'LL', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', 'A', 'B', 'G', 'D', 'E', 'V', 'Z', 'T`', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Zh', 'R', 'S', 'T', 'U', 'P`', 'K`', "G'", 'Q', 'Sh', 'Ch`', 'C`', "Z'", 'C', 'Ch', 'X', 'J', 'H', 'E', 'Y', 'W', 'Xh', 'OE', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', '[?]', 'a', 'b', 'g', 'd', 'e', 'v', 'z', 't`', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'zh', 'r', 's', 't', 'u', 'p`', 'k`', "g'", 'q', 'sh', 'ch`', 'c`', "z'", 'c', 'ch', 'x', 'j', 'h', 'e', 'y', 'w', 'xh', 'oe', 'f', '[?]', '[?]', '[?]', '[?]', ' // ', '[?]', '[?]', '[?]') |
def user_url():
"""this fuction is used to take the username as input,
then generate the profile url
Returns:
[string] -- [profile url]
"""
username = input("enter the username - ")
url = "https://www.instagram.com/{}/".format(username)
return url | def user_url():
"""this fuction is used to take the username as input,
then generate the profile url
Returns:
[string] -- [profile url]
"""
username = input('enter the username - ')
url = 'https://www.instagram.com/{}/'.format(username)
return url |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def helper(ans, res, nums):
if not nums:
ans.append(res[:])
else:
element = nums.pop()
helper(ans, res, nums)
res.append(element)
helper(ans, res, nums)
res.pop()
nums.append(element)
return ans
return helper([], [], nums)
| class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def helper(ans, res, nums):
if not nums:
ans.append(res[:])
else:
element = nums.pop()
helper(ans, res, nums)
res.append(element)
helper(ans, res, nums)
res.pop()
nums.append(element)
return ans
return helper([], [], nums) |
#!/usr/bin/env python3
# imports go here
#
# Free Coding session for 2015-03-31
# Written by Matt Warren
#
def foo():
print("completely out of ideas")
if __name__ == "__main__":
foo()
| def foo():
print('completely out of ideas')
if __name__ == '__main__':
foo() |
"""Advent of Code Day 13 - Packet Scanners"""
def severity(layers, delay):
"""Calculate cost of getting caught when traversing a Firewall."""
layers_list = layers.strip().split('\n')
severity = 0
for layer in layers_list:
layer_parts = (str(layer).split(':'))
layer_num = int(layer_parts[0])
layer_range = int(str(layer_parts[1]).strip())
if (layer_num + delay) % ((layer_range - 1) * 2) == 0:
severity += layer_num * layer_range
if layer_num == 0:
severity += 1 # Prevents being caught on 0 not counting
if delay == 0:
print('Bypassing with no delay results in overall severity of '
+ str(severity - 1))
if severity == 0:
return delay
with open('inputs/day_13.txt') as f:
firewall = f.read()
delay = 0
while severity(firewall, delay) is None:
delay += 1
# Answer One
print('The smallest delay that would bypass the firewall is:', delay, 'picoseconds.')
| """Advent of Code Day 13 - Packet Scanners"""
def severity(layers, delay):
"""Calculate cost of getting caught when traversing a Firewall."""
layers_list = layers.strip().split('\n')
severity = 0
for layer in layers_list:
layer_parts = str(layer).split(':')
layer_num = int(layer_parts[0])
layer_range = int(str(layer_parts[1]).strip())
if (layer_num + delay) % ((layer_range - 1) * 2) == 0:
severity += layer_num * layer_range
if layer_num == 0:
severity += 1
if delay == 0:
print('Bypassing with no delay results in overall severity of ' + str(severity - 1))
if severity == 0:
return delay
with open('inputs/day_13.txt') as f:
firewall = f.read()
delay = 0
while severity(firewall, delay) is None:
delay += 1
print('The smallest delay that would bypass the firewall is:', delay, 'picoseconds.') |
# see https://www.codewars.com/kata/5ba38ba180824a86850000f7/solutions/python
def solve(arr):
i = 0
while i < len(arr):
if arr.count(arr[i]) > 1:
arr.pop(i)
else:
i+= 1
return arr
print(solve([3,4,4,3,6,3]) == [4,6,3])
print(solve([1,2,1,2,1,2,3]) == [1,2,3])
print(solve([1,2,3,4]) == [1,2,3,4])
print(solve([1,1,4,5,1,2,1]) == [4,5,2,1])
| def solve(arr):
i = 0
while i < len(arr):
if arr.count(arr[i]) > 1:
arr.pop(i)
else:
i += 1
return arr
print(solve([3, 4, 4, 3, 6, 3]) == [4, 6, 3])
print(solve([1, 2, 1, 2, 1, 2, 3]) == [1, 2, 3])
print(solve([1, 2, 3, 4]) == [1, 2, 3, 4])
print(solve([1, 1, 4, 5, 1, 2, 1]) == [4, 5, 2, 1]) |
"""Given two numbers and an arithmetic operator (the name of it, as a string),
return the result of the two numbers having that operator used on them.
a and b will both be positive integers, and a will always be the first number in the operation,
and b always the second.
The four operators are "add", "subtract", "divide", "multiply".
A few examples:
arithmetic(5, 2, "add") => returns 7
arithmetic(5, 2, "subtract") => returns 3
arithmetic(5, 2, "multiply") => returns 10
arithmetic(5, 2, "divide") => returns 2.5
ArithmeticFunction.arithmetic(5, 2, "add") => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2
Try to do it without using if statements!"""
def add( num1,num2):
return num1+num2
def subtract( num1,num2):
return num1-num2
def multiply ( num1,num2):
return num1 * num2
def divide (num1,num2):
return num1 / num2
def arithmetic( num1,num2,function):
if ( function == "add"):
return add(num1,num2)
if ( function == "subtract"):
return subtract(num1,num2)
if ( function == "multiply"):
return multiply(num1,num2)
if ( function == "divide"):
return divide(num1,num2)
#RW 28/05/2021
"""def arithmetic(a, b, operator):
return {
'add': a + b,
'subtract': a - b,
'multiply': a * b,
'divide': a / b,
}[operator]
#Gives error Ex: on 1,0,'add'
#But very clever
""" | """Given two numbers and an arithmetic operator (the name of it, as a string),
return the result of the two numbers having that operator used on them.
a and b will both be positive integers, and a will always be the first number in the operation,
and b always the second.
The four operators are "add", "subtract", "divide", "multiply".
A few examples:
arithmetic(5, 2, "add") => returns 7
arithmetic(5, 2, "subtract") => returns 3
arithmetic(5, 2, "multiply") => returns 10
arithmetic(5, 2, "divide") => returns 2.5
ArithmeticFunction.arithmetic(5, 2, "add") => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2
Try to do it without using if statements!"""
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def arithmetic(num1, num2, function):
if function == 'add':
return add(num1, num2)
if function == 'subtract':
return subtract(num1, num2)
if function == 'multiply':
return multiply(num1, num2)
if function == 'divide':
return divide(num1, num2)
"def arithmetic(a, b, operator):\n return {\n 'add': a + b,\n 'subtract': a - b,\n 'multiply': a * b,\n 'divide': a / b,\n }[operator]\n #Gives error Ex: on 1,0,'add'\n #But very clever\n" |
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
ans = "-" if numerator * denominator < 0 else ""
numerator = abs(numerator)
denominator = abs(denominator)
ans += str(numerator / denominator)
if numerator % denominator:
ans += "."
numerator = (numerator % denominator) * 10
if numerator == 0:
return ans
d = {}
res = []
while True:
r = numerator % denominator
v = numerator / denominator
if numerator in d:
idx = d[numerator]
return ans + "".join(res[:idx]) + "(" + "".join(res[idx:]) + ")"
res.append(str(v))
if v == 0:
d[numerator] = len(res) - 1
numerator *= 10
continue
d[numerator] = len(res) - 1
numerator = r * 10
if r == 0:
return ans + "".join(res)
return ans + "".join(res) | class Solution(object):
def fraction_to_decimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
ans = '-' if numerator * denominator < 0 else ''
numerator = abs(numerator)
denominator = abs(denominator)
ans += str(numerator / denominator)
if numerator % denominator:
ans += '.'
numerator = numerator % denominator * 10
if numerator == 0:
return ans
d = {}
res = []
while True:
r = numerator % denominator
v = numerator / denominator
if numerator in d:
idx = d[numerator]
return ans + ''.join(res[:idx]) + '(' + ''.join(res[idx:]) + ')'
res.append(str(v))
if v == 0:
d[numerator] = len(res) - 1
numerator *= 10
continue
d[numerator] = len(res) - 1
numerator = r * 10
if r == 0:
return ans + ''.join(res)
return ans + ''.join(res) |
# __init__.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Wed, Sep 1, 2021 5:05:46 PM
"""Demos to show how to use Open GoPro package"""
| """Demos to show how to use Open GoPro package""" |
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
for i in reversed(range(len(num))):
k, num[i] = divmod(num[i] + k, 10)
while k > 0:
num = [k % 10] + num
k //= 10
return num
| class Solution:
def add_to_array_form(self, num: List[int], k: int) -> List[int]:
for i in reversed(range(len(num))):
(k, num[i]) = divmod(num[i] + k, 10)
while k > 0:
num = [k % 10] + num
k //= 10
return num |
# Complete the printLinkedList function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def printLinkedList(head):
if(head is not None):
print(head.data)
printLinkedList(head.next)
| def print_linked_list(head):
if head is not None:
print(head.data)
print_linked_list(head.next) |
class BalanceUnderLimitError(Exception):
pass
class BalanceOverLimitError(Exception):
pass
| class Balanceunderlimiterror(Exception):
pass
class Balanceoverlimiterror(Exception):
pass |
"""
Global settings and constants
"""
TEMP_IMAGE_FILE="/home/pi/tmp/capture.jpg"
CAPTURE_SLEEP=0.5
MUSIC_ROOT="/home/pi/Music"
DEFAULT_VOLUME=40
| """
Global settings and constants
"""
temp_image_file = '/home/pi/tmp/capture.jpg'
capture_sleep = 0.5
music_root = '/home/pi/Music'
default_volume = 40 |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Child(Person):
def __init__(self, name, age):
super().__init__(name, age)
# """"Test Code"""
# child = Child('Boris', 18)
# print(child.__dict__) | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Child(Person):
def __init__(self, name, age):
super().__init__(name, age) |
nbPaquets = int(input())
poidsPaquet = int(input())
poidsTotal = nbPaquets * poidsPaquet
if (poidsTotal > 105):
print("Surcharge !") | nb_paquets = int(input())
poids_paquet = int(input())
poids_total = nbPaquets * poidsPaquet
if poidsTotal > 105:
print('Surcharge !') |
def test_root_api(api_client):
status_code, body, _ = api_client.get('/')
assert 200 == status_code
assert 'API' in body
assert {{cookiecutter.project_short_description}} == body['API']
| def test_root_api(api_client):
(status_code, body, _) = api_client.get('/')
assert 200 == status_code
assert 'API' in body
assert {{cookiecutter.project_short_description}} == body['API'] |
PATH_MESHES = '../output'
PATH_DATASET = '../input'
PATH_UNIT_MESHES = '../unit_meshes'
STR_LEGO_2_4 = 'lego_2_4.stl'
STR_CUBE = 'cube.stl'
| path_meshes = '../output'
path_dataset = '../input'
path_unit_meshes = '../unit_meshes'
str_lego_2_4 = 'lego_2_4.stl'
str_cube = 'cube.stl' |
general = "ffmpeg -f gdigrab -framerate 20 -offset_x"
# Encoding method:
# amd: hevc_amf
# nvidia: hevc_nvenc
encoder = "hevc_nvenc" | general = 'ffmpeg -f gdigrab -framerate 20 -offset_x'
encoder = 'hevc_nvenc' |
_base_ = './solo_r50_fpn_3x_coco.py'
# model settings
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='torchvision://resnet101')))
| _base_ = './solo_r50_fpn_3x_coco.py'
model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet101'))) |
# Time: O(n)
# Space: O(1)
# array
class Solution(object):
def findClosestNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return max(nums, key=lambda x:(-abs(x), x))
| class Solution(object):
def find_closest_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return max(nums, key=lambda x: (-abs(x), x)) |
{
"targets": [
{
"target_name": "compressor",
"sources": [ "./dev/compressor/bit_reader.cpp", "./dev/compressor/bit_writer.cpp", "./dev/compressor/encoding.cpp",
"./dev/compressor/tree_node.cpp", "./dev/compressor/huffman.cpp", "./dev/compressor/node_wrapper.cpp" ],
"include_dirs": [
"<!(node -e \"require('nan')\")"
]
}
]
} | {'targets': [{'target_name': 'compressor', 'sources': ['./dev/compressor/bit_reader.cpp', './dev/compressor/bit_writer.cpp', './dev/compressor/encoding.cpp', './dev/compressor/tree_node.cpp', './dev/compressor/huffman.cpp', './dev/compressor/node_wrapper.cpp'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]} |
# coding: utf-8
"""Module that contains all personalized exceptions used in this library."""
class BaseError(Exception):
"""Base Exception to be inherited by all Githon exceptions.
Args:
kwargs: Dict with attributes that will be logged in message error.
"""
def __init__(self, kwargs):
"""Initialize with keyword arguments."""
self.kwargs = kwargs
class ApiError(Exception):
"""Exception raised when GitHub Server returns status code equals to 500."""
def __str__(self):
return "An unexpected error occurred on the Github API server"
class InvalidQueryError(Exception):
"""Exception raised by searches without query string."""
def __str__(self):
"""Return error description."""
return "Github Query string not provided or is invalid."
class ApiRateLimitError(BaseError):
"""Exception raised by GitHub API rate limit exceeded."""
def __str__(self):
"""Return error description."""
return "GitHub API rate limit for your token was reached. X-RateLimit-Limit: {0} - X-RateLimit-Remaining: {1}".format(self.kwargs.get('X-RateLimit-Limit', None), self.kwargs.get('X-RateLimit-Remaining', None))
class UserNotFoundError(BaseError):
"""Exception raised by searches with an unexistent username."""
def __str__(self):
"""Return error description."""
return "Github user '{}' not exists.".format(
self.kwargs.get('user', None))
class RepositoryIdNotFoundError(BaseError):
"""Exception raised by searches with an unexistent repository ID."""
def __str__(self):
"""Return error description."""
return "Reposity with ID '{}' does not exists.".format(
self.kwargs.get('repository_id', None))
class RepositoryNameNotFoundError(BaseError):
"""Exception raised by searches with an unexistent repository name."""
def __str__(self):
"""Return error description."""
return "Reposity with name '{0}' not exists for user '{1}'".format(
self.kwargs.get('repository_id', None),
self.kwargs.get('username', None))
class InvalidTokenError(BaseError):
"""Exception raised by unexistents or expired access token."""
def __str__(self):
"""Return error description."""
return "The access token '{}' doesn't have permission to access the requested resource or has been expired.".format(
self.kwargs.get('access_token', None))
class InvalidDateTimeFormat(BaseError):
"""Exception raised by invalid datetime converts."""
def __str__(self):
"""Return error description."""
return "The datetime '{}' doesn't have a valid format to convertion.".format(
self.kwargs.get('datetime', None))
| """Module that contains all personalized exceptions used in this library."""
class Baseerror(Exception):
"""Base Exception to be inherited by all Githon exceptions.
Args:
kwargs: Dict with attributes that will be logged in message error.
"""
def __init__(self, kwargs):
"""Initialize with keyword arguments."""
self.kwargs = kwargs
class Apierror(Exception):
"""Exception raised when GitHub Server returns status code equals to 500."""
def __str__(self):
return 'An unexpected error occurred on the Github API server'
class Invalidqueryerror(Exception):
"""Exception raised by searches without query string."""
def __str__(self):
"""Return error description."""
return 'Github Query string not provided or is invalid.'
class Apiratelimiterror(BaseError):
"""Exception raised by GitHub API rate limit exceeded."""
def __str__(self):
"""Return error description."""
return 'GitHub API rate limit for your token was reached. X-RateLimit-Limit: {0} - X-RateLimit-Remaining: {1}'.format(self.kwargs.get('X-RateLimit-Limit', None), self.kwargs.get('X-RateLimit-Remaining', None))
class Usernotfounderror(BaseError):
"""Exception raised by searches with an unexistent username."""
def __str__(self):
"""Return error description."""
return "Github user '{}' not exists.".format(self.kwargs.get('user', None))
class Repositoryidnotfounderror(BaseError):
"""Exception raised by searches with an unexistent repository ID."""
def __str__(self):
"""Return error description."""
return "Reposity with ID '{}' does not exists.".format(self.kwargs.get('repository_id', None))
class Repositorynamenotfounderror(BaseError):
"""Exception raised by searches with an unexistent repository name."""
def __str__(self):
"""Return error description."""
return "Reposity with name '{0}' not exists for user '{1}'".format(self.kwargs.get('repository_id', None), self.kwargs.get('username', None))
class Invalidtokenerror(BaseError):
"""Exception raised by unexistents or expired access token."""
def __str__(self):
"""Return error description."""
return "The access token '{}' doesn't have permission to access the requested resource or has been expired.".format(self.kwargs.get('access_token', None))
class Invaliddatetimeformat(BaseError):
"""Exception raised by invalid datetime converts."""
def __str__(self):
"""Return error description."""
return "The datetime '{}' doesn't have a valid format to convertion.".format(self.kwargs.get('datetime', None)) |
cur.sendQuery("exec exampleproc");
field00=cur.getFieldByIndex(0,0);
field01=cur.getFieldByIndex(0,1);
field02=cur.getFieldByIndex(0,2);
field10=cur.getFieldByIndex(1,0);
field11=cur.getFieldByIndex(1,1);
field12=cur.getFieldByIndex(1,2);
| cur.sendQuery('exec exampleproc')
field00 = cur.getFieldByIndex(0, 0)
field01 = cur.getFieldByIndex(0, 1)
field02 = cur.getFieldByIndex(0, 2)
field10 = cur.getFieldByIndex(1, 0)
field11 = cur.getFieldByIndex(1, 1)
field12 = cur.getFieldByIndex(1, 2) |
# Worker Processes
worker_class = 'sync'
socket_path = 'unix:/tmp/web-info.sock'
bind = socket_path
| worker_class = 'sync'
socket_path = 'unix:/tmp/web-info.sock'
bind = socket_path |
word="banana"
def bananas(s):
return helper(s, [], "", len(word))
def helper(s, arr, remain, length):
if length==0:
arr.append(remain+len(s)*"-")
return
for i,j in enumerate(s):
if j==word[len(word)-length]:
helper(s[i+1:], arr, remain+"-"*i+j, length-1)
return arr | word = 'banana'
def bananas(s):
return helper(s, [], '', len(word))
def helper(s, arr, remain, length):
if length == 0:
arr.append(remain + len(s) * '-')
return
for (i, j) in enumerate(s):
if j == word[len(word) - length]:
helper(s[i + 1:], arr, remain + '-' * i + j, length - 1)
return arr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.