content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
def table_pkey(table):
query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='{table}' ORDER BY KU.TABLE_NAME,KU.ORDINAL_POSITION LIMIT 1;"""
return query
def get_fkey_relations(db_name, table):
query = f"""SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '{db_name}'
AND REFERENCED_TABLE_NAME = '{table}';"""
return query
def get_index_info(db_name):
query = f"""SELECT DISTINCT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '{db_name}';"""
return query
def get_table_columns_for_indexing(table):
query = f"select column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table}';"
return query
def get_table_ref_idx(index_table, table, index_column, column):
sql = f"SELECT * FROM {index_table}, {table} WHERE {index_table}.{index_column} = {table}.{column} LIMIT 500;"
return sql
|
def table_pkey(table):
query = f"SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC \n INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME \n AND KU.table_name='{table}' ORDER BY KU.TABLE_NAME,KU.ORDINAL_POSITION LIMIT 1;"
return query
def get_fkey_relations(db_name, table):
query = f"SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '{db_name}'\n AND REFERENCED_TABLE_NAME = '{table}';"
return query
def get_index_info(db_name):
query = f"SELECT DISTINCT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '{db_name}';"
return query
def get_table_columns_for_indexing(table):
query = f"select column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{table}';"
return query
def get_table_ref_idx(index_table, table, index_column, column):
sql = f'SELECT * FROM {index_table}, {table} WHERE {index_table}.{index_column} = {table}.{column} LIMIT 500;'
return sql
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: __init__.py.py
Author: Scott Yang(Scott)
Email: yangyingfa@skybility.com
Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved.
Description:
"""
|
"""
File: __init__.py.py
Author: Scott Yang(Scott)
Email: yangyingfa@skybility.com
Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved.
Description:
"""
|
#
# Copyright 2017 Vitalii Kulanov
#
class ClientException(Exception):
"""Base Exception for Dropme client
All child classes must be instantiated before raising.
"""
pass
class ConfigNotFoundException(ClientException):
"""
Should be raised if configuration for dropme client is not specified.
"""
pass
class InvalidFileException(ClientException):
"""
Should be raised when some problems while working with file occurred.
"""
pass
class ActionException(ClientException):
"""
Should be raised when some problems occurred while perform any command
"""
|
class Clientexception(Exception):
"""Base Exception for Dropme client
All child classes must be instantiated before raising.
"""
pass
class Confignotfoundexception(ClientException):
"""
Should be raised if configuration for dropme client is not specified.
"""
pass
class Invalidfileexception(ClientException):
"""
Should be raised when some problems while working with file occurred.
"""
pass
class Actionexception(ClientException):
"""
Should be raised when some problems occurred while perform any command
"""
|
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
# Example:
# Input: [0,1,0,2,1,0,1,3,2,1,2,1]
# Output: 6
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if (height == []):
return 0
maximum = max(height)
x = height.count(maximum) - 1
index = height.index(maximum)
result = 0
if (index > 1):
result += Solution.trap(self, height[:index] + [max(height[:index])])
while x > 0:
nextIndex = height[index + 1:].index(maximum) + index + 1
for i in height[index + 1: nextIndex]:
result += maximum - i
index = nextIndex
x -= 1
if (index < len(height) - 1):
result += Solution.trap(self, [max(height[index + 1:])] + height[index + 1:])
return result
|
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if height == []:
return 0
maximum = max(height)
x = height.count(maximum) - 1
index = height.index(maximum)
result = 0
if index > 1:
result += Solution.trap(self, height[:index] + [max(height[:index])])
while x > 0:
next_index = height[index + 1:].index(maximum) + index + 1
for i in height[index + 1:nextIndex]:
result += maximum - i
index = nextIndex
x -= 1
if index < len(height) - 1:
result += Solution.trap(self, [max(height[index + 1:])] + height[index + 1:])
return result
|
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
if not s :
return ""
s = list(s)
st = []
for i,n in enumerate(s):
if n == "(":
st.append(i)
elif n == ")" :
if st :
st.pop()
else :
s[i] = ""
while st:
s[st.pop()] = ""
return "".join(s)
|
class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
if not s:
return ''
s = list(s)
st = []
for (i, n) in enumerate(s):
if n == '(':
st.append(i)
elif n == ')':
if st:
st.pop()
else:
s[i] = ''
while st:
s[st.pop()] = ''
return ''.join(s)
|
#Given a sorted array and a target value, return the index if the target is found. If not, return the index
#where it would be if it were inserted in order.
#You may assume no duplicates in the array.
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
self._nums = nums
self._target = target
if len(nums) == 0:
return 0
return self.findPos(0, len(nums) - 1)
def findPos(self, low, high):
#print(low, high, nums[low:high + 1])
if low >= high:
if self._target <= self._nums[low]:
return low
else:
return low + 1
mid = (low + high) // 2
if self._target == self._nums[mid]:
return mid
elif self._target < self._nums[mid]:
return self.findPos(low, mid - 1)
else:
return self.findPos(mid + 1, high)
sol = Solution()
res = sol.searchInsert([1,3], 0)
print(res)
|
class Solution(object):
def search_insert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
self._nums = nums
self._target = target
if len(nums) == 0:
return 0
return self.findPos(0, len(nums) - 1)
def find_pos(self, low, high):
if low >= high:
if self._target <= self._nums[low]:
return low
else:
return low + 1
mid = (low + high) // 2
if self._target == self._nums[mid]:
return mid
elif self._target < self._nums[mid]:
return self.findPos(low, mid - 1)
else:
return self.findPos(mid + 1, high)
sol = solution()
res = sol.searchInsert([1, 3], 0)
print(res)
|
class PoolArgs:
def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber):
self.BankerBufCap = bankerBufCap
self.BankerMaxBufNumber = bankerMaxBufNumber
self.SignerBufCap = signerBufCap
self.SignerBufMaxNumber = signerBufMaxNumber
self.BroadcasterBufCap = broadcasterBufCap
self.BroadcasterMaxNumber = broadcasterMaxNumber
self.StakingBufCap = stakingBufCap
self.StakingMaxNumber = stakingMaxNumber
self.DistributionBufCap = distributionBufCap
self.DistributionMaxNumber = distributionMaxNumber
self.ErrorBufCap = errorBufCap
self.ErrorMaxNumber = errorMaxNumber
def Check(self):
if self.BankerBufCap == 0:
return PoolArgsError('zero banker buffer capacity')
if self.BankerMaxBufNumber == 0:
return PoolArgsError('zero banker max buffer number')
if self.SignerBufCap == 0:
return PoolArgsError('zero signer buffer capacity')
if self.SignerBufMaxNumber == 0:
return PoolArgsError('zero signer max buffer number')
if self.BroadcasterBufCap == 0:
return PoolArgsError('zero broadcaster buffer capacity')
if self.BroadcasterMaxNumber == 0:
return PoolArgsError('zero broadcaster max buffer number')
if self.StakingBufCap == 0:
return PoolArgsError('zero staking buffer capacity')
if self.StakingMaxNumber == 0:
return PoolArgsError('zero staking max buffer number')
if self.DistributionBufCap == 0:
return PoolArgsError('zero distribution buffer capacity')
if self.DistributionMaxNumber == 0:
return PoolArgsError('zero distribution max buffer number')
if self.ErrorBufCap == 0:
return PoolArgsError('zero error buffer capacity')
if self.ErrorMaxNumber == 0:
return PoolArgsError('zero error max buffer number')
return None
class PoolArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class ModuleArgs:
def __init__(self, bankers, signers, broadcasters, stakings, distributors):
self.Bankers = bankers
self.Signers = signers
self.Broadcasters = broadcasters
self.Stakings = stakings
self.Distributors = distributors
def Check(self):
if len(self.Bankers) == 0:
return ModuleArgsError('empty banker list')
if len(self.Signers) == 0:
return ModuleArgsError('empty signer list')
if len(self.Broadcasters) == 0:
return ModuleArgsError('empty broadcaster list')
if len(self.Stakings) == 0:
return ModuleArgsError('empty stakinger list')
if len(self.Distributors) == 0:
return ModuleArgsError('empty distributor list')
return None
class ModuleArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class SendCoinArgs:
def __init__(self, srcAccount, dstAccount, coins, fees, gas, gasAdjust):
self.srcAccount = srcAccount
self.dstAccount = dstAccount
self.coins = coins
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def Check(self):
if self.srcAccount is None or self.srcAccount.getAddress() == '':
return SendCoinArgsError('srcAccount is invalid')
if self.dstAccount is None or self.dstAccount.getAddress() == '':
return SendCoinArgsError('dstAccount is invalid')
if self.coins is None or len(self.coins) == 0:
return SendCoinArgsError('empty coins')
if self.fees is None or len(self.fees) == 0:
return SendCoinArgsError('empty fess')
if self.gas is None:
return SendCoinArgsError('empty gas')
if self.gasAdjust is None:
return SendCoinArgsError('empty gasAdjust')
return None
class SendCoinArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class SendSignArgs:
def __init__(self, srcAccount, sendedJsonFilePath, node):
self.srcAccount = srcAccount
self.sendedJsonFilePath = sendedJsonFilePath
self.node = node
def Check(self):
if self.srcAccount is None or self.srcAccount.getAddress() == '':
return SendSignArgsError('srcAccount is invalid')
if self.sendedJsonFilePath is None:
return SendSignArgsError('empty sendedJsonFilePath')
if self.node is None:
return SendSignArgsError('empty node')
return None
class SendSignArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class SendBroadcastArgs:
def __init__(self, srcAccount, body, mode='sync'):
self.srcAccount = srcAccount
self.body = body
self.mode = mode
def Check(self):
if self.body is None:
return SendBroadcastArgsError('empty broadcast body')
if self.srcAccount is None:
return SendBroadcastArgsError('unknown tx src account')
return None
class SendBroadcastArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class DelegateArgs():
def __init__(self, delegator, validator, coin, fees, gas, gasAdjust):
self.delegator = delegator
self.validator = validator
self.coin = coin
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def Check(self):
if self.delegator is None or self.delegator.getAddress() == '':
return DelegateArgsError('delegator is invalid')
if self.validator is None:
return DelegateArgsError('validator is invalid')
if self.coin is None:
return DelegateArgsError('empty coins')
if self.fees is None or len(self.fees) == 0:
return DelegateArgsError('empty fess')
if self.gas is None:
return DelegateArgsError('empty gas')
if self.gasAdjust is None:
return DelegateArgsError('empty gasAdjust')
return None
class StakingArgs():
def __init__(self, _type, data):
self._type = _type
self.data = data
def getType(self):
return self._type
def getData(self):
return self.data
class WithdrawDelegatorOneRewardArgs():
def __init__(self, delegator, validator, fees, gas, gasAdjust):
self.delegator = delegator
self.validator = validator
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def Check(self):
if self.delegator is None or self.delegator.getAddress() == '':
return DelegateArgsError('delegator is invalid')
if self.validator is None:
return DelegateArgsError('validator is invalid')
if self.fees is None or len(self.fees) == 0:
return DelegateArgsError('empty fess')
if self.gas is None:
return DelegateArgsError('empty gas')
if self.gasAdjust is None:
return DelegateArgsError('empty gasAdjust')
return None
class DistributionArgs():
def __init__(self, _type, data):
self._type = _type
self.data = data
def getType(self):
return self._type
def getData(self):
return self.data
class DelegateArgsError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
|
class Poolargs:
def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber):
self.BankerBufCap = bankerBufCap
self.BankerMaxBufNumber = bankerMaxBufNumber
self.SignerBufCap = signerBufCap
self.SignerBufMaxNumber = signerBufMaxNumber
self.BroadcasterBufCap = broadcasterBufCap
self.BroadcasterMaxNumber = broadcasterMaxNumber
self.StakingBufCap = stakingBufCap
self.StakingMaxNumber = stakingMaxNumber
self.DistributionBufCap = distributionBufCap
self.DistributionMaxNumber = distributionMaxNumber
self.ErrorBufCap = errorBufCap
self.ErrorMaxNumber = errorMaxNumber
def check(self):
if self.BankerBufCap == 0:
return pool_args_error('zero banker buffer capacity')
if self.BankerMaxBufNumber == 0:
return pool_args_error('zero banker max buffer number')
if self.SignerBufCap == 0:
return pool_args_error('zero signer buffer capacity')
if self.SignerBufMaxNumber == 0:
return pool_args_error('zero signer max buffer number')
if self.BroadcasterBufCap == 0:
return pool_args_error('zero broadcaster buffer capacity')
if self.BroadcasterMaxNumber == 0:
return pool_args_error('zero broadcaster max buffer number')
if self.StakingBufCap == 0:
return pool_args_error('zero staking buffer capacity')
if self.StakingMaxNumber == 0:
return pool_args_error('zero staking max buffer number')
if self.DistributionBufCap == 0:
return pool_args_error('zero distribution buffer capacity')
if self.DistributionMaxNumber == 0:
return pool_args_error('zero distribution max buffer number')
if self.ErrorBufCap == 0:
return pool_args_error('zero error buffer capacity')
if self.ErrorMaxNumber == 0:
return pool_args_error('zero error max buffer number')
return None
class Poolargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Moduleargs:
def __init__(self, bankers, signers, broadcasters, stakings, distributors):
self.Bankers = bankers
self.Signers = signers
self.Broadcasters = broadcasters
self.Stakings = stakings
self.Distributors = distributors
def check(self):
if len(self.Bankers) == 0:
return module_args_error('empty banker list')
if len(self.Signers) == 0:
return module_args_error('empty signer list')
if len(self.Broadcasters) == 0:
return module_args_error('empty broadcaster list')
if len(self.Stakings) == 0:
return module_args_error('empty stakinger list')
if len(self.Distributors) == 0:
return module_args_error('empty distributor list')
return None
class Moduleargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Sendcoinargs:
def __init__(self, srcAccount, dstAccount, coins, fees, gas, gasAdjust):
self.srcAccount = srcAccount
self.dstAccount = dstAccount
self.coins = coins
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def check(self):
if self.srcAccount is None or self.srcAccount.getAddress() == '':
return send_coin_args_error('srcAccount is invalid')
if self.dstAccount is None or self.dstAccount.getAddress() == '':
return send_coin_args_error('dstAccount is invalid')
if self.coins is None or len(self.coins) == 0:
return send_coin_args_error('empty coins')
if self.fees is None or len(self.fees) == 0:
return send_coin_args_error('empty fess')
if self.gas is None:
return send_coin_args_error('empty gas')
if self.gasAdjust is None:
return send_coin_args_error('empty gasAdjust')
return None
class Sendcoinargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Sendsignargs:
def __init__(self, srcAccount, sendedJsonFilePath, node):
self.srcAccount = srcAccount
self.sendedJsonFilePath = sendedJsonFilePath
self.node = node
def check(self):
if self.srcAccount is None or self.srcAccount.getAddress() == '':
return send_sign_args_error('srcAccount is invalid')
if self.sendedJsonFilePath is None:
return send_sign_args_error('empty sendedJsonFilePath')
if self.node is None:
return send_sign_args_error('empty node')
return None
class Sendsignargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Sendbroadcastargs:
def __init__(self, srcAccount, body, mode='sync'):
self.srcAccount = srcAccount
self.body = body
self.mode = mode
def check(self):
if self.body is None:
return send_broadcast_args_error('empty broadcast body')
if self.srcAccount is None:
return send_broadcast_args_error('unknown tx src account')
return None
class Sendbroadcastargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Delegateargs:
def __init__(self, delegator, validator, coin, fees, gas, gasAdjust):
self.delegator = delegator
self.validator = validator
self.coin = coin
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def check(self):
if self.delegator is None or self.delegator.getAddress() == '':
return delegate_args_error('delegator is invalid')
if self.validator is None:
return delegate_args_error('validator is invalid')
if self.coin is None:
return delegate_args_error('empty coins')
if self.fees is None or len(self.fees) == 0:
return delegate_args_error('empty fess')
if self.gas is None:
return delegate_args_error('empty gas')
if self.gasAdjust is None:
return delegate_args_error('empty gasAdjust')
return None
class Stakingargs:
def __init__(self, _type, data):
self._type = _type
self.data = data
def get_type(self):
return self._type
def get_data(self):
return self.data
class Withdrawdelegatoronerewardargs:
def __init__(self, delegator, validator, fees, gas, gasAdjust):
self.delegator = delegator
self.validator = validator
self.fees = fees
self.gas = gas
self.gasAdjust = gasAdjust
def check(self):
if self.delegator is None or self.delegator.getAddress() == '':
return delegate_args_error('delegator is invalid')
if self.validator is None:
return delegate_args_error('validator is invalid')
if self.fees is None or len(self.fees) == 0:
return delegate_args_error('empty fess')
if self.gas is None:
return delegate_args_error('empty gas')
if self.gasAdjust is None:
return delegate_args_error('empty gasAdjust')
return None
class Distributionargs:
def __init__(self, _type, data):
self._type = _type
self.data = data
def get_type(self):
return self._type
def get_data(self):
return self.data
class Delegateargserror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
|
# Signal processing
SAMPLE_RATE = 16000
PREEMPHASIS_ALPHA = 0.97
FRAME_LEN = 0.025
FRAME_STEP = 0.01
NUM_FFT = 512
BUCKET_STEP = 1
MAX_SEC = 10
# Model
WEIGHTS_FILE = "data/model/weights.h5"
COST_METRIC = "cosine" # euclidean or cosine
INPUT_SHAPE=(NUM_FFT,None,1)
# IO
ENROLL_LIST_FILE = "cfg/enroll_list.csv"
TEST_LIST_FILE = "cfg/test_list.csv"
RESULT_FILE = "res/results.csv"
|
sample_rate = 16000
preemphasis_alpha = 0.97
frame_len = 0.025
frame_step = 0.01
num_fft = 512
bucket_step = 1
max_sec = 10
weights_file = 'data/model/weights.h5'
cost_metric = 'cosine'
input_shape = (NUM_FFT, None, 1)
enroll_list_file = 'cfg/enroll_list.csv'
test_list_file = 'cfg/test_list.csv'
result_file = 'res/results.csv'
|
class Mac_Address_Information:
par_id = ''
case_id = ''
evd_id = ''
mac_address = ''
description = ''
backup_flag = ''
source_location = []
def MACADDRESS(reg_system):
mac_address_list = []
mac_address_count = 0
reg_key = reg_system.find_key(r"ControlSet001\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}")
for reg_subkey in reg_key.subkeys():
try:
for reg_subkey_value in reg_subkey.values():
if reg_subkey_value.name() == 'DeviceInstanceID':
if 'FFFF' in reg_subkey_value.data():
mac_address_information = Mac_Address_Information()
mac_address_list.append(mac_address_information)
mac_address_list[mac_address_count].source_location = []
mac_address_list[mac_address_count].source_location.append('SYSTEM-ControlSet001/Control/Class/{4d36e972-e325-11ce-bfc1-08002be10318}')
mac_address_list[mac_address_count].mac_address = reg_subkey_value.data().split('\\')[-1][0:6] + reg_subkey_value.data().split('\\')[-1][10:16]
mac_address_list[mac_address_count].description = reg_subkey.value(name='DriverDesc').data()
mac_address_count = mac_address_count + 1
except:
print('-----MAC Address Error')
return mac_address_list
|
class Mac_Address_Information:
par_id = ''
case_id = ''
evd_id = ''
mac_address = ''
description = ''
backup_flag = ''
source_location = []
def macaddress(reg_system):
mac_address_list = []
mac_address_count = 0
reg_key = reg_system.find_key('ControlSet001\\Control\\Class\\{4d36e972-e325-11ce-bfc1-08002be10318}')
for reg_subkey in reg_key.subkeys():
try:
for reg_subkey_value in reg_subkey.values():
if reg_subkey_value.name() == 'DeviceInstanceID':
if 'FFFF' in reg_subkey_value.data():
mac_address_information = mac__address__information()
mac_address_list.append(mac_address_information)
mac_address_list[mac_address_count].source_location = []
mac_address_list[mac_address_count].source_location.append('SYSTEM-ControlSet001/Control/Class/{4d36e972-e325-11ce-bfc1-08002be10318}')
mac_address_list[mac_address_count].mac_address = reg_subkey_value.data().split('\\')[-1][0:6] + reg_subkey_value.data().split('\\')[-1][10:16]
mac_address_list[mac_address_count].description = reg_subkey.value(name='DriverDesc').data()
mac_address_count = mac_address_count + 1
except:
print('-----MAC Address Error')
return mac_address_list
|
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0.
To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |j-i|, where || denotes absolute value.Find the time taken to type the string S2 with the given keyboard layout.
Example 1:
Input:
S1 = "abcdefghijklmnopqrstuvwxyz"
S2 = "cba"
Output:
4
Explanation:
Initially we are at index 0. To type 'c',
it will take a time of abs(0-2) = 2. To, type
'b' next, it will take abs(2-1) = 1. And, for
'a', it will take abs(1-0) = 1 unit time.
So, total time = 2+1+1 = 4."""
S1 = "abcdefghijklmnopqrstuvwxyz"
S2 = "cba"
map = {}
initial = 0
distance = []
for i in range(26):
map[S1[i]] = i
print(map)
for i in S2:
print(i)
distance.append(abs(map[i] - initial))
initial = map[i]
print(distance)
|
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0.
To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |j-i|, where || denotes absolute value.Find the time taken to type the string S2 with the given keyboard layout.
Example 1:
Input:
S1 = "abcdefghijklmnopqrstuvwxyz"
S2 = "cba"
Output:
4
Explanation:
Initially we are at index 0. To type 'c',
it will take a time of abs(0-2) = 2. To, type
'b' next, it will take abs(2-1) = 1. And, for
'a', it will take abs(1-0) = 1 unit time.
So, total time = 2+1+1 = 4."""
s1 = 'abcdefghijklmnopqrstuvwxyz'
s2 = 'cba'
map = {}
initial = 0
distance = []
for i in range(26):
map[S1[i]] = i
print(map)
for i in S2:
print(i)
distance.append(abs(map[i] - initial))
initial = map[i]
print(distance)
|
# ***************************************************************************************
# ***************************************************************************************
#
# Name : processcore.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 22nd December 2018
# Purpose : Convert vocabulary.asm to assemblable file by adding marker labels.
#
# ***************************************************************************************
# ***************************************************************************************
#
# Copy vocabulary.asm to __words.asm
#
hOut = open("__words.asm","w")
for l in [x.rstrip() for x in open("vocabulary.asm").readlines()]:
hOut.write(l+"\n")
#
# If ;; found insert a label which is generated using ASCII so all chars can be used
#
if l[:2] == ";;":
name = "_".join([str(ord(x)) for x in l[2:].strip()])
hOut.write("core_{0}:\n".format(name))
hOut.close()
|
h_out = open('__words.asm', 'w')
for l in [x.rstrip() for x in open('vocabulary.asm').readlines()]:
hOut.write(l + '\n')
if l[:2] == ';;':
name = '_'.join([str(ord(x)) for x in l[2:].strip()])
hOut.write('core_{0}:\n'.format(name))
hOut.close()
|
"""
https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/python
Given an int, return the next 'integral perfect square', which is an integer n such that sqrt(n) is also an int.
If the given int is not an integral perfect square, return -1.
"""
def find_next_square(sq: int) -> int:
sqrt_of_sq = sq ** (1/2)
if sqrt_of_sq % 1 != 0:
return -1
else:
return int((sqrt_of_sq + 1) ** 2)
def find_next_square2(sq: int) -> int:
"""
This version is just more compact.
"""
sqrt_of_sq = sq ** (1/2)
return -1 if sqrt_of_sq % 1 != 0 else int((sqrt_of_sq + 1) ** 2)
def find_next_square3(sq: int) -> int:
"""
This version uses the .is_integer() method instead of %.
"""
sqrt_of_sq = sq ** 0.5
return int((sqrt_of_sq+1)**2) if sqrt_of_sq.is_integer() else -1
print(find_next_square3(4)) # 9
print(find_next_square3(121)) # 144
print(find_next_square3(625)) # 676
print(find_next_square3(114)) # -1
|
"""
https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/python
Given an int, return the next 'integral perfect square', which is an integer n such that sqrt(n) is also an int.
If the given int is not an integral perfect square, return -1.
"""
def find_next_square(sq: int) -> int:
sqrt_of_sq = sq ** (1 / 2)
if sqrt_of_sq % 1 != 0:
return -1
else:
return int((sqrt_of_sq + 1) ** 2)
def find_next_square2(sq: int) -> int:
"""
This version is just more compact.
"""
sqrt_of_sq = sq ** (1 / 2)
return -1 if sqrt_of_sq % 1 != 0 else int((sqrt_of_sq + 1) ** 2)
def find_next_square3(sq: int) -> int:
"""
This version uses the .is_integer() method instead of %.
"""
sqrt_of_sq = sq ** 0.5
return int((sqrt_of_sq + 1) ** 2) if sqrt_of_sq.is_integer() else -1
print(find_next_square3(4))
print(find_next_square3(121))
print(find_next_square3(625))
print(find_next_square3(114))
|
class Ledfade:
def __init__(self, *args, **kwargs):
if 'start' in kwargs:
self.start = kwargs.get('start')
if 'end' in kwargs:
self.end = kwargs.get('end')
if 'action' in kwargs:
self.action = kwargs.get('action')
self.transit = self.end - self.start
def ledpwm(self, p):
c = 0.181+(0.0482*p)+(0.00323*p*p)+(0.0000629*p*p*p)
if c < 0.0:
return 0
if c > 0.0 and c <= 100.0:
return c
elif c > 100.0:
return 100
def update(self, now):
if self.action == 'sunrise':
return self.ledpwm(((now - self.start) / self.transit) * 100)
elif self.action == 'sunset':
return self.ledpwm(100 - ((now - self.start) / self.transit) * 100)
|
class Ledfade:
def __init__(self, *args, **kwargs):
if 'start' in kwargs:
self.start = kwargs.get('start')
if 'end' in kwargs:
self.end = kwargs.get('end')
if 'action' in kwargs:
self.action = kwargs.get('action')
self.transit = self.end - self.start
def ledpwm(self, p):
c = 0.181 + 0.0482 * p + 0.00323 * p * p + 6.29e-05 * p * p * p
if c < 0.0:
return 0
if c > 0.0 and c <= 100.0:
return c
elif c > 100.0:
return 100
def update(self, now):
if self.action == 'sunrise':
return self.ledpwm((now - self.start) / self.transit * 100)
elif self.action == 'sunset':
return self.ledpwm(100 - (now - self.start) / self.transit * 100)
|
"""Foreign Key Solving base class."""
class ForeignKeySolver():
def fit(self, list_of_databases):
"""Fit this solver.
Args:
list_of_databases (list):
List of tuples containing ``MetaData`` instnces and table dictinaries,
which contain table names as input and ``pandas.DataFrames`` as values.
"""
pass
def solve(self, tables, primary_keys=None):
"""Solve the foreign key detection problem.
The output is a list of foreign key specifications, in order from the most likely
to the least likely.
Args:
tables (dict):
Dict containing table names as input and ``pandas.DataFrames``
as values.
primary_keys (dict):
(Optional). Dictionary of table primary keys, as returned by the Primary
Key Solvers. This parameter is optional and not all the subclasses need it.
Returns:
dict:
List of foreign key specifications, sorted by likelyhood.
"""
raise NotImplementedError()
|
"""Foreign Key Solving base class."""
class Foreignkeysolver:
def fit(self, list_of_databases):
"""Fit this solver.
Args:
list_of_databases (list):
List of tuples containing ``MetaData`` instnces and table dictinaries,
which contain table names as input and ``pandas.DataFrames`` as values.
"""
pass
def solve(self, tables, primary_keys=None):
"""Solve the foreign key detection problem.
The output is a list of foreign key specifications, in order from the most likely
to the least likely.
Args:
tables (dict):
Dict containing table names as input and ``pandas.DataFrames``
as values.
primary_keys (dict):
(Optional). Dictionary of table primary keys, as returned by the Primary
Key Solvers. This parameter is optional and not all the subclasses need it.
Returns:
dict:
List of foreign key specifications, sorted by likelyhood.
"""
raise not_implemented_error()
|
"""
predefined params for openimu
"""
JSON_FILE_NAME = 'openimu.json'
def get_app_names():
'''
define openimu app type
'''
app_names = ['Compass',
'IMU',
'INS',
'Leveler',
'OpenIMU',
'VG',
'VG_AHRS',
]
return app_names
APP_STR = ['INS', 'VG', 'VG_AHRS', 'Compass', 'Leveler', 'IMU', 'OpenIMU']
|
"""
predefined params for openimu
"""
json_file_name = 'openimu.json'
def get_app_names():
"""
define openimu app type
"""
app_names = ['Compass', 'IMU', 'INS', 'Leveler', 'OpenIMU', 'VG', 'VG_AHRS']
return app_names
app_str = ['INS', 'VG', 'VG_AHRS', 'Compass', 'Leveler', 'IMU', 'OpenIMU']
|
def read_paragraph_element(element):
"""Returns text in given ParagraphElement
Args:
element: ParagraphElement from Google Doc
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content')
def read_structural_elements(elements):
"""Recurses through list of Structural Elements to read document's
text where text may be in nested elements
Args:
elements: list of Structural Elements.
"""
text = ''
for value in elements:
if 'paragraph' in value:
elements = value.get('paragraph').get('elements')
for elem in elements:
text += read_paragraph_element(elem)
elif 'table' in value:
# text in table cells are in nested Structural Elements
# and tables may be nested
table = value.get('table')
for row in table.get('tableRows'):
cells = row.get('tableCells')
for cell in cells:
text += read_strucutural_elements(cell.get('content'))
elif 'tableOfContents' in value:
# text in TOC is also in Structural Element.
toc = value.get('tableOfContents')
text += read_strucutural_elements(toc.get('content'))
return text
|
def read_paragraph_element(element):
"""Returns text in given ParagraphElement
Args:
element: ParagraphElement from Google Doc
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content')
def read_structural_elements(elements):
"""Recurses through list of Structural Elements to read document's
text where text may be in nested elements
Args:
elements: list of Structural Elements.
"""
text = ''
for value in elements:
if 'paragraph' in value:
elements = value.get('paragraph').get('elements')
for elem in elements:
text += read_paragraph_element(elem)
elif 'table' in value:
table = value.get('table')
for row in table.get('tableRows'):
cells = row.get('tableCells')
for cell in cells:
text += read_strucutural_elements(cell.get('content'))
elif 'tableOfContents' in value:
toc = value.get('tableOfContents')
text += read_strucutural_elements(toc.get('content'))
return text
|
def average_speed(s1 : float, s0 : float, t1 : float, t0 : float) -> float:
"""
[FUNC] average_speed:
Returns the average speed.
Where:
Delta Space = (space1[s1] - space0[s0])
Delta Time = (time1[t1] - time0[t0])
"""
return ((s1-s0)/(t1-t0));
def average_acceleration(v1 : float, v0 : float, t1 : float, t0 : float) -> float:
"""
[FUNC] average_acceleration:
Returns the average_acceleration
"""
return ((v1-v0)/(t1-t0));
|
def average_speed(s1: float, s0: float, t1: float, t0: float) -> float:
"""
[FUNC] average_speed:
Returns the average speed.
Where:
Delta Space = (space1[s1] - space0[s0])
Delta Time = (time1[t1] - time0[t0])
"""
return (s1 - s0) / (t1 - t0)
def average_acceleration(v1: float, v0: float, t1: float, t0: float) -> float:
"""
[FUNC] average_acceleration:
Returns the average_acceleration
"""
return (v1 - v0) / (t1 - t0)
|
def set_material(sg_node, sg_material_node):
'''Sets the material on a scenegraph group node and sets the materialid
user attribute at the same time.
Arguments:
sg_node (RixSGGroup) - scene graph group node to attach the material.
sg_material_node (RixSGMaterial) - the scene graph material node
'''
sg_node.SetMaterial(sg_material_node)
attrs = sg_node.GetAttributes()
attrs.SetString('user:__materialid', sg_material_node.GetIdentifier().CStr())
sg_node.SetAttributes(attrs)
|
def set_material(sg_node, sg_material_node):
"""Sets the material on a scenegraph group node and sets the materialid
user attribute at the same time.
Arguments:
sg_node (RixSGGroup) - scene graph group node to attach the material.
sg_material_node (RixSGMaterial) - the scene graph material node
"""
sg_node.SetMaterial(sg_material_node)
attrs = sg_node.GetAttributes()
attrs.SetString('user:__materialid', sg_material_node.GetIdentifier().CStr())
sg_node.SetAttributes(attrs)
|
# Debug or not
DEBUG = 1
# Trackbar or not
CREATE_TRACKBARS = 1
# Display or not
DISPLAY = 1
# Image or Video, if "Video" is given as argument, program will use cv2.VideoCapture
# If "Image" argument is given the program will use cv2.imread
imageType = "Video"
# imageType = "Image"
# Image/Video source 0 or 1 for webcam or the file path of the video source such as
# "images/rocket/RocketPanelStraightDark72in.jpg" or "images/rocket/testvideo.mp4"
imageSource = 0
# Ip address
ipAddress = "10.99.99.2"
# The script to make camera arrangements
osScript = "v4l2-ctl --device /dev/video0 -c auto_exposure=1 -c exposure_auto_priority=0 -c exposure_time_absolute=20 --set-fmt-video=width=160,height=120,pixelformat=MJPG -p 15 && v4l2-ctl -d1 --get-fmt-video"
# Call OS script or not, close this in WINDOWS
callOS = 1
# NetworkTable Name
networkTableName = "visiontable"
# Camera Properties
camera = { 'HFOV' : 53.50, # 80.0, Horizontal FOV of the camera, see camera datasheet
'VFOV' : 41.41, # 64.0, Vertical FOV of the camera, see camera datasheet
'Brightness' : 1, # Brightness of the image
'Contrast' : 1000, # Contrast of the image
'HeightDiff' : 15, # Height difference between camera and target
'MountAngle' : -5, # Mounting angle of the camera need minus sign if pointing downwards
'WidthSize' : 320, # Resized image width size in pixels (image becomes square)
'HeightSize' : 240, # Resized image height size in pixels (image becomes square)
'FPS' : 15, # FPS of the camera
'AngleAcc' : 360, # 5 is normally used, you can use 360 to let the code ignore accuracy
'SetSize' : 0, # Set size of the camera with cap prop
'DoCrop' : 0, # Crop the image or don't
'DoResize' : 1, # Resize the image or don't
'CropXLow' : 0, # Lowest Point in X axis to be cropped
'CropYLow' : 125, # Lowest Point in Y axis to be cropped
'ColorSpace' : 'HSV', # Which color space to use BGR, HSV or Gray
'Gray_low' : 127, # Lower Gray value to be filtered
'Gray_high' : 255, # Higher Gray value to be filtered
'H_low' : 13, # Lower Hue value to be filtered, 55
'H_high' : 255, # Higher Hue to be filtered
'S_low' : 25, # Lower Saturation to be filtered, 97
'S_high' : 255, # Higher Saturation to be filtered
'V_low' : 24, # Lower Value to be filtered, 177
'V_high' : 255, # Higher Value to be filtered
'B_low' : 5, # Lower Blue value to be filtered
'B_high' : 95, # Higher Blue value to be filtered
'G_low' : 135, # Lower Green value to be filtered
'G_high' : 255, # Higher Green value to be filtered
'R_low' : 121, # Lower Red value to be filtered
'R_high' : 181 # Higher Red value to be filtered
}
filter = { 'MinArea' : 200, # Minimum value of area filter in pixels
'MaxArea' : 5000 # Maximum value of area filter in pixels
}
|
debug = 1
create_trackbars = 1
display = 1
image_type = 'Video'
image_source = 0
ip_address = '10.99.99.2'
os_script = 'v4l2-ctl --device /dev/video0 -c auto_exposure=1 -c exposure_auto_priority=0 -c exposure_time_absolute=20 --set-fmt-video=width=160,height=120,pixelformat=MJPG -p 15 && v4l2-ctl -d1 --get-fmt-video'
call_os = 1
network_table_name = 'visiontable'
camera = {'HFOV': 53.5, 'VFOV': 41.41, 'Brightness': 1, 'Contrast': 1000, 'HeightDiff': 15, 'MountAngle': -5, 'WidthSize': 320, 'HeightSize': 240, 'FPS': 15, 'AngleAcc': 360, 'SetSize': 0, 'DoCrop': 0, 'DoResize': 1, 'CropXLow': 0, 'CropYLow': 125, 'ColorSpace': 'HSV', 'Gray_low': 127, 'Gray_high': 255, 'H_low': 13, 'H_high': 255, 'S_low': 25, 'S_high': 255, 'V_low': 24, 'V_high': 255, 'B_low': 5, 'B_high': 95, 'G_low': 135, 'G_high': 255, 'R_low': 121, 'R_high': 181}
filter = {'MinArea': 200, 'MaxArea': 5000}
|
#! /usr/bin/env python3
"""Context files must contain a 'main' function.
The return from the main function should be the resulting text"""
def main(params):
if hasattr(params,'time'):
# 1e6 steps per ns
steps = int(params.time * 1e6)
else:
steps = 10000
return steps
|
"""Context files must contain a 'main' function.
The return from the main function should be the resulting text"""
def main(params):
if hasattr(params, 'time'):
steps = int(params.time * 1000000.0)
else:
steps = 10000
return steps
|
class NamingUtils(object):
""" A collection of utilities related to element naming. """
@staticmethod
def CompareNames(nameA, nameB):
"""
CompareNames(nameA: str,nameB: str) -> int
Compares two object name strings using Revit's comparison rules.
nameA: The first object name to compare.
nameB: The second object name to compare.
Returns: An integer indicating the result of the lexical comparison between the two
names.
Less than zero if nameA comes before nameB in the ordering,zero if
nameA and nameB are equivalent,
and greater than zero if nameA is comes
after nameB in the ordering.
"""
pass
@staticmethod
def IsValidName(string):
"""
IsValidName(string: str) -> bool
Identifies if the input string is valid for use as an object name in Revit.
string: The name to validate.
Returns: True if the name is valid for use as a name in Revit,false if it contains
prohibited characters and is invalid.
"""
pass
__all__ = [
"CompareNames",
"IsValidName",
]
|
class Namingutils(object):
""" A collection of utilities related to element naming. """
@staticmethod
def compare_names(nameA, nameB):
"""
CompareNames(nameA: str,nameB: str) -> int
Compares two object name strings using Revit's comparison rules.
nameA: The first object name to compare.
nameB: The second object name to compare.
Returns: An integer indicating the result of the lexical comparison between the two
names.
Less than zero if nameA comes before nameB in the ordering,zero if
nameA and nameB are equivalent,
and greater than zero if nameA is comes
after nameB in the ordering.
"""
pass
@staticmethod
def is_valid_name(string):
"""
IsValidName(string: str) -> bool
Identifies if the input string is valid for use as an object name in Revit.
string: The name to validate.
Returns: True if the name is valid for use as a name in Revit,false if it contains
prohibited characters and is invalid.
"""
pass
__all__ = ['CompareNames', 'IsValidName']
|
# Description: Class Based Decorators
"""
### Note
* If you want to maintain some sort of state and/or just make your code more confusing, use class based decorators.
"""
class ClassBasedDecorator(object):
def __init__(self, function_to_decorate):
print("INIT ClassBasedDecorator")
self.function_to_decorate = function_to_decorate
def __call__(self, *args, **kwargs):
print("CALL ClassBasedDecorator")
return self.function_to_decorate(*args, **kwargs)
# Call Class Based Decorator
@ClassBasedDecorator
def function_1(*args):
for arg in args:
print(arg)
def function_2(*args):
for arg in args:
print(arg)
if __name__ == '__main__':
function_1(1, 2, 3)
# Call Class Based Decorator - Alternate way
function_2 = ClassBasedDecorator(function_2)
function_2(1, 2, 3)
|
"""
### Note
* If you want to maintain some sort of state and/or just make your code more confusing, use class based decorators.
"""
class Classbaseddecorator(object):
def __init__(self, function_to_decorate):
print('INIT ClassBasedDecorator')
self.function_to_decorate = function_to_decorate
def __call__(self, *args, **kwargs):
print('CALL ClassBasedDecorator')
return self.function_to_decorate(*args, **kwargs)
@ClassBasedDecorator
def function_1(*args):
for arg in args:
print(arg)
def function_2(*args):
for arg in args:
print(arg)
if __name__ == '__main__':
function_1(1, 2, 3)
function_2 = class_based_decorator(function_2)
function_2(1, 2, 3)
|
# Task 09. Hello, France
def validate_price(items_and_prices):
item = items_and_prices.split('->')[0]
prices = float(items_and_prices.split('->')[1])
if item == 'Clothes' and prices <= 50 or \
item == 'Shoes' and prices <= 35.00 or \
item == 'Accessories' and prices <= 20.50:
return True
return False
items_and_prices = input().split('|')
budget = float(input())
initial_budget = budget
new_prices = []
for item in items_and_prices:
item_price = float(item.split('->')[1])
if budget - item_price < 0:
continue
if validate_price(item):
budget -= item_price
new_price = item_price + (item_price * 0.40)
new_prices.append(new_price)
earned = sum(new_prices)
profit = budget + (earned-initial_budget)
budget += earned
if budget >= 150:
result = 'Hello, France!'
else:
result = 'Time to go.'
print(' '.join([f'{x:.2f}' for x in new_prices]))
print(f'Profit: {profit:.2f}')
print(result)
|
def validate_price(items_and_prices):
item = items_and_prices.split('->')[0]
prices = float(items_and_prices.split('->')[1])
if item == 'Clothes' and prices <= 50 or (item == 'Shoes' and prices <= 35.0) or (item == 'Accessories' and prices <= 20.5):
return True
return False
items_and_prices = input().split('|')
budget = float(input())
initial_budget = budget
new_prices = []
for item in items_and_prices:
item_price = float(item.split('->')[1])
if budget - item_price < 0:
continue
if validate_price(item):
budget -= item_price
new_price = item_price + item_price * 0.4
new_prices.append(new_price)
earned = sum(new_prices)
profit = budget + (earned - initial_budget)
budget += earned
if budget >= 150:
result = 'Hello, France!'
else:
result = 'Time to go.'
print(' '.join([f'{x:.2f}' for x in new_prices]))
print(f'Profit: {profit:.2f}')
print(result)
|
{
'name': 'Clean Theme',
'description': 'Clean Theme',
'category': 'Theme/Services',
'summary': 'Corporate, Business, Tech, Services',
'sequence': 120,
'version': '2.0',
'author': 'Odoo S.A.',
'depends': ['theme_common', 'website_animate'],
'data': [
'views/assets.xml',
'views/image_content.xml',
'views/snippets/s_cover.xml',
'views/snippets/s_carousel.xml',
'views/snippets/s_text_image.xml',
'views/snippets/s_three_columns.xml',
'views/snippets/s_call_to_action.xml',
],
'images': [
'static/description/Clean_description.jpg',
'static/description/clean_screenshot.jpg',
],
'license': 'LGPL-3',
'live_test_url': 'https://theme-clean.odoo.com',
}
|
{'name': 'Clean Theme', 'description': 'Clean Theme', 'category': 'Theme/Services', 'summary': 'Corporate, Business, Tech, Services', 'sequence': 120, 'version': '2.0', 'author': 'Odoo S.A.', 'depends': ['theme_common', 'website_animate'], 'data': ['views/assets.xml', 'views/image_content.xml', 'views/snippets/s_cover.xml', 'views/snippets/s_carousel.xml', 'views/snippets/s_text_image.xml', 'views/snippets/s_three_columns.xml', 'views/snippets/s_call_to_action.xml'], 'images': ['static/description/Clean_description.jpg', 'static/description/clean_screenshot.jpg'], 'license': 'LGPL-3', 'live_test_url': 'https://theme-clean.odoo.com'}
|
class ValidationException(Exception):
pass
class NeedsGridType(ValidationException):
def __init__(self, ghost_zones=0, fields=None):
self.ghost_zones = ghost_zones
self.fields = fields
def __str__(self):
return f"({self.ghost_zones}, {self.fields})"
class NeedsOriginalGrid(NeedsGridType):
def __init__(self):
self.ghost_zones = 0
class NeedsDataField(ValidationException):
def __init__(self, missing_fields):
self.missing_fields = missing_fields
def __str__(self):
return f"({self.missing_fields})"
class NeedsProperty(ValidationException):
def __init__(self, missing_properties):
self.missing_properties = missing_properties
def __str__(self):
return f"({self.missing_properties})"
class NeedsParameter(ValidationException):
def __init__(self, missing_parameters):
self.missing_parameters = missing_parameters
def __str__(self):
return f"({self.missing_parameters})"
class NeedsConfiguration(ValidationException):
def __init__(self, parameter, value):
self.parameter = parameter
self.value = value
def __str__(self):
return f"(Needs {self.parameter} = {self.value})"
class FieldUnitsError(Exception):
pass
|
class Validationexception(Exception):
pass
class Needsgridtype(ValidationException):
def __init__(self, ghost_zones=0, fields=None):
self.ghost_zones = ghost_zones
self.fields = fields
def __str__(self):
return f'({self.ghost_zones}, {self.fields})'
class Needsoriginalgrid(NeedsGridType):
def __init__(self):
self.ghost_zones = 0
class Needsdatafield(ValidationException):
def __init__(self, missing_fields):
self.missing_fields = missing_fields
def __str__(self):
return f'({self.missing_fields})'
class Needsproperty(ValidationException):
def __init__(self, missing_properties):
self.missing_properties = missing_properties
def __str__(self):
return f'({self.missing_properties})'
class Needsparameter(ValidationException):
def __init__(self, missing_parameters):
self.missing_parameters = missing_parameters
def __str__(self):
return f'({self.missing_parameters})'
class Needsconfiguration(ValidationException):
def __init__(self, parameter, value):
self.parameter = parameter
self.value = value
def __str__(self):
return f'(Needs {self.parameter} = {self.value})'
class Fieldunitserror(Exception):
pass
|
#import sys
#file = sys.stdin
file = open( r".\data\nestedlists.txt" )
data = file.read().strip().split()[1:]
records = [ [data[i], float(data[i+1])] for i in range(0, len(data), 2) ]
print(records)
low = min([r[1] for r in records])
dif = min([r[1] - low for r in records if r[1] != low])
print(dif)
names = [ r[0] for r in records if r[1]-dif == low]
[print(name) for name in sorted(names)]
#from decimal import Decimal
#from itertools import groupby, islice
#from operator import itemgetter
#a = []
#for i in range(int(input())):
# x, y = (input(), Decimal(input()))
# a.append((y, x))
#a.sort()
#for k, v in islice(groupby(a, key=itemgetter(0)), 1, 2):
# for x in v:
# print(x[1])
|
file = open('.\\data\\nestedlists.txt')
data = file.read().strip().split()[1:]
records = [[data[i], float(data[i + 1])] for i in range(0, len(data), 2)]
print(records)
low = min([r[1] for r in records])
dif = min([r[1] - low for r in records if r[1] != low])
print(dif)
names = [r[0] for r in records if r[1] - dif == low]
[print(name) for name in sorted(names)]
|
class ApiOperations:
"""
Class to extract defined parts from the OpenApiSpecs definition json
"""
def __init__(self, resource, parts=None):
"""
Extract defined parts out of paths/<endpoint> (resource) in the OpenApiSpecs definition
:param resource: source to be extracted from
:param parts: single bloc names to be extracted
"""
if parts is None:
parts = ["parameters", "responses", "requestBody"]
self.operations = {}
default_operation = {}
for part in parts:
default_operation[part] = None
for (method, details) in resource.items():
self.operations[method] = default_operation.copy()
for part in parts:
if part in details:
self.operations[method][part] = details[part]
|
class Apioperations:
"""
Class to extract defined parts from the OpenApiSpecs definition json
"""
def __init__(self, resource, parts=None):
"""
Extract defined parts out of paths/<endpoint> (resource) in the OpenApiSpecs definition
:param resource: source to be extracted from
:param parts: single bloc names to be extracted
"""
if parts is None:
parts = ['parameters', 'responses', 'requestBody']
self.operations = {}
default_operation = {}
for part in parts:
default_operation[part] = None
for (method, details) in resource.items():
self.operations[method] = default_operation.copy()
for part in parts:
if part in details:
self.operations[method][part] = details[part]
|
"""
MIRA API config
"""
MODELS = [
{
"endpoint_name": "mira-large",
"classes": ["fox", "skunk", "empty"]
},
{
"endpoint_name": "mira-small",
"classes": ["rodent", "empty"]
}
]
HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "POST"
}
|
"""
MIRA API config
"""
models = [{'endpoint_name': 'mira-large', 'classes': ['fox', 'skunk', 'empty']}, {'endpoint_name': 'mira-small', 'classes': ['rodent', 'empty']}]
headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST'}
|
class Int_code:
def __init__(self, s, inputs):
memory = {}
nrs = map(int, s.split(","))
for i, x in enumerate(nrs):
memory[i] = x
self.memory = memory
self.inputs = inputs
def set(self, i, x):
self.memory[i] = x
def one(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = a + b
def two(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = a * b
def three(self, a, modes):
x = self.inputs.pop(0)
self.memory[a] = x
def four(self, a, modes):
if modes % 10 == 0:
a = self.memory[a]
print(a)
def five(self, a, b, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
if a != 0:
return (True, b)
else:
return (False, 0)
def six(self, a, b, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
if a == 0:
return (True, b)
else:
return (False, 0)
def seven(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = 1 if (a < b) else 0
def eight(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = 1 if (a == b) else 0
def run(self, start):
i = start
while True:
c = self.memory[i]
modes = c // 100
c %= 100
# print(i, self.memory[i])
if c == 99:
break
elif c == 1:
self.one(self.memory[i+1], self.memory[i+2], self.memory[i+3], modes)
i += 4
elif c == 2:
self.two(self.memory[i+1], self.memory[i+2], self.memory[i+3], modes)
i += 4
elif c == 3:
self.three(self.memory[i+1], modes)
i += 2
elif c == 4:
self.four(self.memory[i+1], modes)
i += 2
elif c == 5:
sol = self.five(self.memory[i+1], self.memory[i+2], modes)
if sol[0]:
i = sol[1]
else:
i += 3
elif c == 6:
sol = self.six(self.memory[i+1], self.memory[i+2], modes)
if sol[0]:
i = sol[1]
else:
i += 3
elif c == 7:
self.seven(self.memory[i+1], self.memory[i+2], self.memory[i+3], modes)
i += 4
elif c == 8:
self.eight(self.memory[i+1], self.memory[i+2], self.memory[i+3], modes)
i += 4
return self.memory[0]
start = input()
# part one
inputs_1 = [1]
computer = Int_code(start, inputs_1)
computer.run(0)
# part two
inputs_2 = [5]
computer = Int_code(start, inputs_2)
computer.run(0)
# # test
# inputs = [3]
# computer = Int_code(start, inputs)
# computer.run(0)
|
class Int_Code:
def __init__(self, s, inputs):
memory = {}
nrs = map(int, s.split(','))
for (i, x) in enumerate(nrs):
memory[i] = x
self.memory = memory
self.inputs = inputs
def set(self, i, x):
self.memory[i] = x
def one(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = a + b
def two(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = a * b
def three(self, a, modes):
x = self.inputs.pop(0)
self.memory[a] = x
def four(self, a, modes):
if modes % 10 == 0:
a = self.memory[a]
print(a)
def five(self, a, b, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
if a != 0:
return (True, b)
else:
return (False, 0)
def six(self, a, b, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
if a == 0:
return (True, b)
else:
return (False, 0)
def seven(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = 1 if a < b else 0
def eight(self, a, b, c, modes):
if modes % 10 == 0:
a = self.memory[a]
modes //= 10
if modes % 10 == 0:
b = self.memory[b]
self.memory[c] = 1 if a == b else 0
def run(self, start):
i = start
while True:
c = self.memory[i]
modes = c // 100
c %= 100
if c == 99:
break
elif c == 1:
self.one(self.memory[i + 1], self.memory[i + 2], self.memory[i + 3], modes)
i += 4
elif c == 2:
self.two(self.memory[i + 1], self.memory[i + 2], self.memory[i + 3], modes)
i += 4
elif c == 3:
self.three(self.memory[i + 1], modes)
i += 2
elif c == 4:
self.four(self.memory[i + 1], modes)
i += 2
elif c == 5:
sol = self.five(self.memory[i + 1], self.memory[i + 2], modes)
if sol[0]:
i = sol[1]
else:
i += 3
elif c == 6:
sol = self.six(self.memory[i + 1], self.memory[i + 2], modes)
if sol[0]:
i = sol[1]
else:
i += 3
elif c == 7:
self.seven(self.memory[i + 1], self.memory[i + 2], self.memory[i + 3], modes)
i += 4
elif c == 8:
self.eight(self.memory[i + 1], self.memory[i + 2], self.memory[i + 3], modes)
i += 4
return self.memory[0]
start = input()
inputs_1 = [1]
computer = int_code(start, inputs_1)
computer.run(0)
inputs_2 = [5]
computer = int_code(start, inputs_2)
computer.run(0)
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='OTEMobileNetV3',
mode='small',
width_mult=1.0),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='NonLinearClsHead',
num_classes=1000,
in_channels=576,
hid_channels=1024,
act_cfg=dict(type='HSwish'),
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
|
model = dict(type='ImageClassifier', backbone=dict(type='OTEMobileNetV3', mode='small', width_mult=1.0), neck=dict(type='GlobalAveragePooling'), head=dict(type='NonLinearClsHead', num_classes=1000, in_channels=576, hid_channels=1024, act_cfg=dict(type='HSwish'), loss=dict(type='CrossEntropyLoss', loss_weight=1.0)))
|
class BaseNode:
pass
class Node(BaseNode):
def __init__(self, offset, name=None, **opts):
self.offset = offset
self.end_offset = None
self.name = name
self.nodes = []
self.opts = opts
def __as_dict__(self):
return {"name": self.name, "nodes": [node.__as_dict__() for node in self.nodes]}
class Token(BaseNode):
def __init__(self, offset, value):
self.offset = offset
self.value = value
def __as_dict__(self):
return {"offset": self.offset, "value": self.value}
class NodeInspector:
def __init__(self, target):
if not isinstance(target, Node):
raise TypeError("target should be an instance of Node, not " + target.__class__)
self.target = target
self.names = {}
self.values = []
for node in target.nodes:
if isinstance(node, Node):
if node.name in self.names:
self.names[node.name] += [node]
else:
self.names[node.name] = [node]
else:
self.values.append(node)
if target.opts.get("flatten"):
if target.opts.get("as_list"):
if len(self.names) >= 1:
nodes = list(self.names.values())[0]
else:
nodes = []
self.mask = [NodeInspector(node).mask for node in nodes]
elif len(self.names) >= 1:
nodes = list(self.names.values())[0]
self.mask = NodeInspector(nodes[0]).mask
else:
self.mask = None
# elif len(self.names) == 0 and len(self.values) == 1:
# self.mask = self.values[0]
else:
self.mask = NodeMask(self)
class NodeMask:
def __init__(self, inspector):
super().__setattr__("_inspector", inspector)
super().__setattr__("_offset", inspector.target.offset)
super().__setattr__("_end_offset", inspector.target.end_offset)
super().__setattr__("_name", inspector.target.name)
def __str__(self):
target = self._inspector.target
n = target.name
v = len(self._inspector.values)
s = ", ".join(("{}[{}]".format(k, len(v)) for k,v in self._inspector.names))
return "<NodeMask name={}; values=[{}], nodes=[{}]>".format(n, v, s)
def __getattr__(self, name):
names = self._inspector.names
nodes = names.get(name)
if nodes:
node = NodeInspector(nodes[0]).mask
else:
node = None
return node
def __setattr__(self, name, value):
raise AttributeError
def __getitem__(self, i):
return self._inspector.values[i]
def __len__(self):
return len(self._inspector.values)
def __iter__(self):
return iter(self._inspector.values)
def __as_dict__(self):
return self._inspector.target.__as_dict__()
|
class Basenode:
pass
class Node(BaseNode):
def __init__(self, offset, name=None, **opts):
self.offset = offset
self.end_offset = None
self.name = name
self.nodes = []
self.opts = opts
def __as_dict__(self):
return {'name': self.name, 'nodes': [node.__as_dict__() for node in self.nodes]}
class Token(BaseNode):
def __init__(self, offset, value):
self.offset = offset
self.value = value
def __as_dict__(self):
return {'offset': self.offset, 'value': self.value}
class Nodeinspector:
def __init__(self, target):
if not isinstance(target, Node):
raise type_error('target should be an instance of Node, not ' + target.__class__)
self.target = target
self.names = {}
self.values = []
for node in target.nodes:
if isinstance(node, Node):
if node.name in self.names:
self.names[node.name] += [node]
else:
self.names[node.name] = [node]
else:
self.values.append(node)
if target.opts.get('flatten'):
if target.opts.get('as_list'):
if len(self.names) >= 1:
nodes = list(self.names.values())[0]
else:
nodes = []
self.mask = [node_inspector(node).mask for node in nodes]
elif len(self.names) >= 1:
nodes = list(self.names.values())[0]
self.mask = node_inspector(nodes[0]).mask
else:
self.mask = None
else:
self.mask = node_mask(self)
class Nodemask:
def __init__(self, inspector):
super().__setattr__('_inspector', inspector)
super().__setattr__('_offset', inspector.target.offset)
super().__setattr__('_end_offset', inspector.target.end_offset)
super().__setattr__('_name', inspector.target.name)
def __str__(self):
target = self._inspector.target
n = target.name
v = len(self._inspector.values)
s = ', '.join(('{}[{}]'.format(k, len(v)) for (k, v) in self._inspector.names))
return '<NodeMask name={}; values=[{}], nodes=[{}]>'.format(n, v, s)
def __getattr__(self, name):
names = self._inspector.names
nodes = names.get(name)
if nodes:
node = node_inspector(nodes[0]).mask
else:
node = None
return node
def __setattr__(self, name, value):
raise AttributeError
def __getitem__(self, i):
return self._inspector.values[i]
def __len__(self):
return len(self._inspector.values)
def __iter__(self):
return iter(self._inspector.values)
def __as_dict__(self):
return self._inspector.target.__as_dict__()
|
def foo():
print("I'm a lovely foo()-function")
print(foo)
# <function foo at 0x7f9b75de3f28>
print(foo.__class__)
# <class 'function'>
bar = foo
bar()
# I'm a lovely foo()-function
print(bar.__name__)
# foo
def do_something(what):
"""Executes a function
:param what: name of the function to be executed
"""
what()
do_something(foo)
# I'm a lovely foo()-function
def try_me(self):
print('I am '+self.name)
print("I was created by " + self.creator)
print("This is wat I do")
self()
# a function is an object with attributed and methods
setattr(foo, 'name', 'foo')
foo.creator = "Hans"
foo.print = try_me
foo.print(foo)
"""
I am foo
I was created by Hans
This is wat I do
I'm a lovely foo()-function
"""
print(foo)
# <function foo at 0x7f9b75de3f28>
|
def foo():
print("I'm a lovely foo()-function")
print(foo)
print(foo.__class__)
bar = foo
bar()
print(bar.__name__)
def do_something(what):
"""Executes a function
:param what: name of the function to be executed
"""
what()
do_something(foo)
def try_me(self):
print('I am ' + self.name)
print('I was created by ' + self.creator)
print('This is wat I do')
self()
setattr(foo, 'name', 'foo')
foo.creator = 'Hans'
foo.print = try_me
foo.print(foo)
"\nI am foo\nI was created by Hans\nThis is wat I do\nI'm a lovely foo()-function\n"
print(foo)
|
# Copyright 2019 The Bazel 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.
"""Implementation of tvOS test rules."""
load(
"@build_bazel_rules_apple//apple/internal/testing:apple_test_rule_support.bzl",
"apple_test_rule_support",
)
load(
"@build_bazel_rules_apple//apple/internal:apple_product_type.bzl",
"apple_product_type",
)
load(
"@build_bazel_rules_apple//apple/internal:rule_factory.bzl",
"rule_factory",
)
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"TvosXcTestBundleInfo",
)
def _tvos_ui_test_impl(ctx):
"""Implementation of tvos_ui_test."""
return apple_test_rule_support.apple_test_impl(
ctx,
"xcuitest",
extra_providers = [TvosXcTestBundleInfo()],
)
def _tvos_unit_test_impl(ctx):
"""Implementation of tvos_unit_test."""
return apple_test_rule_support.apple_test_impl(
ctx,
"xctest",
extra_providers = [TvosXcTestBundleInfo()],
)
tvos_ui_test = rule_factory.create_apple_bundling_rule(
implementation = _tvos_ui_test_impl,
platform_type = str(apple_common.platform_type.tvos),
product_type = apple_product_type.ui_test_bundle,
doc = "Builds and bundles a tvOS UI Test Bundle.",
)
tvos_unit_test = rule_factory.create_apple_bundling_rule(
implementation = _tvos_unit_test_impl,
platform_type = str(apple_common.platform_type.tvos),
product_type = apple_product_type.unit_test_bundle,
doc = "Builds and bundles a tvOS Unit Test Bundle.",
)
|
"""Implementation of tvOS test rules."""
load('@build_bazel_rules_apple//apple/internal/testing:apple_test_rule_support.bzl', 'apple_test_rule_support')
load('@build_bazel_rules_apple//apple/internal:apple_product_type.bzl', 'apple_product_type')
load('@build_bazel_rules_apple//apple/internal:rule_factory.bzl', 'rule_factory')
load('@build_bazel_rules_apple//apple:providers.bzl', 'TvosXcTestBundleInfo')
def _tvos_ui_test_impl(ctx):
"""Implementation of tvos_ui_test."""
return apple_test_rule_support.apple_test_impl(ctx, 'xcuitest', extra_providers=[tvos_xc_test_bundle_info()])
def _tvos_unit_test_impl(ctx):
"""Implementation of tvos_unit_test."""
return apple_test_rule_support.apple_test_impl(ctx, 'xctest', extra_providers=[tvos_xc_test_bundle_info()])
tvos_ui_test = rule_factory.create_apple_bundling_rule(implementation=_tvos_ui_test_impl, platform_type=str(apple_common.platform_type.tvos), product_type=apple_product_type.ui_test_bundle, doc='Builds and bundles a tvOS UI Test Bundle.')
tvos_unit_test = rule_factory.create_apple_bundling_rule(implementation=_tvos_unit_test_impl, platform_type=str(apple_common.platform_type.tvos), product_type=apple_product_type.unit_test_bundle, doc='Builds and bundles a tvOS Unit Test Bundle.')
|
n, m = [int(e) for e in input().split()]
mat = []
for i in range(n):
j = [int(e) for e in input().split()]
mat.append(j)
for i in range(n):
for j in range(m):
if mat[i][j] == 0:
if i == 0:
if mat[i][j+1] == 1 and mat[i][j-1] == 1 and mat[i+1][j] == 1:
print(i, j)
exit()
if j == 0:
if mat[i+1][j] == 1 and mat[i-1][j] == 1 and mat[i][j+1] == 1:
print(i, j)
exit()
if i == n-1:
if mat[i][j+1] == 1 and mat[i][j-1] == 1 and mat[i-1][j] == 1:
print(i, j)
exit()
if j == m-1:
if mat[i+1][j] == 1 and mat[i-1][j] == 1 and mat[i][j-1] == 1:
print(i, j)
exit()
if mat[i+1][j] == 1 and mat[i-1][j] == 1 and mat[i][j+1] == 1 and mat[i][j-1] == 1:
print(i, j)
exit()
print(0, 0)
|
(n, m) = [int(e) for e in input().split()]
mat = []
for i in range(n):
j = [int(e) for e in input().split()]
mat.append(j)
for i in range(n):
for j in range(m):
if mat[i][j] == 0:
if i == 0:
if mat[i][j + 1] == 1 and mat[i][j - 1] == 1 and (mat[i + 1][j] == 1):
print(i, j)
exit()
if j == 0:
if mat[i + 1][j] == 1 and mat[i - 1][j] == 1 and (mat[i][j + 1] == 1):
print(i, j)
exit()
if i == n - 1:
if mat[i][j + 1] == 1 and mat[i][j - 1] == 1 and (mat[i - 1][j] == 1):
print(i, j)
exit()
if j == m - 1:
if mat[i + 1][j] == 1 and mat[i - 1][j] == 1 and (mat[i][j - 1] == 1):
print(i, j)
exit()
if mat[i + 1][j] == 1 and mat[i - 1][j] == 1 and (mat[i][j + 1] == 1) and (mat[i][j - 1] == 1):
print(i, j)
exit()
print(0, 0)
|
CONNECTION_STRING = '/@'
CHUNK_SIZE = 100
BORDER_QTY = 5 # minimun matches per year per player for reload player
ATP_URL_PREFIX = 'http://www.atpworldtour.com'
DC_URL_PREFIX = 'https://www.daviscup.com'
ATP_TOURNAMENT_SERIES = ('gs', '1000', 'atp', 'ch')
DC_TOURNAMENT_SERIES = ('dc',)
DURATION_IN_DAYS = 18
ATP_CSV_PATH = ''
DC_CSV_PATH = ''
SLEEP_DURATION = 10
COUNTRY_CODE_MAP = {
'LIB': 'LBN',
'SIN': 'SGP',
'bra': 'BRA',
'ROM': 'ROU'}
COUNTRY_NAME_MAP = {
'Slovak Republic': 'Slovakia',
'Bosnia-Herzegovina': 'Bosnia and Herzegovina'}
INDOOR_OUTDOOR_MAP = {
'I': 'Indoor',
'O': 'Outdoor'}
SURFACE_MAP = {
'H': 'Hard',
'C': 'Clay',
'A': 'Carpet',
'G': 'Grass'}
STADIE_CODES_MAP = {
'Finals': 'F',
'Final': 'F',
'Semi-Finals': 'SF',
'Semifinals': 'SF',
'Quarter-Finals': 'QF',
'Quarterfinals': 'QF',
'Round of 16': 'R16',
'Round of 32': 'R32',
'Round of 64': 'R64',
'Round of 128': 'R128',
'Round Robin': 'RR',
'Olympic Bronze': 'BR',
'3rd Round Qualifying': 'Q3',
'2nd Round Qualifying': 'Q2',
'1st Round Qualifying': 'Q1'}
|
connection_string = '/@'
chunk_size = 100
border_qty = 5
atp_url_prefix = 'http://www.atpworldtour.com'
dc_url_prefix = 'https://www.daviscup.com'
atp_tournament_series = ('gs', '1000', 'atp', 'ch')
dc_tournament_series = ('dc',)
duration_in_days = 18
atp_csv_path = ''
dc_csv_path = ''
sleep_duration = 10
country_code_map = {'LIB': 'LBN', 'SIN': 'SGP', 'bra': 'BRA', 'ROM': 'ROU'}
country_name_map = {'Slovak Republic': 'Slovakia', 'Bosnia-Herzegovina': 'Bosnia and Herzegovina'}
indoor_outdoor_map = {'I': 'Indoor', 'O': 'Outdoor'}
surface_map = {'H': 'Hard', 'C': 'Clay', 'A': 'Carpet', 'G': 'Grass'}
stadie_codes_map = {'Finals': 'F', 'Final': 'F', 'Semi-Finals': 'SF', 'Semifinals': 'SF', 'Quarter-Finals': 'QF', 'Quarterfinals': 'QF', 'Round of 16': 'R16', 'Round of 32': 'R32', 'Round of 64': 'R64', 'Round of 128': 'R128', 'Round Robin': 'RR', 'Olympic Bronze': 'BR', '3rd Round Qualifying': 'Q3', '2nd Round Qualifying': 'Q2', '1st Round Qualifying': 'Q1'}
|
def digitsProduct(product):
"""
Given an integer product, find the smallest
positive (i.e. greater than 0) integer the
product of whose digits is equal to product.
If there is no such integer, return -1 instead.
Time Complexity: O(inf)
Space Complexity: O(1)
"""
number = 1
while True:
p = 1
digits = [int(x) for x in str(number)]
for n in digits:
p = p * n
if number > 10000:
return -1
if p == product:
return number
number += 1
|
def digits_product(product):
"""
Given an integer product, find the smallest
positive (i.e. greater than 0) integer the
product of whose digits is equal to product.
If there is no such integer, return -1 instead.
Time Complexity: O(inf)
Space Complexity: O(1)
"""
number = 1
while True:
p = 1
digits = [int(x) for x in str(number)]
for n in digits:
p = p * n
if number > 10000:
return -1
if p == product:
return number
number += 1
|
# 15. replace() -> Altera determinado valor de uma string por outro. Troca uma string por outra.
texto = 'vou Treinar todo Dia Python'
print(texto.replace('vou','Vamos'))
print(texto.replace('Python','Algoritmos'))
|
texto = 'vou Treinar todo Dia Python'
print(texto.replace('vou', 'Vamos'))
print(texto.replace('Python', 'Algoritmos'))
|
"""
Singly linked lists
-------------------
- is a list with only 1 pointer between 2 successive nodes
- It can only be traversed in a single direction: from the 1st node in the list to the last node
Several problems
----------------
It requires too much manual work by the programmer
It is too error-prone (this is a consequence of the first point)
Too much of the inner workings of the list is exposed to the programmer
"""
"""Singly linked list implementation"""
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
n1 = Node("eggs")
n2 = Node("spam")
n3 = Node("ham")
# Link the nodes together so that they form a chain
n1.next = n2
n2.next = n3
# To traverse the list: start by setting the variable current to the first item in the list:
# Loop: print the current element; set current to point to the next element in the list; until reaching the end of list
current = n1
while current:
print(current.data)
current = current.next
print("\n")
"""
Singly linked list class
-------------------------
Create a very simple class to hold our list. Start with a constructor that holds a reference to the very first node in
the list. Since this list is initially empty, start by setting this reference to None:
Append
-------
- append items to the list(insert operation):
- hide away the Node class. The user of our list class should really never have to interact with Node objects.
- Big problem: it has to traverse the entire list to find the insertion point => Ok few items in the list, but not to
add thousands of items. Each append will be slightly slower than the previous one
- Worst case running time of the append operation: O(n)
Faster append operation
--------------------------
- store, not only a reference to the first node in the list, but also a reference to the last node.
- Make sure the previous last node points to the new node, that is about to be appended to the list.
=> quickly append a new node at the end of the list.
- Reduced worst case running time: O(1).
Size of the list
-----------------
- counting the number of nodes: traverse the entire list and increase a counter as we go along
- works but list traversal is potentially an expensive operation that we should avoid
- Worst case running time: O(n) because of using a loop to count the number of nodes in the list
Better size of the list
-----------------------
- add a size member to the SinglyLinkedList class, initializing it to 0 in the constructor.
- Then increment size by one in the append method
- Reduced the worst case running time: O(1), because we are now only reading the size attribute of the node object
Improving list traversal
-------------------------
Still exposed to the Node class; need to use node.data to get the contents of the node and node.next to get next node.
But client code should never need to interact with Node objects => Create a method that returns a generator: iter()
Deleting nodes
--------------
Decide how to select a node for deletion: by an index number/ by the data the node contains? Here delete by the data
- to delete a node that is between 2 other nodes, make the previous node directly to the successor of its next node
- O(n) to delete a node
List search
------------
- check whether a list contains an item.
- each pass of the loop compares the current data to the data being searched for; if match: True returned, else: False
Clear a list
------------
Clear the pointers head and tail by setting them to None
By orphaning all the nodes at the tail and head pointers of the list => effect of orphaning all the nodes in between
"""
class SinglyLinkedListSlow:
def __init__(self):
self.tail = None
# Worst case running time: O(n)
def append(self, data):
# encapsulate data in a Node
# so that it now has the next pointer attribute
node = Node(data)
# check if there are any existing nodes in the list
# does self.tail point to a Node ?
if self.tail is None:
# if none, make the new node the first node of the list
self.tail = node
else:
# find the insertion point by traversing the list to the last node
# updating the next pointer of the last node to the new node.
current = self.tail
while current.next:
current = current.next
current.next = node
# Worst case running time: O(n)
def size(self):
count = 0
current = self.tail
while current:
count += 1
current = current.next
return count
#############################################################################
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0 # to compute size of list
# Worst case running time: O(1)
# append new nodes through self.head
# the self.tail variable points to the first node in the list
def append(self, data):
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.size += 1 # worst case running time: O(1)
def delete(self, data):
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.size -= 1
return
prev = current
current = current.next
# Traverse the list - iter() method yields the data member of the node
def iter(self):
current = self.tail
while current:
val = current.data
current = current.next
yield val
def search(self, data):
for node_data in self.iter():
if data == node_data:
return True
return False
# clear the entire list
def clear(self):
self.tail = None
self.head = None
# append a few items
words1 = SinglyLinkedListSlow()
words1.append('egg')
words1.append('ham')
words1.append('spam')
# append faster
words2 = SinglyLinkedList()
words2.append('egg')
words2.append('ham')
words2.append('spam')
# List traversal
current = words1.tail
while current:
print(current.data)
current = current.next
print("\n")
# List traversal using iter
for word in words2.iter():
print(word)
print("\n")
# Size of list
print(words1.size())
print(words2.size)
print("\n")
# Delete a node
words2.delete('ham')
for word in words2.iter():
print(word)
print(words2.size)
print('\n')
# Search for a node
print(words2.search('spam'))
|
"""
Singly linked lists
-------------------
- is a list with only 1 pointer between 2 successive nodes
- It can only be traversed in a single direction: from the 1st node in the list to the last node
Several problems
----------------
It requires too much manual work by the programmer
It is too error-prone (this is a consequence of the first point)
Too much of the inner workings of the list is exposed to the programmer
"""
'Singly linked list implementation'
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
n1 = node('eggs')
n2 = node('spam')
n3 = node('ham')
n1.next = n2
n2.next = n3
current = n1
while current:
print(current.data)
current = current.next
print('\n')
'\nSingly linked list class\n-------------------------\nCreate a very simple class to hold our list. Start with a constructor that holds a reference to the very first node in \nthe list. Since this list is initially empty, start by setting this reference to None:\n\nAppend \n-------\n- append items to the list(insert operation):\n- hide away the Node class. The user of our list class should really never have to interact with Node objects.\n- Big problem: it has to traverse the entire list to find the insertion point => Ok few items in the list, but not to \nadd thousands of items. Each append will be slightly slower than the previous one \n- Worst case running time of the append operation: O(n) \n\nFaster append operation\n--------------------------\n- store, not only a reference to the first node in the list, but also a reference to the last node. \n- Make sure the previous last node points to the new node, that is about to be appended to the list.\n=> quickly append a new node at the end of the list. \n- Reduced worst case running time: O(1). \n\nSize of the list\n-----------------\n- counting the number of nodes: traverse the entire list and increase a counter as we go along\n- works but list traversal is potentially an expensive operation that we should avoid \n- Worst case running time: O(n) because of using a loop to count the number of nodes in the list\n\nBetter size of the list\n-----------------------\n- add a size member to the SinglyLinkedList class, initializing it to 0 in the constructor. \n- Then increment size by one in the append method\n- Reduced the worst case running time: O(1), because we are now only reading the size attribute of the node object\n\n\nImproving list traversal\n-------------------------\nStill exposed to the Node class; need to use node.data to get the contents of the node and node.next to get next node. \nBut client code should never need to interact with Node objects => Create a method that returns a generator: iter()\n\n\nDeleting nodes\n--------------\nDecide how to select a node for deletion: by an index number/ by the data the node contains? Here delete by the data\n- to delete a node that is between 2 other nodes, make the previous node directly to the successor of its next node\n- O(n) to delete a node \n\nList search\n------------\n- check whether a list contains an item.\n- each pass of the loop compares the current data to the data being searched for; if match: True returned, else: False\n\n\nClear a list\n ------------\nClear the pointers head and tail by setting them to None\nBy orphaning all the nodes at the tail and head pointers of the list => effect of orphaning all the nodes in between\n'
class Singlylinkedlistslow:
def __init__(self):
self.tail = None
def append(self, data):
node = node(data)
if self.tail is None:
self.tail = node
else:
current = self.tail
while current.next:
current = current.next
current.next = node
def size(self):
count = 0
current = self.tail
while current:
count += 1
current = current.next
return count
class Singlylinkedlist:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def append(self, data):
node = node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node
self.size += 1
def delete(self, data):
current = self.tail
prev = self.tail
while current:
if current.data == data:
if current == self.tail:
self.tail = current.next
else:
prev.next = current.next
self.size -= 1
return
prev = current
current = current.next
def iter(self):
current = self.tail
while current:
val = current.data
current = current.next
yield val
def search(self, data):
for node_data in self.iter():
if data == node_data:
return True
return False
def clear(self):
self.tail = None
self.head = None
words1 = singly_linked_list_slow()
words1.append('egg')
words1.append('ham')
words1.append('spam')
words2 = singly_linked_list()
words2.append('egg')
words2.append('ham')
words2.append('spam')
current = words1.tail
while current:
print(current.data)
current = current.next
print('\n')
for word in words2.iter():
print(word)
print('\n')
print(words1.size())
print(words2.size)
print('\n')
words2.delete('ham')
for word in words2.iter():
print(word)
print(words2.size)
print('\n')
print(words2.search('spam'))
|
class Email:
def __init__(self):
self.from_email = ''
self.to_email = ''
self.subject = ''
self.contents = ''
def send_mail(self):
print('From: '+ self.from_email)
print('To: '+ self.to_email)
print('Subject: '+ self.subject)
print('Contents: '+ self.contents)
|
class Email:
def __init__(self):
self.from_email = ''
self.to_email = ''
self.subject = ''
self.contents = ''
def send_mail(self):
print('From: ' + self.from_email)
print('To: ' + self.to_email)
print('Subject: ' + self.subject)
print('Contents: ' + self.contents)
|
n, x = map(int, input().split())
ll = list(map(int, input().split()))
ans = 1
d_p = 0
d_c = 0
for i in range(n):
d_c = d_p + ll[i]
if d_c <= x:
ans += 1
d_p = d_c
print(ans)
|
(n, x) = map(int, input().split())
ll = list(map(int, input().split()))
ans = 1
d_p = 0
d_c = 0
for i in range(n):
d_c = d_p + ll[i]
if d_c <= x:
ans += 1
d_p = d_c
print(ans)
|
def fill_the_box(*args):
height = args[0]
length = args[1]
width = args[2]
cube_size = height * length * width
for i in range(3, len(args)):
if args[i] == "Finish":
return f"There is free space in the box. You could put {cube_size} more cubes."
if cube_size < args[i]:
cubes_left = args[i] - cube_size
for c in range(i + 1, len(args)):
if args[c] == "Finish":
break
cubes_left += args[c]
return f"No more free space! You have {cubes_left} more cubes."
cube_size -= args[i]
print(fill_the_box(2, 8, 2, 2, 1, 7, 3, 1, 5, "Finish"))
print(fill_the_box(5, 5, 2, 40, 11, 7, 3, 1, 5, "Finish"))
print(fill_the_box(10, 10, 10, 40, "Finish", 2, 15, 30))
|
def fill_the_box(*args):
height = args[0]
length = args[1]
width = args[2]
cube_size = height * length * width
for i in range(3, len(args)):
if args[i] == 'Finish':
return f'There is free space in the box. You could put {cube_size} more cubes.'
if cube_size < args[i]:
cubes_left = args[i] - cube_size
for c in range(i + 1, len(args)):
if args[c] == 'Finish':
break
cubes_left += args[c]
return f'No more free space! You have {cubes_left} more cubes.'
cube_size -= args[i]
print(fill_the_box(2, 8, 2, 2, 1, 7, 3, 1, 5, 'Finish'))
print(fill_the_box(5, 5, 2, 40, 11, 7, 3, 1, 5, 'Finish'))
print(fill_the_box(10, 10, 10, 40, 'Finish', 2, 15, 30))
|
#!/usr/bin/env python3
#Antonio Karlo Mijares
# return_text_value function
def return_text_value():
name = 'Terry'
greeting = 'Good Morning ' + name
return greeting
# return_number_value function
def return_number_value():
num1 = 10
num2 = 5
num3 = num1 + num2
return num3
# Main program
if __name__ == '__main__':
print('python code')
text = return_text_value()
print(text)
number = return_number_value()
print(str(number))
|
def return_text_value():
name = 'Terry'
greeting = 'Good Morning ' + name
return greeting
def return_number_value():
num1 = 10
num2 = 5
num3 = num1 + num2
return num3
if __name__ == '__main__':
print('python code')
text = return_text_value()
print(text)
number = return_number_value()
print(str(number))
|
{
"variables": {
"HEROKU%": '<!(echo $HEROKU)'
},
"targets": [
{
"target_name": "gif2webp",
"defines": [
],
"sources": [
"src/gif2webp.cpp",
"src/webp/example_util.cpp",
"src/webp/gif2webp_util.cpp",
"src/webp/gif2webpMain.cpp"
],
"conditions": [
[
'OS=="mac"',
{
"include_dirs": [
"/usr/local/include",
"src/webp"
],
"libraries": [
"-lwebp",
"-lwebpmux",
"-lgif"
]
}
],
[
'OS=="linux"',
{
"include_dirs": [
"/usr/local/include",
"src/webp"
],
"libraries": [
"-lwebp",
"-lwebpmux",
"-lgif"
]
}
]
]
}
]
}
|
{'variables': {'HEROKU%': '<!(echo $HEROKU)'}, 'targets': [{'target_name': 'gif2webp', 'defines': [], 'sources': ['src/gif2webp.cpp', 'src/webp/example_util.cpp', 'src/webp/gif2webp_util.cpp', 'src/webp/gif2webpMain.cpp'], 'conditions': [['OS=="mac"', {'include_dirs': ['/usr/local/include', 'src/webp'], 'libraries': ['-lwebp', '-lwebpmux', '-lgif']}], ['OS=="linux"', {'include_dirs': ['/usr/local/include', 'src/webp'], 'libraries': ['-lwebp', '-lwebpmux', '-lgif']}]]}]}
|
with open("day6_input.txt") as f:
initial_fish = list(map(int, f.readline().strip().split(",")))
fish = [0] * 9
for initial_f in initial_fish:
fish[initial_f] += 1
for day in range(80):
new_fish = [0] * 9
for state in range(9):
if state == 0:
new_fish[6] += fish[0]
new_fish[8] += fish[0]
else:
new_fish[state-1] += fish[state]
fish = new_fish
print(sum(fish))
|
with open('day6_input.txt') as f:
initial_fish = list(map(int, f.readline().strip().split(',')))
fish = [0] * 9
for initial_f in initial_fish:
fish[initial_f] += 1
for day in range(80):
new_fish = [0] * 9
for state in range(9):
if state == 0:
new_fish[6] += fish[0]
new_fish[8] += fish[0]
else:
new_fish[state - 1] += fish[state]
fish = new_fish
print(sum(fish))
|
# [Root Abyss] Guardians of the World Tree
MYSTERIOUS_GIRL = 1064001 # npc Id
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext("We need to find those baddies if we want to get you out of here.")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("But... they all left")
sm.setPlayerAsSpeaker()
sm.sendNext("They had to have left some clues behind. "
"What about those weird doors over there?")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("They showed up when the bad guys left, but I can't get through them.")
sm.setPlayerAsSpeaker()
sm.sendNext("Then that sounds like a good place to start. Maybe I should-")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("Y-you're glowing!")
sm.invokeAtFixedRate(0, 2450, 3, "showEffect", "Effect/Direction11.img/effect/Aura/0", 3, 0)
sm.setPlayerAsSpeaker()
sm.sendNext("Ah! What is this?! Don't let it take all my fr00dz!!")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("#h0#!!!")
sm.startQuest(parentID)
sm.lockInGameUI(False)
sm.warpInstanceIn(910700300, 0) # Fake Vellum Cave for QuestLine
|
mysterious_girl = 1064001
sm.removeEscapeButton()
sm.lockInGameUI(True)
sm.setPlayerAsSpeaker()
sm.sendNext('We need to find those baddies if we want to get you out of here.')
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext('But... they all left')
sm.setPlayerAsSpeaker()
sm.sendNext('They had to have left some clues behind. What about those weird doors over there?')
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("They showed up when the bad guys left, but I can't get through them.")
sm.setPlayerAsSpeaker()
sm.sendNext('Then that sounds like a good place to start. Maybe I should-')
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext("Y-you're glowing!")
sm.invokeAtFixedRate(0, 2450, 3, 'showEffect', 'Effect/Direction11.img/effect/Aura/0', 3, 0)
sm.setPlayerAsSpeaker()
sm.sendNext("Ah! What is this?! Don't let it take all my fr00dz!!")
sm.setSpeakerID(MYSTERIOUS_GIRL)
sm.sendNext('#h0#!!!')
sm.startQuest(parentID)
sm.lockInGameUI(False)
sm.warpInstanceIn(910700300, 0)
|
# 11 List Comprehensions
products = [
("Product1", 15),
("Product2", 50),
("Product3", 5)
]
print(products)
# prices = list(map(lambda item: item[1], products))
# print(prices)
prices = [item[1] for item in products] # With list comprehensions we can achive the same result with a clenaer code
print(prices)
# filtered_price = list(filter(lambda item: item[1] >= 10, products))
# print(filtered_price)
filtered_price = [item for item in products if item[1] >= 10]
print(filtered_price)
|
products = [('Product1', 15), ('Product2', 50), ('Product3', 5)]
print(products)
prices = [item[1] for item in products]
print(prices)
filtered_price = [item for item in products if item[1] >= 10]
print(filtered_price)
|
class orgApiPara:
setOrg_POST_request = {"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"cer_path": {"type": str, "default": ''},
"use_sll": {"type": bool, "default": True},
"admin": {"type": str, "default": ''},
"admin_pwd": {"type": str, "default": ''},
"admin_group": {"type": str, "default": ''},
"base_group": {"type": str, "default": ''},
"org_name": {"type": str, "default": ''},
"des": {"type": str, "default": ''},
"search_base": {"type": str, "default": ''}},
updateOrg_POST_request = {"id": {"type": int, "default": -1},
"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"cer_path": {"type": str, "default": ''},
"use_sll": {"type": bool, "default": True},
"admin": {"type": str, "default": ''},
"admin_pwd": {"type": str, "default": ''},
"admin_group": {"type": str, "default": ''},
"base_group": {"type": str, "default": ''},
"org_name": {"type": str, "default": ''},
"des": {"type": str, "default": ''},
"search_base": {"type": str, "default": ''}},
setOrg_POST_response = {
"ldap_id": {"type": int, "default": -1},
"org_id": {"type": int, "default": -1},
"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"cer_path": {"type": str, "default": ''},
"use_sll": {"type": bool, "default": True},
"admin": {"type": str, "default": ''},
"admin_pwd": {"type": str, "default": ''},
"admin_group": {"type": str, "default": ''},
"base_group": {"type": str, "default": ''},
"org_name": {"type": str, "default": ''},
"des": {"type": str, "default": ''},
"search_base": {"type": str, "default": ''}}
updateOrg_POST_response = {
"ldap_id": {"type": int, "default": -1},
"org_id": {"type": int, "default": -1},
"host": {"type": str, "default": ''},
"port": {"type": int, "default": 636},
"use_sll": {"type": bool, "default": True},
"cer_path": {"type": str, "default": ''},
"admin": {"type": str, "default": ''},
"admin_pwd": {"type": str, "default": ''},
"admin_group": {"type": str, "default": ''},
"base_group": {"type": str, "default": ''},
"org_name": {"type": str, "default": ''},
"des": {"type": str, "default": ''},
"search_base": {"type": str, "default": ''}}
|
class Orgapipara:
set_org_post_request = ({'host': {'type': str, 'default': ''}, 'port': {'type': int, 'default': 636}, 'cer_path': {'type': str, 'default': ''}, 'use_sll': {'type': bool, 'default': True}, 'admin': {'type': str, 'default': ''}, 'admin_pwd': {'type': str, 'default': ''}, 'admin_group': {'type': str, 'default': ''}, 'base_group': {'type': str, 'default': ''}, 'org_name': {'type': str, 'default': ''}, 'des': {'type': str, 'default': ''}, 'search_base': {'type': str, 'default': ''}},)
update_org_post_request = ({'id': {'type': int, 'default': -1}, 'host': {'type': str, 'default': ''}, 'port': {'type': int, 'default': 636}, 'cer_path': {'type': str, 'default': ''}, 'use_sll': {'type': bool, 'default': True}, 'admin': {'type': str, 'default': ''}, 'admin_pwd': {'type': str, 'default': ''}, 'admin_group': {'type': str, 'default': ''}, 'base_group': {'type': str, 'default': ''}, 'org_name': {'type': str, 'default': ''}, 'des': {'type': str, 'default': ''}, 'search_base': {'type': str, 'default': ''}},)
set_org_post_response = {'ldap_id': {'type': int, 'default': -1}, 'org_id': {'type': int, 'default': -1}, 'host': {'type': str, 'default': ''}, 'port': {'type': int, 'default': 636}, 'cer_path': {'type': str, 'default': ''}, 'use_sll': {'type': bool, 'default': True}, 'admin': {'type': str, 'default': ''}, 'admin_pwd': {'type': str, 'default': ''}, 'admin_group': {'type': str, 'default': ''}, 'base_group': {'type': str, 'default': ''}, 'org_name': {'type': str, 'default': ''}, 'des': {'type': str, 'default': ''}, 'search_base': {'type': str, 'default': ''}}
update_org_post_response = {'ldap_id': {'type': int, 'default': -1}, 'org_id': {'type': int, 'default': -1}, 'host': {'type': str, 'default': ''}, 'port': {'type': int, 'default': 636}, 'use_sll': {'type': bool, 'default': True}, 'cer_path': {'type': str, 'default': ''}, 'admin': {'type': str, 'default': ''}, 'admin_pwd': {'type': str, 'default': ''}, 'admin_group': {'type': str, 'default': ''}, 'base_group': {'type': str, 'default': ''}, 'org_name': {'type': str, 'default': ''}, 'des': {'type': str, 'default': ''}, 'search_base': {'type': str, 'default': ''}}
|
#!/usr/bin/python3
#-----------------bot session-------------------
UserCancel = 'You have cancel the process.'
welcomeMessage = ('User identity conformed, please input gallery urls ' +
'and use space to separate them'
)
denyMessage = 'You are not the admin of this bot, conversation end.'
urlComform = ('Received {0} gallery url(s). \nNow begin to download the content. ' +
'Once the download completed, you will receive a report.'
)
magnetLinkConform = ('Received a magnetLink. Now send it to bittorrent client')
magnetResultMessage = ('Torrent {0} has been added bittorrent client.')
urlNotFound = 'Could not find any gallery url, please check and re-input.'
gidError = 'Encountered an error gid: {0}'
#------------------magnet download session---------------------
emptyFileListError = ('Could not retrive file list for this link, maybe still '+
'downloading meta data.')
#-----------------dloptgenerate session---------------------
userCookiesFormError = 'userCookies form error, please check the config file.'
#-----------------managgessiongen session-------------------
usercookiesEXHError = 'This cookies could not access EXH'
#-----------------ehlogin session---------------------------
ehloginError = 'username or password error, please check.'
exhError = 'This username could not access exhentai.'
#------------------download session------------------------
galleryError = 'Gallery does not contain any page, maybe deleted.'
|
user_cancel = 'You have cancel the process.'
welcome_message = 'User identity conformed, please input gallery urls ' + 'and use space to separate them'
deny_message = 'You are not the admin of this bot, conversation end.'
url_comform = 'Received {0} gallery url(s). \nNow begin to download the content. ' + 'Once the download completed, you will receive a report.'
magnet_link_conform = 'Received a magnetLink. Now send it to bittorrent client'
magnet_result_message = 'Torrent {0} has been added bittorrent client.'
url_not_found = 'Could not find any gallery url, please check and re-input.'
gid_error = 'Encountered an error gid: {0}'
empty_file_list_error = 'Could not retrive file list for this link, maybe still ' + 'downloading meta data.'
user_cookies_form_error = 'userCookies form error, please check the config file.'
usercookies_exh_error = 'This cookies could not access EXH'
ehlogin_error = 'username or password error, please check.'
exh_error = 'This username could not access exhentai.'
gallery_error = 'Gallery does not contain any page, maybe deleted.'
|
(n,m) = [int(x) for x in input().split()]
loop_range = n + m
set_m = set()
set_n = set()
for _ in range(n):
set_n.add(int(input()))
for _ in range(m):
set_m.add(int(input()))
uniques = set_n.intersection(set_m)
[print(x) for x in (uniques)]
|
(n, m) = [int(x) for x in input().split()]
loop_range = n + m
set_m = set()
set_n = set()
for _ in range(n):
set_n.add(int(input()))
for _ in range(m):
set_m.add(int(input()))
uniques = set_n.intersection(set_m)
[print(x) for x in uniques]
|
class bcolors():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OK = '\033[92m'
WARNING = '\033[96m'
FAIL = '\033[91m'
TITLE = '\033[93m'
ENDC = '\033[0m'
|
class Bcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
ok = '\x1b[92m'
warning = '\x1b[96m'
fail = '\x1b[91m'
title = '\x1b[93m'
endc = '\x1b[0m'
|
nz = 512 # noize vector size
nsf = 4 # encoded voxel size, scale factor
nvx = 32 # output voxel size
batch_size = 64
learning_rate = 2e-4
dataset_path_i = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned"
dataset_path_o = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox"
params_path = "params/voxel_dcgan_model.ckpt"
|
nz = 512
nsf = 4
nvx = 32
batch_size = 64
learning_rate = 0.0002
dataset_path_i = '/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned'
dataset_path_o = '/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox'
params_path = 'params/voxel_dcgan_model.ckpt'
|
class Fiz_contact:
def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword):
self.lastname=lastname
self.firstname=firstname
self.middlename=middlename
self.email=email
self.telephone=telephone
self.password=password
self.confirmpassword=confirmpassword
|
class Fiz_Contact:
def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword):
self.lastname = lastname
self.firstname = firstname
self.middlename = middlename
self.email = email
self.telephone = telephone
self.password = password
self.confirmpassword = confirmpassword
|
"""
igen stands for "invoice generator".
The project is currently inactive.
"""
|
"""
igen stands for "invoice generator".
The project is currently inactive.
"""
|
def main():
with open("number.txt", "r") as file:
data = file.read()
data = data.split("\n")
x = [row.split("\t") for row in data[:5]]
print(function(x))
def function(x):
sum=0
for el in x[0:]:
sum += int(el[0])
return sum
if __name__=="__main__":
main();
|
def main():
with open('number.txt', 'r') as file:
data = file.read()
data = data.split('\n')
x = [row.split('\t') for row in data[:5]]
print(function(x))
def function(x):
sum = 0
for el in x[0:]:
sum += int(el[0])
return sum
if __name__ == '__main__':
main()
|
a = input()
b= input()
print(ord(a) + ord(b))
|
a = input()
b = input()
print(ord(a) + ord(b))
|
def prastevila_do_n(n):
pra = [2,3,5,7]
for x in range(8,n+1):
d = True
for y in range(2,int(x ** 0.5) + 1):
if d == False:
break
elif x % y == 0:
d = False
if d == True:
pra.append(x)
return pra
def euler_50():
pra = prastevila_do_n(1000000)
najvecja_vsot_ki_je_prastevilo = 0
stevilo_z_najvec_p = 0
for p in pra:
i = pra.index(p)
if sum(pra[i:i+stevilo_z_najvec_p]) > 1000000:
break
stevilo_p = 0
vsota = pra[i]
for p1 in range(i+1,len(pra)):
stevilo_p += 1
vsota += pra[p1]
if vsota > 1000000:
break
elif vsota in pra and stevilo_z_najvec_p < stevilo_p:
najvecja_vsot_ki_je_prastevilo = vsota
stevilo_z_najvec_p = stevilo_p
return najvecja_vsot_ki_je_prastevilo
euler_50()
|
def prastevila_do_n(n):
pra = [2, 3, 5, 7]
for x in range(8, n + 1):
d = True
for y in range(2, int(x ** 0.5) + 1):
if d == False:
break
elif x % y == 0:
d = False
if d == True:
pra.append(x)
return pra
def euler_50():
pra = prastevila_do_n(1000000)
najvecja_vsot_ki_je_prastevilo = 0
stevilo_z_najvec_p = 0
for p in pra:
i = pra.index(p)
if sum(pra[i:i + stevilo_z_najvec_p]) > 1000000:
break
stevilo_p = 0
vsota = pra[i]
for p1 in range(i + 1, len(pra)):
stevilo_p += 1
vsota += pra[p1]
if vsota > 1000000:
break
elif vsota in pra and stevilo_z_najvec_p < stevilo_p:
najvecja_vsot_ki_je_prastevilo = vsota
stevilo_z_najvec_p = stevilo_p
return najvecja_vsot_ki_je_prastevilo
euler_50()
|
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries',
'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client']
def strip_globals(kwargs):
for arg in args_global:
kwargs.pop(arg, None)
def remove_null(kwargs):
keys = []
for key, value in kwargs.items():
if value is None:
keys.append(key)
for key in keys:
kwargs.pop(key, None)
def apply_defaults(kwargs, **defaults):
for key, value in defaults.items():
if key not in kwargs:
kwargs[key] = value
def group_as(kwargs, name, values):
group = {}
for arg in values:
if arg in kwargs and kwargs[arg] is not None:
group[arg] = kwargs.pop(arg, None)
kwargs[name] = group
|
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries', 'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client']
def strip_globals(kwargs):
for arg in args_global:
kwargs.pop(arg, None)
def remove_null(kwargs):
keys = []
for (key, value) in kwargs.items():
if value is None:
keys.append(key)
for key in keys:
kwargs.pop(key, None)
def apply_defaults(kwargs, **defaults):
for (key, value) in defaults.items():
if key not in kwargs:
kwargs[key] = value
def group_as(kwargs, name, values):
group = {}
for arg in values:
if arg in kwargs and kwargs[arg] is not None:
group[arg] = kwargs.pop(arg, None)
kwargs[name] = group
|
datasetFile = open("datasets/rosalind_ba1e.txt", "r")
genome = datasetFile.readline().strip()
otherArgs = datasetFile.readline().strip()
k, L, t = map(lambda x: int(x), otherArgs.split(" "))
def findClumps(genome, k, L, t):
kmerIndex = {}
clumpedKmers = set()
for i in range(len(genome) - k + 1):
kmer = genome[i:i+k]
if kmer in kmerIndex:
currentIndex = kmerIndex[kmer]
currentIndex.append(i)
if len(currentIndex) >= t:
clumpStart = currentIndex[-t]
if i - clumpStart <= L:
clumpedKmers.add(kmer)
else:
kmerIndex[kmer] = [i]
return clumpedKmers
solution = " ".join(findClumps(genome, k, L, t))
outputFile = open("output/rosalind_ba1e.txt", "a")
outputFile.write(solution)
|
dataset_file = open('datasets/rosalind_ba1e.txt', 'r')
genome = datasetFile.readline().strip()
other_args = datasetFile.readline().strip()
(k, l, t) = map(lambda x: int(x), otherArgs.split(' '))
def find_clumps(genome, k, L, t):
kmer_index = {}
clumped_kmers = set()
for i in range(len(genome) - k + 1):
kmer = genome[i:i + k]
if kmer in kmerIndex:
current_index = kmerIndex[kmer]
currentIndex.append(i)
if len(currentIndex) >= t:
clump_start = currentIndex[-t]
if i - clumpStart <= L:
clumpedKmers.add(kmer)
else:
kmerIndex[kmer] = [i]
return clumpedKmers
solution = ' '.join(find_clumps(genome, k, L, t))
output_file = open('output/rosalind_ba1e.txt', 'a')
outputFile.write(solution)
|
class Token:
def __init__(self, word, line, start, finish, category, reason=None):
self.__word__ = word
self.__line__ = line
self.__start__ = start
self.__finish__ = finish
self.__category__ = category
self.__reason__ = reason
@property
def word(self):
return self.__word__
@word.setter
def word(self, word):
self.__word__ = word
@property
def line(self):
return self.__line__
@line.setter
def line(self, line):
self.__line__ = line
@property
def start(self):
return self.__start__
@start.setter
def start(self, start):
self.__start__ = start
@property
def finish(self):
return self.__finish__
@finish.setter
def finish(self, finish):
self.__finish__ = finish
@property
def category(self):
return self.__category__
@category.setter
def category(self, category):
self.__category__ = category
@property
def reason(self):
return self.__reason__
@reason.setter
def reason(self, reason):
self.__reason__ = reason
|
class Token:
def __init__(self, word, line, start, finish, category, reason=None):
self.__word__ = word
self.__line__ = line
self.__start__ = start
self.__finish__ = finish
self.__category__ = category
self.__reason__ = reason
@property
def word(self):
return self.__word__
@word.setter
def word(self, word):
self.__word__ = word
@property
def line(self):
return self.__line__
@line.setter
def line(self, line):
self.__line__ = line
@property
def start(self):
return self.__start__
@start.setter
def start(self, start):
self.__start__ = start
@property
def finish(self):
return self.__finish__
@finish.setter
def finish(self, finish):
self.__finish__ = finish
@property
def category(self):
return self.__category__
@category.setter
def category(self, category):
self.__category__ = category
@property
def reason(self):
return self.__reason__
@reason.setter
def reason(self, reason):
self.__reason__ = reason
|
# Node types
TYPE_NODE = b'\x10'
TYPE_NODE_NR = b'\x11'
# Gateway types
TYPE_GATEWAY = b'\x20'
TYPE_GATEWAY_TIME = b'\x21'
# Special types
TYPE_PROVISIONING = b'\xFF'
|
type_node = b'\x10'
type_node_nr = b'\x11'
type_gateway = b' '
type_gateway_time = b'!'
type_provisioning = b'\xff'
|
#!/usr/bin/env python
# encoding: utf-8
"""
merge_intervals.py
Created by Shengwei on 2014-07-07.
"""
# https://oj.leetcode.com/problems/merge-intervals/
# tags: medium, array, interval
"""
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
"""
# https://gist.github.com/senvey/772e0afd345934cee475
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Interval
# @return a list of Interval
def merge(self, intervals):
if intervals is None or len(intervals) <= 1:
return intervals
result = []
intervals = sorted(intervals, key=lambda i: i.start)
# this step must be after the intervals are sorted
start, end = intervals[0].start, intervals[0].end
for interval in intervals:
n_start, n_end = interval.start, interval.end
# becasue the intervals are sorted now, start
# must be less than or equal to n_start, so
# if n_start <= end, it starts in [start, end]
if n_start <= end:
if n_end >= end:
end = n_end
# if n_end < end: pass
else:
result.append(Interval(start, end))
start, end = n_start, n_end
# IMPORTANT! remember to post-process
result.append(Interval(start, end))
return result
|
"""
merge_intervals.py
Created by Shengwei on 2014-07-07.
"""
'\nGiven a collection of intervals, merge all overlapping intervals.\n\nFor example,\nGiven [1,3],[2,6],[8,10],[15,18],\nreturn [1,6],[8,10],[15,18].\n'
class Solution:
def merge(self, intervals):
if intervals is None or len(intervals) <= 1:
return intervals
result = []
intervals = sorted(intervals, key=lambda i: i.start)
(start, end) = (intervals[0].start, intervals[0].end)
for interval in intervals:
(n_start, n_end) = (interval.start, interval.end)
if n_start <= end:
if n_end >= end:
end = n_end
else:
result.append(interval(start, end))
(start, end) = (n_start, n_end)
result.append(interval(start, end))
return result
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Have no idea how to do this
# import sys
# sys.path.insert(0, '../../data_structures')
# import node
def intersection(l1: Node, l2: Node) -> Node:
l1_end, len1 = get_tail(l1)
l2_end, len2 = get_tail(l2)
if l1_end != l2_end:
return None
if len1 > len2:
l1 = move_head(l1, len1 - len2)
else:
l2 = move_head(l2, len2 - len1)
while l1 != l2:
l1 = l1.next
l2 = l2.next
print(l1.value, l2.value)
return l1
def move_head(head: Node, pos: int) -> Node:
current = head
while pos > 0:
current = current.next
pos -= 1
return current
def get_tail(head: Node) -> (Node, int):
current = head
length = 0
while not current.next == None:
current = current.next
length += 1
return (current, length)
inter = Node('c')
inter.next = Node('a')
inter.next.next = Node('r')
l1 = Node('r')
l1.next = Node('a')
l1.next.next = Node('c')
l1.next.next.next = Node('e')
l1.next.next.next.next = inter
l2 = Node('r')
l2.next = Node('e')
l2.next.next = Node('d')
l2.next.next.next = inter
res = intersection(l1, l2)
print(res.value)
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
def intersection(l1: Node, l2: Node) -> Node:
(l1_end, len1) = get_tail(l1)
(l2_end, len2) = get_tail(l2)
if l1_end != l2_end:
return None
if len1 > len2:
l1 = move_head(l1, len1 - len2)
else:
l2 = move_head(l2, len2 - len1)
while l1 != l2:
l1 = l1.next
l2 = l2.next
print(l1.value, l2.value)
return l1
def move_head(head: Node, pos: int) -> Node:
current = head
while pos > 0:
current = current.next
pos -= 1
return current
def get_tail(head: Node) -> (Node, int):
current = head
length = 0
while not current.next == None:
current = current.next
length += 1
return (current, length)
inter = node('c')
inter.next = node('a')
inter.next.next = node('r')
l1 = node('r')
l1.next = node('a')
l1.next.next = node('c')
l1.next.next.next = node('e')
l1.next.next.next.next = inter
l2 = node('r')
l2.next = node('e')
l2.next.next = node('d')
l2.next.next.next = inter
res = intersection(l1, l2)
print(res.value)
|
# NAVI AND MATH
def power(base, exp):
res = 1
while exp>0:
if exp&1:
res = (res*base)%1000000007
exp = exp>>1
base = (base*base)%1000000007
return res%1000000007
mod = 1000000007
for i in range(int(input().strip())):
ans = "Case #" + str(i+1) + ': '
N = int(input().strip())
Arr = [int(a) for a in input().strip().split()]
mask = 3
maxx = -1
#ct = 0
while mask<(1<<N):
p = 0
sm = 0
ml = 1
#ct += 1
for j in range(0,N,1):
if mask&(1<<j):
sm += Arr[j]
ml = (ml*Arr[j])%mod
#print(Arr[j])
p = (ml*power(sm,mod-2))%mod
if maxx<p:
maxx = p
#print(maxx)
mask += 1
#print(ct)
ans += str(maxx)
print(ans)
|
def power(base, exp):
res = 1
while exp > 0:
if exp & 1:
res = res * base % 1000000007
exp = exp >> 1
base = base * base % 1000000007
return res % 1000000007
mod = 1000000007
for i in range(int(input().strip())):
ans = 'Case #' + str(i + 1) + ': '
n = int(input().strip())
arr = [int(a) for a in input().strip().split()]
mask = 3
maxx = -1
while mask < 1 << N:
p = 0
sm = 0
ml = 1
for j in range(0, N, 1):
if mask & 1 << j:
sm += Arr[j]
ml = ml * Arr[j] % mod
p = ml * power(sm, mod - 2) % mod
if maxx < p:
maxx = p
mask += 1
ans += str(maxx)
print(ans)
|
class Manifest:
def __init__(self, definition: dict):
self._definition = definition
def exists(self):
return self._definition is not None and self._definition != {}
def _resolve_node(self, name: str):
key = next((k for k in self._definition["nodes"].keys() if name == k.split(".")[-1]), None)
if key is None:
raise ValueError(
f"Could not find the ref {name} in the co-located dbt project."
" Please check the name in your dbt project."
)
return self._definition["nodes"][key]
def resolve_name(self, name: str):
node = self._resolve_node(name)
# return f"{node['database']}.{node['schema']}.{node['alias']}"
return f"{node['schema']}.{node['alias']}"
|
class Manifest:
def __init__(self, definition: dict):
self._definition = definition
def exists(self):
return self._definition is not None and self._definition != {}
def _resolve_node(self, name: str):
key = next((k for k in self._definition['nodes'].keys() if name == k.split('.')[-1]), None)
if key is None:
raise value_error(f'Could not find the ref {name} in the co-located dbt project. Please check the name in your dbt project.')
return self._definition['nodes'][key]
def resolve_name(self, name: str):
node = self._resolve_node(name)
return f"{node['schema']}.{node['alias']}"
|
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "commons_fileupload_commons_fileupload",
artifact = "commons-fileupload:commons-fileupload:1.4",
artifact_sha256 = "a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7",
srcjar_sha256 = "2acfe29671daf8c94be5d684b8ac260d9c11f78611dff4899779b43a99205291",
excludes = [
"commons-io:commons-io",
],
)
|
load(':import_external.bzl', import_external='import_external')
def dependencies():
import_external(name='commons_fileupload_commons_fileupload', artifact='commons-fileupload:commons-fileupload:1.4', artifact_sha256='a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7', srcjar_sha256='2acfe29671daf8c94be5d684b8ac260d9c11f78611dff4899779b43a99205291', excludes=['commons-io:commons-io'])
|
class Node:
props = ()
def __init__(self, **kwargs):
for prop in kwargs:
if prop not in self.props:
raise Exception('Invalid property %r, allowed only: %s' %
(prop, self.props))
self.__dict__[prop] = kwargs[prop]
for prop in self.props:
if prop not in self.__dict__:
self.__dict__[prop] = None
self.attrs = {}
def print_node(self, indent=0, indent_size=4,extra=0):
s = self.__class__.__name__
s += '(\n'
i = ' ' * (indent+indent_size)
for prop in self.props:
s += i + prop + ' = '
s += self._print_val(self.__dict__[prop], indent+indent_size, indent_size,
(len(prop) + 3) - indent_size)
s += '\n'
s += (' ' * (indent + extra)) + ')'
return s
def _print_val(self, val, indent, indent_size,extra=0):
if isinstance(val, Node):
return val.print_node(indent+indent_size,indent_size,extra)
elif type(val) == list:
s = '[\n'
i = ' ' * (indent+indent_size)
for e in val:
s += i + self._print_val(e, indent, indent_size)
s += ',\n'
s += (' ' * (indent+extra)) + ']'
return s
else:
return str(val)
class Statement(Node): pass
class Expression(Node): pass
class EmptyStatement(Statement): pass
EmptyStatement.INSTANCE = EmptyStatement()
class FunctionDeclaration(Statement): props = ('type', 'decl', 'body')
class Declaration(Statement): props = ('type', 'init')
class ParamDeclaration(Node): props = ('type', 'decl')
class StructTypeRef(Node): props = ('name',)
class DeclarationSpecifier(Node): props = ('store', 'qual', 'type')
class InitSpec(Node): props = ('decl', 'val')
class DeclaratorSpec(Node): props = ('pointer_depth', 'name_spec')
class ArrayDeclSpec(Node): props = ('name', 'dim')
class FuncDeclSpec(Node): props = ('name', 'params')
class VarArgs(Node): pass
VarArgs.INSTANCE = VarArgs()
class StructSpec(Node): props = ('name', 'decl')
class StructMemberDecl(Node): props = ('spec', 'decl')
class MemberReference(Node): props = ('child', 'idx', 'name')
class TypeName(Node): props = ('type', 'spec')
class LabelledStmt(Statement): props = ('label', 'stmt')
class WhileStmt(Statement): props = ('cond', 'body')
class DoWhileStmt(Statement): props = ('body', 'cond')
class ForStmt(Statement): props = ('init', 'cond', 'after', 'body')
class IfStmt(Statement): props = ('cond', 'true', 'false')
class SwitchStmt(Statement): props = ('expr', 'cases')
class ContinueStmt(Statement): pass
ContinueStmt.INSTANCE = ContinueStmt()
class BreakStmt(Statement): pass
BreakStmt.INSTANCE = BreakStmt()
class ReturnStmt(Statement): props = ('expr',)
class GotoStmt(Statement): props = ('label',)
class CaseStmt(Statement): props = ('choice', 'body')
class SyncStmt(Statement): pass
class ExpressionStmt(Statement): props = ('expr',)
class SizeofExpr(Expression): props = ('expr',)
class ConditionalExpr(Expression): props = ('cond', 'true', 'false')
class FunctionCallExpr(Expression): props = ('ref', 'args')
class IdentifierExpr(Expression): props = ('val',)
class AssignmentExpr(Expression): props = ('left', 'right')
class AssignmentOperatorExpr(Expression): props = ('left', 'op', 'right')
class UnaryExpr(Expression): props = ('op', 'expr')
class BinaryOperatorExpr(Expression): props = ('left', 'op', 'right')
class IncrementExpr(Expression): props = ('dir', 'post', 'expr')
class MemberAccessExpr(Expression): props = ('expr', 'prop', 'deref')
class ArraySubscriptExpr(Expression): props = ('expr', 'sub')
class Literal(Expression): props = ('val',)
class IntLiteral(Literal): pass
class StringLiteral(Literal): pass
class Pragma(Node): props = ('val',)
class Token:
class Type:
IDENTIFIER = 'identifier'
OPERATOR = 'operator'
NUMBER = 'number'
STRING = 'string'
def __init__(self, val, type=None):
self.val = val
self.type = type or Token.Type.OPERATOR
def __str__(self):
return 'Token(%r, %s)' % (self.val, self.type)
class Keyword(Token):
REGISTRY = {}
def __init__(self, val):
super().__init__(val, Token.Type.IDENTIFIER)
Keyword.REGISTRY[val] = self
Token.EOF = Token('<eof>')
Token.OPEN_PAREN = Token('(')
Token.CLOSE_PAREN = Token(')')
Token.OPEN_BRACE = Token('{')
Token.CLOSE_BRACE = Token('}')
Token.OPEN_SQUARE = Token('[')
Token.CLOSE_SQUARE = Token(']')
Token.COMMA = Token(',')
Token.SEMICOLON = Token(';')
Token.QUESTION = Token('?')
Token.COLON = Token(':')
Token.DOT = Token('.')
Token.ARROW = Token('->')
Token.VARARG = Token('...')
Token.OP_ASSIGN = Token('=')
Token.OP_MUL_ASSIGN = Token('*=')
Token.OP_DIV_ASSIGN = Token('/=')
Token.OP_MOD_ASSIGN = Token('%=')
Token.OP_PLUS_ASSIGN = Token('+=')
Token.OP_MINUS_ASSIGN = Token('-=')
Token.OP_LSHIFT_ASSIGN = Token('<<=')
Token.OP_RSHIFT_ASSIGN = Token('>>=')
Token.OP_AND_ASSIGN = Token('&=')
Token.OP_XOR_ASSIGN = Token('^=')
Token.OP_OR_ASSIGN = Token('|=')
Token.OP_PLUS = Token('+')
Token.OP_PLUS_PLUS = Token('++')
Token.OP_MINUS = Token('-')
Token.OP_MINUS_MINUS = Token('--')
Token.OP_STAR = Token('*')
Token.OP_DIV = Token('/')
Token.OP_MOD = Token('%')
Token.OP_AND = Token('&')
Token.OP_OR = Token('|')
Token.OP_AND_AND = Token('&&')
Token.OP_OR_OR = Token('||')
Token.OP_XOR = Token('^')
Token.OP_NOT = Token('!')
Token.OP_BITNOT = Token('~')
Token.OP_SHIFT_LEFT = Token('<<')
Token.OP_SHIFT_RIGHT = Token('>>')
Token.OP_EQUAL = Token('==')
Token.OP_NOT_EQUAL = Token('!=')
Token.OP_LESS_THAN = Token('<')
Token.OP_LESS_OR_EQUAL = Token('<=')
Token.OP_GREATER_THAN = Token('>')
Token.OP_GREATER_OR_EQUAL = Token('>=')
Keyword.DO = Keyword('do')
Keyword.WHILE = Keyword('while')
Keyword.FOR = Keyword('for')
Keyword.IF = Keyword('if')
Keyword.ELSE = Keyword('else')
Keyword.SIZEOF = Keyword('sizeof')
Keyword.SYNC = Keyword('sync')
Keyword.SWITCH = Keyword('switch')
Keyword.CASE = Keyword('case')
Keyword.DEFAULT = Keyword('default')
Keyword.GOTO = Keyword('goto')
Keyword.CONTINUE = Keyword('continue')
Keyword.BREAK = Keyword('break')
Keyword.RETURN = Keyword('return')
Keyword.CONST = Keyword('const')
Keyword.STATIC = Keyword('static')
Keyword.TYPEDEF = Keyword('typedef')
Keyword.STRUCT = Keyword('struct')
|
class Node:
props = ()
def __init__(self, **kwargs):
for prop in kwargs:
if prop not in self.props:
raise exception('Invalid property %r, allowed only: %s' % (prop, self.props))
self.__dict__[prop] = kwargs[prop]
for prop in self.props:
if prop not in self.__dict__:
self.__dict__[prop] = None
self.attrs = {}
def print_node(self, indent=0, indent_size=4, extra=0):
s = self.__class__.__name__
s += '(\n'
i = ' ' * (indent + indent_size)
for prop in self.props:
s += i + prop + ' = '
s += self._print_val(self.__dict__[prop], indent + indent_size, indent_size, len(prop) + 3 - indent_size)
s += '\n'
s += ' ' * (indent + extra) + ')'
return s
def _print_val(self, val, indent, indent_size, extra=0):
if isinstance(val, Node):
return val.print_node(indent + indent_size, indent_size, extra)
elif type(val) == list:
s = '[\n'
i = ' ' * (indent + indent_size)
for e in val:
s += i + self._print_val(e, indent, indent_size)
s += ',\n'
s += ' ' * (indent + extra) + ']'
return s
else:
return str(val)
class Statement(Node):
pass
class Expression(Node):
pass
class Emptystatement(Statement):
pass
EmptyStatement.INSTANCE = empty_statement()
class Functiondeclaration(Statement):
props = ('type', 'decl', 'body')
class Declaration(Statement):
props = ('type', 'init')
class Paramdeclaration(Node):
props = ('type', 'decl')
class Structtyperef(Node):
props = ('name',)
class Declarationspecifier(Node):
props = ('store', 'qual', 'type')
class Initspec(Node):
props = ('decl', 'val')
class Declaratorspec(Node):
props = ('pointer_depth', 'name_spec')
class Arraydeclspec(Node):
props = ('name', 'dim')
class Funcdeclspec(Node):
props = ('name', 'params')
class Varargs(Node):
pass
VarArgs.INSTANCE = var_args()
class Structspec(Node):
props = ('name', 'decl')
class Structmemberdecl(Node):
props = ('spec', 'decl')
class Memberreference(Node):
props = ('child', 'idx', 'name')
class Typename(Node):
props = ('type', 'spec')
class Labelledstmt(Statement):
props = ('label', 'stmt')
class Whilestmt(Statement):
props = ('cond', 'body')
class Dowhilestmt(Statement):
props = ('body', 'cond')
class Forstmt(Statement):
props = ('init', 'cond', 'after', 'body')
class Ifstmt(Statement):
props = ('cond', 'true', 'false')
class Switchstmt(Statement):
props = ('expr', 'cases')
class Continuestmt(Statement):
pass
ContinueStmt.INSTANCE = continue_stmt()
class Breakstmt(Statement):
pass
BreakStmt.INSTANCE = break_stmt()
class Returnstmt(Statement):
props = ('expr',)
class Gotostmt(Statement):
props = ('label',)
class Casestmt(Statement):
props = ('choice', 'body')
class Syncstmt(Statement):
pass
class Expressionstmt(Statement):
props = ('expr',)
class Sizeofexpr(Expression):
props = ('expr',)
class Conditionalexpr(Expression):
props = ('cond', 'true', 'false')
class Functioncallexpr(Expression):
props = ('ref', 'args')
class Identifierexpr(Expression):
props = ('val',)
class Assignmentexpr(Expression):
props = ('left', 'right')
class Assignmentoperatorexpr(Expression):
props = ('left', 'op', 'right')
class Unaryexpr(Expression):
props = ('op', 'expr')
class Binaryoperatorexpr(Expression):
props = ('left', 'op', 'right')
class Incrementexpr(Expression):
props = ('dir', 'post', 'expr')
class Memberaccessexpr(Expression):
props = ('expr', 'prop', 'deref')
class Arraysubscriptexpr(Expression):
props = ('expr', 'sub')
class Literal(Expression):
props = ('val',)
class Intliteral(Literal):
pass
class Stringliteral(Literal):
pass
class Pragma(Node):
props = ('val',)
class Token:
class Type:
identifier = 'identifier'
operator = 'operator'
number = 'number'
string = 'string'
def __init__(self, val, type=None):
self.val = val
self.type = type or Token.Type.OPERATOR
def __str__(self):
return 'Token(%r, %s)' % (self.val, self.type)
class Keyword(Token):
registry = {}
def __init__(self, val):
super().__init__(val, Token.Type.IDENTIFIER)
Keyword.REGISTRY[val] = self
Token.EOF = token('<eof>')
Token.OPEN_PAREN = token('(')
Token.CLOSE_PAREN = token(')')
Token.OPEN_BRACE = token('{')
Token.CLOSE_BRACE = token('}')
Token.OPEN_SQUARE = token('[')
Token.CLOSE_SQUARE = token(']')
Token.COMMA = token(',')
Token.SEMICOLON = token(';')
Token.QUESTION = token('?')
Token.COLON = token(':')
Token.DOT = token('.')
Token.ARROW = token('->')
Token.VARARG = token('...')
Token.OP_ASSIGN = token('=')
Token.OP_MUL_ASSIGN = token('*=')
Token.OP_DIV_ASSIGN = token('/=')
Token.OP_MOD_ASSIGN = token('%=')
Token.OP_PLUS_ASSIGN = token('+=')
Token.OP_MINUS_ASSIGN = token('-=')
Token.OP_LSHIFT_ASSIGN = token('<<=')
Token.OP_RSHIFT_ASSIGN = token('>>=')
Token.OP_AND_ASSIGN = token('&=')
Token.OP_XOR_ASSIGN = token('^=')
Token.OP_OR_ASSIGN = token('|=')
Token.OP_PLUS = token('+')
Token.OP_PLUS_PLUS = token('++')
Token.OP_MINUS = token('-')
Token.OP_MINUS_MINUS = token('--')
Token.OP_STAR = token('*')
Token.OP_DIV = token('/')
Token.OP_MOD = token('%')
Token.OP_AND = token('&')
Token.OP_OR = token('|')
Token.OP_AND_AND = token('&&')
Token.OP_OR_OR = token('||')
Token.OP_XOR = token('^')
Token.OP_NOT = token('!')
Token.OP_BITNOT = token('~')
Token.OP_SHIFT_LEFT = token('<<')
Token.OP_SHIFT_RIGHT = token('>>')
Token.OP_EQUAL = token('==')
Token.OP_NOT_EQUAL = token('!=')
Token.OP_LESS_THAN = token('<')
Token.OP_LESS_OR_EQUAL = token('<=')
Token.OP_GREATER_THAN = token('>')
Token.OP_GREATER_OR_EQUAL = token('>=')
Keyword.DO = keyword('do')
Keyword.WHILE = keyword('while')
Keyword.FOR = keyword('for')
Keyword.IF = keyword('if')
Keyword.ELSE = keyword('else')
Keyword.SIZEOF = keyword('sizeof')
Keyword.SYNC = keyword('sync')
Keyword.SWITCH = keyword('switch')
Keyword.CASE = keyword('case')
Keyword.DEFAULT = keyword('default')
Keyword.GOTO = keyword('goto')
Keyword.CONTINUE = keyword('continue')
Keyword.BREAK = keyword('break')
Keyword.RETURN = keyword('return')
Keyword.CONST = keyword('const')
Keyword.STATIC = keyword('static')
Keyword.TYPEDEF = keyword('typedef')
Keyword.STRUCT = keyword('struct')
|
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])]
if __name__ == "__main__":
print(sort([
("English", 88),
("Social", 82),
("Science", 90),
("Math", 97)
]))
|
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])]
if __name__ == '__main__':
print(sort([('English', 88), ('Social', 82), ('Science', 90), ('Math', 97)]))
|
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
de = []
for i in range(0, len(nums), 2):
pair = []
pair.append(nums[i])
pair.append(nums[i + 1])
arr = [nums[i + 1]] * nums[i]
de += arr
return de
|
class Solution:
def decompress_rl_elist(self, nums: List[int]) -> List[int]:
de = []
for i in range(0, len(nums), 2):
pair = []
pair.append(nums[i])
pair.append(nums[i + 1])
arr = [nums[i + 1]] * nums[i]
de += arr
return de
|
class SubCommand:
def __init__(self, command, description="", arguments=[], mutually_exclusive_arguments=[]):
self._command = command
self._description = description
self._arguments = arguments
self._mutually_exclusive_arguments = mutually_exclusive_arguments
def getCommand(self):
return self._command
def get_description(self):
return self._description
def getArguments(self):
return self._arguments
def getMutuallyExclusiveArguments(self):
return self._mutually_exclusive_arguments
|
class Subcommand:
def __init__(self, command, description='', arguments=[], mutually_exclusive_arguments=[]):
self._command = command
self._description = description
self._arguments = arguments
self._mutually_exclusive_arguments = mutually_exclusive_arguments
def get_command(self):
return self._command
def get_description(self):
return self._description
def get_arguments(self):
return self._arguments
def get_mutually_exclusive_arguments(self):
return self._mutually_exclusive_arguments
|
def read_file(filepath):
with open(filepath,'r') as i:
inst = [int(x) for x in i.read().replace(')','-1,').replace('(','1,').strip('\n').strip(',').split(',')]
return inst
def calculate(inst,floor=0):
for i,f in enumerate(inst):
floor += f
if floor < 0: break
return sum(inst), i+1
def main(filepath):
pt1, pt2 = calculate(read_file(filepath))
return pt1, pt2
print(main('1.txt'))
|
def read_file(filepath):
with open(filepath, 'r') as i:
inst = [int(x) for x in i.read().replace(')', '-1,').replace('(', '1,').strip('\n').strip(',').split(',')]
return inst
def calculate(inst, floor=0):
for (i, f) in enumerate(inst):
floor += f
if floor < 0:
break
return (sum(inst), i + 1)
def main(filepath):
(pt1, pt2) = calculate(read_file(filepath))
return (pt1, pt2)
print(main('1.txt'))
|
"""Exceptions for the Luftdaten Wrapper."""
class LuftdatenError(Exception):
"""General LuftdatenError exception occurred."""
pass
class LuftdatenConnectionError(LuftdatenError):
"""When a connection error is encountered."""
pass
class LuftdatenNoDataAvailable(LuftdatenError):
"""When no data is available."""
pass
|
"""Exceptions for the Luftdaten Wrapper."""
class Luftdatenerror(Exception):
"""General LuftdatenError exception occurred."""
pass
class Luftdatenconnectionerror(LuftdatenError):
"""When a connection error is encountered."""
pass
class Luftdatennodataavailable(LuftdatenError):
"""When no data is available."""
pass
|
def test_check_left_panel(app):
app.login(username="admin", password="admin")
app.main_page.get_menu_items_list()
app.main_page.check_all_admin_panel_items()
|
def test_check_left_panel(app):
app.login(username='admin', password='admin')
app.main_page.get_menu_items_list()
app.main_page.check_all_admin_panel_items()
|
#
# PySNMP MIB module ALVARION-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALVARION-SMI
# Produced by pysmi-0.3.4 at Mon Apr 29 17:06:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
IpAddress, Unsigned32, ObjectIdentity, TimeTicks, MibIdentifier, Integer32, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, enterprises, Gauge32, NotificationType, Counter32, Counter64, iso = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Unsigned32", "ObjectIdentity", "TimeTicks", "MibIdentifier", "Integer32", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "enterprises", "Gauge32", "NotificationType", "Counter32", "Counter64", "iso")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
alvarionWireless = ModuleIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10))
if mibBuilder.loadTexts: alvarionWireless.setLastUpdated('200710310000Z')
if mibBuilder.loadTexts: alvarionWireless.setOrganization('Alvarion Ltd.')
alvarionProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 1))
if mibBuilder.loadTexts: alvarionProducts.setStatus('current')
alvarionExperiment = ObjectIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 3))
if mibBuilder.loadTexts: alvarionExperiment.setStatus('current')
alvarionModules = ObjectIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 4))
if mibBuilder.loadTexts: alvarionModules.setStatus('current')
alvarionMgmtV2 = ObjectIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 5))
if mibBuilder.loadTexts: alvarionMgmtV2.setStatus('current')
variation = ObjectIdentity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 7))
if mibBuilder.loadTexts: variation.setStatus('current')
mibBuilder.exportSymbols("ALVARION-SMI", variation=variation, PYSNMP_MODULE_ID=alvarionWireless, alvarionProducts=alvarionProducts, alvarionWireless=alvarionWireless, alvarionModules=alvarionModules, alvarionMgmtV2=alvarionMgmtV2, alvarionExperiment=alvarionExperiment)
|
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(ip_address, unsigned32, object_identity, time_ticks, mib_identifier, integer32, module_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, enterprises, gauge32, notification_type, counter32, counter64, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Unsigned32', 'ObjectIdentity', 'TimeTicks', 'MibIdentifier', 'Integer32', 'ModuleIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'enterprises', 'Gauge32', 'NotificationType', 'Counter32', 'Counter64', 'iso')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
alvarion_wireless = module_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10))
if mibBuilder.loadTexts:
alvarionWireless.setLastUpdated('200710310000Z')
if mibBuilder.loadTexts:
alvarionWireless.setOrganization('Alvarion Ltd.')
alvarion_products = object_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 1))
if mibBuilder.loadTexts:
alvarionProducts.setStatus('current')
alvarion_experiment = object_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 3))
if mibBuilder.loadTexts:
alvarionExperiment.setStatus('current')
alvarion_modules = object_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 4))
if mibBuilder.loadTexts:
alvarionModules.setStatus('current')
alvarion_mgmt_v2 = object_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 5))
if mibBuilder.loadTexts:
alvarionMgmtV2.setStatus('current')
variation = object_identity((1, 3, 6, 1, 4, 1, 12394, 1, 10, 7))
if mibBuilder.loadTexts:
variation.setStatus('current')
mibBuilder.exportSymbols('ALVARION-SMI', variation=variation, PYSNMP_MODULE_ID=alvarionWireless, alvarionProducts=alvarionProducts, alvarionWireless=alvarionWireless, alvarionModules=alvarionModules, alvarionMgmtV2=alvarionMgmtV2, alvarionExperiment=alvarionExperiment)
|
_QUEUED_JOBS_KEY = 'projects:global:jobs:queued'
_ARCHIVED_JOBS_KEY = 'projects:global:jobs:archived'
def list_jobs(redis):
return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)}
def remove_jobs(redis, job_id_project_mapping):
for job_id, project_name in job_id_project_mapping.items():
redis.srem(_QUEUED_JOBS_KEY, job_id)
redis.srem('project:{}:jobs:queued'.format(project_name), job_id)
def job_project_names(redis, list_of_job_ids):
return {job_id: _job_project_name(redis, job_id) for job_id in list_of_job_ids}
def _job_project_name(redis, job_id):
project_name = redis.get('jobs:{}:project'.format(job_id))
if project_name:
return project_name.decode()
def add_jobs_to_archive(redis, list_of_job_ids):
for job_id in list_of_job_ids:
redis.sadd(_ARCHIVED_JOBS_KEY, job_id)
def list_archived_jobs(redis):
return {job_id.decode() for job_id in redis.smembers(_ARCHIVED_JOBS_KEY)}
|
_queued_jobs_key = 'projects:global:jobs:queued'
_archived_jobs_key = 'projects:global:jobs:archived'
def list_jobs(redis):
return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)}
def remove_jobs(redis, job_id_project_mapping):
for (job_id, project_name) in job_id_project_mapping.items():
redis.srem(_QUEUED_JOBS_KEY, job_id)
redis.srem('project:{}:jobs:queued'.format(project_name), job_id)
def job_project_names(redis, list_of_job_ids):
return {job_id: _job_project_name(redis, job_id) for job_id in list_of_job_ids}
def _job_project_name(redis, job_id):
project_name = redis.get('jobs:{}:project'.format(job_id))
if project_name:
return project_name.decode()
def add_jobs_to_archive(redis, list_of_job_ids):
for job_id in list_of_job_ids:
redis.sadd(_ARCHIVED_JOBS_KEY, job_id)
def list_archived_jobs(redis):
return {job_id.decode() for job_id in redis.smembers(_ARCHIVED_JOBS_KEY)}
|
#!/usr/bin/env python3
a = []
b = []
s = input()
while s != "end":
n = int(s)
if n % 2 == 1:
a.append(n)
else:
print(n)
s = input()
i = 0
while i < len(a):
print(a[i])
i = i + 1
|
a = []
b = []
s = input()
while s != 'end':
n = int(s)
if n % 2 == 1:
a.append(n)
else:
print(n)
s = input()
i = 0
while i < len(a):
print(a[i])
i = i + 1
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
"""config.py: Default configuration."""
# Server:
SERVER = 'wsgiref'
DOMAIN = 'localhost:7099'
HOST = 'localhost'
PORT = 7099
# Meta:
# Note on making it work in localhost:
# * Open a terminal, then do:
# - sudo gedit /etc/hosts
# * Enter the desired localhost alias for 127.0.0.1:
# - (e.g. 127.0.0.1 mydomain.tld)
# * Don't forget to save the file :)
BASE_URI = 'http://mydomain.tld'
GOOGLE_BASE_URI = 'http://localhost' # Google doesn't seem to accept
# non-working urls, but accepts localhost
# Facebook:
FACEBOOK_CLIENT_ID = 'NULL'
FACEBOOK_CLIENT_SECRET = 'NULL'
# Twitter:
TWITTER_CLIENT_ID = 'NULL'
TWITTER_CLIENT_SECRET = 'NULL'
# Google:
GOOGLE_CLIENT_ID = 'NULL'
GOOGLE_CLIENT_SECRET = 'NULL'
|
"""config.py: Default configuration."""
server = 'wsgiref'
domain = 'localhost:7099'
host = 'localhost'
port = 7099
base_uri = 'http://mydomain.tld'
google_base_uri = 'http://localhost'
facebook_client_id = 'NULL'
facebook_client_secret = 'NULL'
twitter_client_id = 'NULL'
twitter_client_secret = 'NULL'
google_client_id = 'NULL'
google_client_secret = 'NULL'
|
# Copyright 2021 The XLS Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build rules to compile with xlscc"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load(
"//xls/build_rules:xls_common_rules.bzl",
"append_default_to_args",
"args_to_string",
"get_output_filename_value",
"is_args_valid",
)
load(
"//xls/build_rules:xls_config_rules.bzl",
"CONFIG",
"enable_generated_file_wrapper",
)
load("//xls/build_rules:xls_providers.bzl", "ConvIRInfo")
load(
"//xls/build_rules:xls_ir_rules.bzl",
"append_xls_ir_opt_ir_generated_files",
"get_xls_ir_opt_ir_generated_files",
"xls_ir_opt_ir_attrs",
"xls_ir_opt_ir_impl",
)
load(
"//xls/build_rules:xls_codegen_rules.bzl",
"append_xls_ir_verilog_generated_files",
"get_xls_ir_verilog_generated_files",
"xls_ir_verilog_attrs",
"xls_ir_verilog_impl",
)
load("//xls/build_rules:xls_toolchains.bzl", "xls_toolchain_attr")
_CC_FILE_EXTENSION = ".cc"
_H_FILE_EXTENSION = ".h"
_INC_FILE_EXTENSION = ".inc"
_IR_FILE_EXTENSION = ".ir"
_PROTOBIN_FILE_EXTENSION = ".protobin"
_BINARYPB_FILE_EXTENSION = ".binarypb"
_DEFAULT_XLSCC_ARGS = {
"dump_ir_only": "True",
"top": "Run",
}
def _append_xls_cc_ir_generated_files(args, basename):
"""Returns a dictionary of arguments appended with filenames generated by the 'xls_cc_ir' rule.
Args:
args: A dictionary of arguments.
basename: The file basename.
Returns:
Returns a dictionary of arguments appended with filenames generated by the 'xls_cc_ir' rule.
"""
args.setdefault("ir_file", basename + _IR_FILE_EXTENSION)
return args
def _get_xls_cc_ir_generated_files(args):
"""Returns a list of filenames generated by the 'xls_cc_ir' rule found in 'args'.
Args:
args: A dictionary of arguments.
Returns:
Returns a list of files generated by the 'xls_cc_ir' rule found in 'args'.
"""
return [args.get("ir_file")]
def _get_runfiles_for_xls_cc_ir(ctx):
"""Returns the runfiles from a 'xls_cc_ir' ctx.
Args:
ctx: The current rule's context object.
Returns:
The runfiles from a 'xls_cc_ir' ctx.
"""
transitive_runfiles = []
runfiles = ctx.runfiles(files = [ctx.file.src] + [ctx.file.block] +
ctx.files._default_cc_header_files +
ctx.files._default_synthesis_header_files +
ctx.files.src_deps)
transitive_runfiles.append(ctx.attr
._xlscc_tool[DefaultInfo].default_runfiles)
transitive_runfiles.append(ctx.attr
._default_cc_header_files[DefaultInfo].default_runfiles)
transitive_runfiles.append(ctx.attr
._default_synthesis_header_files[DefaultInfo].default_runfiles)
for dep in ctx.attr.src_deps:
transitive_runfiles.append(dep[DefaultInfo].default_runfiles)
runfiles = runfiles.merge_all(transitive_runfiles)
return runfiles
def _get_transitive_built_files_for_xls_cc_ir(ctx):
"""Returns the transitive built files from a 'xls_cc_ir' ctx.
Args:
ctx: The current rule's context object.
Returns:
The transitive built files from a 'xls_cc_ir' ctx.
"""
transitive_built_files = []
transitive_built_files.append(ctx.attr.src[DefaultInfo].files)
transitive_built_files.append(ctx.attr.block[DefaultInfo].files)
transitive_built_files.append(ctx.attr._xlscc_tool[DefaultInfo].files)
transitive_built_files.append(ctx.attr
._default_cc_header_files[DefaultInfo].files)
transitive_built_files.append(ctx.attr
._default_synthesis_header_files[DefaultInfo].files)
for dep in ctx.attr.src_deps:
transitive_built_files.append(dep[DefaultInfo].files)
if not transitive_built_files:
return None
return transitive_built_files
def _xls_cc_ir_impl(ctx):
"""The implementation of the 'xls_cc_ir' rule.
Converts a C/C++ source file to an IR file.
Args:
ctx: The current rule's context object.
Returns:
A tuple with the following elements in the order presented:
1. The ConvIRInfo provider
1. The list of built files.
1. The runfiles.
"""
XLSCC_FLAGS = (
"module_name",
"block_pb",
"top",
"package",
"clang_args_file",
"defines",
"include_dirs",
"meta_out",
"dump_ir_only",
)
xlscc_args = append_default_to_args(
ctx.attr.xlscc_args,
_DEFAULT_XLSCC_ARGS,
)
# Append to user paths.
xlscc_args["include_dirs"] = (
xlscc_args.get("include_dirs", "") + ",${PWD},./," +
ctx.genfiles_dir.path + "," + ctx.bin_dir.path + "," +
"xls/contrib/xlscc/synth_only," +
"xls/contrib/xlscc/synth_only/ac_compat," +
ctx.attr._default_cc_header_files.label.workspace_root # This must the last directory in the list.
)
# Append to user defines.
xlscc_args["defines"] = (
xlscc_args.get("defines", "") + "__SYNTHESIS__," +
"__AC_OVERRIDE_OVF_UPDATE_BODY=,__AC_OVERRIDE_OVF_UPDATE2_BODY="
)
is_args_valid(xlscc_args, XLSCC_FLAGS)
my_args = args_to_string(xlscc_args)
ir_filename = get_output_filename_value(
ctx,
"ir_file",
ctx.attr.name + _IR_FILE_EXTENSION,
)
ir_file = ctx.actions.declare_file(ir_filename)
# Get runfiles
runfiles = _get_runfiles_for_xls_cc_ir(ctx)
ctx.actions.run_shell(
outputs = [ir_file],
# The IR converter executable is a tool needed by the action.
tools = [ctx.executable._xlscc_tool],
# The files required for converting the C/C++ source file.
inputs = runfiles.files,
command = "{} {} --block_pb {} {} > {}".format(
ctx.executable._xlscc_tool.path,
ctx.file.src.path,
ctx.file.block.path,
my_args,
ir_file.path,
),
mnemonic = "ConvertXLSCC",
progress_message = "Converting XLSCC file: %s" % (ctx.file.src.path),
)
return [ConvIRInfo(conv_ir_file = ir_file), [ir_file], runfiles]
_xls_cc_ir_attrs = {
"src": attr.label(
doc = "The C/C++ source file containing the top level block. A " +
"single source file must be provided. The file must have a '" +
_CC_FILE_EXTENSION + "' extension.",
mandatory = True,
allow_single_file = [_CC_FILE_EXTENSION],
),
"block": attr.label(
doc = "Protobuf describing top-level block interface. A single " +
"source file single source file must be provided. The file " +
"must have a '" + _PROTOBIN_FILE_EXTENSION + "' or a '" +
_BINARYPB_FILE_EXTENSION + "' extension.",
mandatory = True,
allow_single_file = [
_PROTOBIN_FILE_EXTENSION,
_BINARYPB_FILE_EXTENSION,
],
),
"src_deps": attr.label_list(
doc = "Additional source files for the rule. The file must have a " +
_CC_FILE_EXTENSION + ", " + _H_FILE_EXTENSION + " or " +
_INC_FILE_EXTENSION + " extension.",
allow_files = [
_CC_FILE_EXTENSION,
_H_FILE_EXTENSION,
_INC_FILE_EXTENSION,
],
),
"xlscc_args": attr.string_dict(
doc = "Arguments of the XLSCC conversion tool.",
),
"ir_file": attr.output(
doc = "Filename of the generated IR. If not specified, the " +
"target name of the bazel rule followed by an " +
_IR_FILE_EXTENSION + " extension is used.",
),
"_xlscc_tool": attr.label(
doc = "The target of the XLSCC executable.",
default = Label("//xls/contrib/xlscc:xlscc"),
allow_single_file = True,
executable = True,
cfg = "exec",
),
"_default_cc_header_files": attr.label(
doc = "Default C/C++ header files for xlscc.",
default = Label("@com_github_hlslibs_ac_types//:ac_types_as_data"),
cfg = "target",
),
"_default_synthesis_header_files": attr.label(
doc = "Default synthesis header files for xlscc.",
default = Label("//xls/contrib/xlscc:synth_only_headers"),
cfg = "target",
),
}
def _xls_cc_ir_impl_wrapper(ctx):
"""The implementation of the 'xls_cc_ir' rule.
Wrapper for xls_cc_ir_impl. See: xls_cc_ir_impl.
Args:
ctx: The current rule's context object.
Returns:
ConvIRInfo provider
DefaultInfo provider
"""
ir_conv_info, built_files, runfiles = _xls_cc_ir_impl(ctx)
return [
ir_conv_info,
DefaultInfo(
files = depset(
direct = built_files,
transitive = _get_transitive_built_files_for_xls_cc_ir(ctx),
),
runfiles = runfiles,
),
]
xls_cc_ir = rule(
doc = """A build rule that converts a C/C++ source file to an IR file.
Examples:
1) A simple IR conversion example. Assume target 'a_block_pb' is
defined.
```
xls_cc_ir(
name = "a_ir",
src = "a.cc",
block = ":a_block_pb",
)
```
""",
implementation = _xls_cc_ir_impl_wrapper,
attrs = dicts.add(
_xls_cc_ir_attrs,
CONFIG["xls_outs_attrs"],
),
)
def xls_cc_ir_macro(
name,
src,
block,
src_deps = [],
xlscc_args = {},
enable_generated_file = True,
enable_presubmit_generated_file = False,
**kwargs):
"""A macro that instantiates a build rule generating an IR file from a C/C++ source file.
The macro instantiates a rule that converts a C/C++ source file to an IR
file and the 'enable_generated_file_wrapper' function. The generated files
are listed in the outs attribute of the rule.
Examples:
1) A simple IR conversion example. Assume target 'a_block_pb' is defined.
```
xls_cc_ir(
name = "a_ir",
src = "a.cc",
block = ":a_block_pb",
)
```
Args:
name: The name of the rule.
src: The C/C++ source file containing the top level block. A single source
file must be provided. The file must have a '.cc' extension.
block: Protobuf describing top-level block interface. A single source file
single source file must be provided. The file must have a '.protobin'
or a '.binarypb' extension.
src_deps: Additional source files for the rule. The file must have a
'.cc', '.h' or '.inc' extension.
xlscc_args: Arguments of the XLSCC conversion tool.
enable_generated_file: See 'enable_generated_file' from
'enable_generated_file_wrapper' function.
enable_presubmit_generated_file: See 'enable_presubmit_generated_file'
from 'enable_generated_file_wrapper' function.
**kwargs: Keyword arguments. Named arguments.
"""
# Type check input
if type(name) != type(""):
fail("Argument 'name' must be of string type.")
if type(src) != type(""):
fail("Argument 'src' must be of string type.")
if type(block) != type(""):
fail("Argument 'block' must be of string type.")
if type(src_deps) != type([]):
fail("Argument 'src_deps' must be of list type.")
if type(xlscc_args) != type({}):
fail("Argument 'xlscc_args' must be of dictionary type.")
if type(enable_generated_file) != type(True):
fail("Argument 'enable_generated_file' must be of boolean type.")
if type(enable_presubmit_generated_file) != type(True):
fail("Argument 'enable_presubmit_generated_file' must be " +
"of boolean type.")
# Append output files to arguments.
kwargs = _append_xls_cc_ir_generated_files(kwargs, name)
xls_cc_ir(
name = name,
src = src,
block = block,
src_deps = src_deps,
xlscc_args = xlscc_args,
outs = _get_xls_cc_ir_generated_files(kwargs),
**kwargs
)
enable_generated_file_wrapper(
wrapped_target = name,
enable_generated_file = enable_generated_file,
enable_presubmit_generated_file = enable_presubmit_generated_file,
**kwargs
)
def _xls_cc_verilog_impl(ctx):
"""The implementation of the 'xls_cc_verilog' rule.
Converts a C/C++ file to an IR, optimizes the IR, and generates a verilog
file from the optimized IR.
Args:
ctx: The current rule's context object.
Returns:
ConvIRInfo provider.
OptIRInfo provider.
CodegenInfo provider.
DefaultInfo provider.
"""
ir_conv_info, ir_conv_built_files, ir_conv_runfiles = _xls_cc_ir_impl(ctx)
ir_opt_info, opt_ir_built_files, opt_ir_runfiles = xls_ir_opt_ir_impl(
ctx,
ir_conv_info.conv_ir_file,
)
codegen_info, verilog_built_files, verilog_runfiles = xls_ir_verilog_impl(
ctx,
ir_opt_info.opt_ir_file,
)
runfiles = ir_conv_runfiles.merge_all([opt_ir_runfiles, verilog_runfiles])
return [
ir_conv_info,
ir_opt_info,
codegen_info,
DefaultInfo(
files = depset(
direct = ir_conv_built_files + opt_ir_built_files +
verilog_built_files,
transitive = _get_transitive_built_files_for_xls_cc_ir(ctx),
),
runfiles = runfiles,
),
]
_cc_verilog_attrs = dicts.add(
_xls_cc_ir_attrs,
xls_ir_opt_ir_attrs,
xls_ir_verilog_attrs,
CONFIG["xls_outs_attrs"],
xls_toolchain_attr,
)
xls_cc_verilog = rule(
doc = """A build rule that generates a Verilog file from a C/C++ source file.
Examples:
1) A simple example. Assume target 'a_block_pb' is defined.
```
xls_cc_verilog(
name = "a_verilog",
src = "a.cc",
block = ":a_block_pb",
codegen_args = {
"generator": "combinational",
"module_name": "A",
"top": "A_proc",
},
)
```
""",
implementation = _xls_cc_verilog_impl,
attrs = _cc_verilog_attrs,
)
def xls_cc_verilog_macro(
name,
src,
block,
verilog_file,
src_deps = [],
xlscc_args = {},
opt_ir_args = {},
codegen_args = {},
enable_generated_file = True,
enable_presubmit_generated_file = False,
**kwargs):
"""A macro that instantiates a build rule generating a Verilog file from a C/C++ source file.
The macro instantiates a build rule that generates an Verilog file from
a DSLX source file. The build rule executes the core functionality of
following macros:
1. xls_cc_ir (converts a C/C++ file to an IR),
1. xls_ir_opt_ir (optimizes the IR), and,
1. xls_ir_verilog (generated a Verilog file).
Examples:
1) A simple example. Assume target 'a_block_pb' is defined.
```
xls_cc_verilog(
name = "a_verilog",
src = "a.cc",
block = ":a_block_pb",
codegen_args = {
"generator": "combinational",
"module_name": "A",
"top": "A_proc",
},
)
```
Args:
name: The name of the rule.
src: The C/C++ source file containing the top level block. A single source
file must be provided. The file must have a '.cc' extension.
block: Protobuf describing top-level block interface. A single source file
single source file must be provided. The file must have a '.protobin'
or a '.binarypb' extension.
verilog_file: The filename of Verilog file generated. The filename must
have a '.v' extension.
src_deps: Additional source files for the rule. The file must have a
'.cc', '.h' or '.inc' extension.
xlscc_args: Arguments of the XLSCC conversion tool.
opt_ir_args: Arguments of the IR optimizer tool. For details on the
arguments, refer to the opt_main application at
//xls/tools/opt_main.cc. Note: the 'top'
argument is not assigned using this attribute.
codegen_args: Arguments of the codegen tool. For details on the arguments,
refer to the codegen_main application at
//xls/tools/codegen_main.cc.
enable_generated_file: See 'enable_generated_file' from
'enable_generated_file_wrapper' function.
enable_presubmit_generated_file: See 'enable_presubmit_generated_file'
from 'enable_generated_file_wrapper' function.
**kwargs: Keyword arguments. Named arguments.
"""
# Type check input
if type(name) != type(""):
fail("Argument 'name' must be of string type.")
if type(src) != type(""):
fail("Argument 'src' must be of string type.")
if type(block) != type(""):
fail("Argument 'block' must be of string type.")
if type(verilog_file) != type(""):
fail("Argument 'verilog_file' must be of string type.")
if type(src_deps) != type([]):
fail("Argument 'src_deps' must be of list type.")
if type(xlscc_args) != type({}):
fail("Argument 'xlscc_args' must be of dictionary type.")
if type(opt_ir_args) != type({}):
fail("Argument 'opt_ir_args' must be of dictionary type.")
if type(codegen_args) != type({}):
fail("Argument 'codegen_args' must be of dictionary type.")
if type(enable_generated_file) != type(True):
fail("Argument 'enable_generated_file' must be of boolean type.")
if type(enable_presubmit_generated_file) != type(True):
fail("Argument 'enable_presubmit_generated_file' must be " +
"of boolean type.")
# Append output files to arguments.
kwargs = _append_xls_cc_ir_generated_files(kwargs, name)
kwargs = append_xls_ir_opt_ir_generated_files(kwargs, name)
kwargs = append_xls_ir_verilog_generated_files(kwargs, name, codegen_args)
xls_cc_verilog(
name = name,
src = src,
block = block,
verilog_file = verilog_file,
src_deps = src_deps,
xlscc_args = xlscc_args,
opt_ir_args = opt_ir_args,
codegen_args = codegen_args,
outs = _get_xls_cc_ir_generated_files(kwargs) +
get_xls_ir_opt_ir_generated_files(kwargs) +
get_xls_ir_verilog_generated_files(kwargs, codegen_args) +
[verilog_file],
**kwargs
)
enable_generated_file_wrapper(
wrapped_target = name,
enable_generated_file = enable_generated_file,
enable_presubmit_generated_file = enable_presubmit_generated_file,
**kwargs
)
|
"""Build rules to compile with xlscc"""
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
load('//xls/build_rules:xls_common_rules.bzl', 'append_default_to_args', 'args_to_string', 'get_output_filename_value', 'is_args_valid')
load('//xls/build_rules:xls_config_rules.bzl', 'CONFIG', 'enable_generated_file_wrapper')
load('//xls/build_rules:xls_providers.bzl', 'ConvIRInfo')
load('//xls/build_rules:xls_ir_rules.bzl', 'append_xls_ir_opt_ir_generated_files', 'get_xls_ir_opt_ir_generated_files', 'xls_ir_opt_ir_attrs', 'xls_ir_opt_ir_impl')
load('//xls/build_rules:xls_codegen_rules.bzl', 'append_xls_ir_verilog_generated_files', 'get_xls_ir_verilog_generated_files', 'xls_ir_verilog_attrs', 'xls_ir_verilog_impl')
load('//xls/build_rules:xls_toolchains.bzl', 'xls_toolchain_attr')
_cc_file_extension = '.cc'
_h_file_extension = '.h'
_inc_file_extension = '.inc'
_ir_file_extension = '.ir'
_protobin_file_extension = '.protobin'
_binarypb_file_extension = '.binarypb'
_default_xlscc_args = {'dump_ir_only': 'True', 'top': 'Run'}
def _append_xls_cc_ir_generated_files(args, basename):
"""Returns a dictionary of arguments appended with filenames generated by the 'xls_cc_ir' rule.
Args:
args: A dictionary of arguments.
basename: The file basename.
Returns:
Returns a dictionary of arguments appended with filenames generated by the 'xls_cc_ir' rule.
"""
args.setdefault('ir_file', basename + _IR_FILE_EXTENSION)
return args
def _get_xls_cc_ir_generated_files(args):
"""Returns a list of filenames generated by the 'xls_cc_ir' rule found in 'args'.
Args:
args: A dictionary of arguments.
Returns:
Returns a list of files generated by the 'xls_cc_ir' rule found in 'args'.
"""
return [args.get('ir_file')]
def _get_runfiles_for_xls_cc_ir(ctx):
"""Returns the runfiles from a 'xls_cc_ir' ctx.
Args:
ctx: The current rule's context object.
Returns:
The runfiles from a 'xls_cc_ir' ctx.
"""
transitive_runfiles = []
runfiles = ctx.runfiles(files=[ctx.file.src] + [ctx.file.block] + ctx.files._default_cc_header_files + ctx.files._default_synthesis_header_files + ctx.files.src_deps)
transitive_runfiles.append(ctx.attr._xlscc_tool[DefaultInfo].default_runfiles)
transitive_runfiles.append(ctx.attr._default_cc_header_files[DefaultInfo].default_runfiles)
transitive_runfiles.append(ctx.attr._default_synthesis_header_files[DefaultInfo].default_runfiles)
for dep in ctx.attr.src_deps:
transitive_runfiles.append(dep[DefaultInfo].default_runfiles)
runfiles = runfiles.merge_all(transitive_runfiles)
return runfiles
def _get_transitive_built_files_for_xls_cc_ir(ctx):
"""Returns the transitive built files from a 'xls_cc_ir' ctx.
Args:
ctx: The current rule's context object.
Returns:
The transitive built files from a 'xls_cc_ir' ctx.
"""
transitive_built_files = []
transitive_built_files.append(ctx.attr.src[DefaultInfo].files)
transitive_built_files.append(ctx.attr.block[DefaultInfo].files)
transitive_built_files.append(ctx.attr._xlscc_tool[DefaultInfo].files)
transitive_built_files.append(ctx.attr._default_cc_header_files[DefaultInfo].files)
transitive_built_files.append(ctx.attr._default_synthesis_header_files[DefaultInfo].files)
for dep in ctx.attr.src_deps:
transitive_built_files.append(dep[DefaultInfo].files)
if not transitive_built_files:
return None
return transitive_built_files
def _xls_cc_ir_impl(ctx):
"""The implementation of the 'xls_cc_ir' rule.
Converts a C/C++ source file to an IR file.
Args:
ctx: The current rule's context object.
Returns:
A tuple with the following elements in the order presented:
1. The ConvIRInfo provider
1. The list of built files.
1. The runfiles.
"""
xlscc_flags = ('module_name', 'block_pb', 'top', 'package', 'clang_args_file', 'defines', 'include_dirs', 'meta_out', 'dump_ir_only')
xlscc_args = append_default_to_args(ctx.attr.xlscc_args, _DEFAULT_XLSCC_ARGS)
xlscc_args['include_dirs'] = xlscc_args.get('include_dirs', '') + ',${PWD},./,' + ctx.genfiles_dir.path + ',' + ctx.bin_dir.path + ',' + 'xls/contrib/xlscc/synth_only,' + 'xls/contrib/xlscc/synth_only/ac_compat,' + ctx.attr._default_cc_header_files.label.workspace_root
xlscc_args['defines'] = xlscc_args.get('defines', '') + '__SYNTHESIS__,' + '__AC_OVERRIDE_OVF_UPDATE_BODY=,__AC_OVERRIDE_OVF_UPDATE2_BODY='
is_args_valid(xlscc_args, XLSCC_FLAGS)
my_args = args_to_string(xlscc_args)
ir_filename = get_output_filename_value(ctx, 'ir_file', ctx.attr.name + _IR_FILE_EXTENSION)
ir_file = ctx.actions.declare_file(ir_filename)
runfiles = _get_runfiles_for_xls_cc_ir(ctx)
ctx.actions.run_shell(outputs=[ir_file], tools=[ctx.executable._xlscc_tool], inputs=runfiles.files, command='{} {} --block_pb {} {} > {}'.format(ctx.executable._xlscc_tool.path, ctx.file.src.path, ctx.file.block.path, my_args, ir_file.path), mnemonic='ConvertXLSCC', progress_message='Converting XLSCC file: %s' % ctx.file.src.path)
return [conv_ir_info(conv_ir_file=ir_file), [ir_file], runfiles]
_xls_cc_ir_attrs = {'src': attr.label(doc='The C/C++ source file containing the top level block. A ' + "single source file must be provided. The file must have a '" + _CC_FILE_EXTENSION + "' extension.", mandatory=True, allow_single_file=[_CC_FILE_EXTENSION]), 'block': attr.label(doc='Protobuf describing top-level block interface. A single ' + 'source file single source file must be provided. The file ' + "must have a '" + _PROTOBIN_FILE_EXTENSION + "' or a '" + _BINARYPB_FILE_EXTENSION + "' extension.", mandatory=True, allow_single_file=[_PROTOBIN_FILE_EXTENSION, _BINARYPB_FILE_EXTENSION]), 'src_deps': attr.label_list(doc='Additional source files for the rule. The file must have a ' + _CC_FILE_EXTENSION + ', ' + _H_FILE_EXTENSION + ' or ' + _INC_FILE_EXTENSION + ' extension.', allow_files=[_CC_FILE_EXTENSION, _H_FILE_EXTENSION, _INC_FILE_EXTENSION]), 'xlscc_args': attr.string_dict(doc='Arguments of the XLSCC conversion tool.'), 'ir_file': attr.output(doc='Filename of the generated IR. If not specified, the ' + 'target name of the bazel rule followed by an ' + _IR_FILE_EXTENSION + ' extension is used.'), '_xlscc_tool': attr.label(doc='The target of the XLSCC executable.', default=label('//xls/contrib/xlscc:xlscc'), allow_single_file=True, executable=True, cfg='exec'), '_default_cc_header_files': attr.label(doc='Default C/C++ header files for xlscc.', default=label('@com_github_hlslibs_ac_types//:ac_types_as_data'), cfg='target'), '_default_synthesis_header_files': attr.label(doc='Default synthesis header files for xlscc.', default=label('//xls/contrib/xlscc:synth_only_headers'), cfg='target')}
def _xls_cc_ir_impl_wrapper(ctx):
"""The implementation of the 'xls_cc_ir' rule.
Wrapper for xls_cc_ir_impl. See: xls_cc_ir_impl.
Args:
ctx: The current rule's context object.
Returns:
ConvIRInfo provider
DefaultInfo provider
"""
(ir_conv_info, built_files, runfiles) = _xls_cc_ir_impl(ctx)
return [ir_conv_info, default_info(files=depset(direct=built_files, transitive=_get_transitive_built_files_for_xls_cc_ir(ctx)), runfiles=runfiles)]
xls_cc_ir = rule(doc='A build rule that converts a C/C++ source file to an IR file.\n\nExamples:\n\n1) A simple IR conversion example. Assume target \'a_block_pb\' is\ndefined.\n\n```\n xls_cc_ir(\n name = "a_ir",\n src = "a.cc",\n block = ":a_block_pb",\n )\n```\n ', implementation=_xls_cc_ir_impl_wrapper, attrs=dicts.add(_xls_cc_ir_attrs, CONFIG['xls_outs_attrs']))
def xls_cc_ir_macro(name, src, block, src_deps=[], xlscc_args={}, enable_generated_file=True, enable_presubmit_generated_file=False, **kwargs):
"""A macro that instantiates a build rule generating an IR file from a C/C++ source file.
The macro instantiates a rule that converts a C/C++ source file to an IR
file and the 'enable_generated_file_wrapper' function. The generated files
are listed in the outs attribute of the rule.
Examples:
1) A simple IR conversion example. Assume target 'a_block_pb' is defined.
```
xls_cc_ir(
name = "a_ir",
src = "a.cc",
block = ":a_block_pb",
)
```
Args:
name: The name of the rule.
src: The C/C++ source file containing the top level block. A single source
file must be provided. The file must have a '.cc' extension.
block: Protobuf describing top-level block interface. A single source file
single source file must be provided. The file must have a '.protobin'
or a '.binarypb' extension.
src_deps: Additional source files for the rule. The file must have a
'.cc', '.h' or '.inc' extension.
xlscc_args: Arguments of the XLSCC conversion tool.
enable_generated_file: See 'enable_generated_file' from
'enable_generated_file_wrapper' function.
enable_presubmit_generated_file: See 'enable_presubmit_generated_file'
from 'enable_generated_file_wrapper' function.
**kwargs: Keyword arguments. Named arguments.
"""
if type(name) != type(''):
fail("Argument 'name' must be of string type.")
if type(src) != type(''):
fail("Argument 'src' must be of string type.")
if type(block) != type(''):
fail("Argument 'block' must be of string type.")
if type(src_deps) != type([]):
fail("Argument 'src_deps' must be of list type.")
if type(xlscc_args) != type({}):
fail("Argument 'xlscc_args' must be of dictionary type.")
if type(enable_generated_file) != type(True):
fail("Argument 'enable_generated_file' must be of boolean type.")
if type(enable_presubmit_generated_file) != type(True):
fail("Argument 'enable_presubmit_generated_file' must be " + 'of boolean type.')
kwargs = _append_xls_cc_ir_generated_files(kwargs, name)
xls_cc_ir(name=name, src=src, block=block, src_deps=src_deps, xlscc_args=xlscc_args, outs=_get_xls_cc_ir_generated_files(kwargs), **kwargs)
enable_generated_file_wrapper(wrapped_target=name, enable_generated_file=enable_generated_file, enable_presubmit_generated_file=enable_presubmit_generated_file, **kwargs)
def _xls_cc_verilog_impl(ctx):
"""The implementation of the 'xls_cc_verilog' rule.
Converts a C/C++ file to an IR, optimizes the IR, and generates a verilog
file from the optimized IR.
Args:
ctx: The current rule's context object.
Returns:
ConvIRInfo provider.
OptIRInfo provider.
CodegenInfo provider.
DefaultInfo provider.
"""
(ir_conv_info, ir_conv_built_files, ir_conv_runfiles) = _xls_cc_ir_impl(ctx)
(ir_opt_info, opt_ir_built_files, opt_ir_runfiles) = xls_ir_opt_ir_impl(ctx, ir_conv_info.conv_ir_file)
(codegen_info, verilog_built_files, verilog_runfiles) = xls_ir_verilog_impl(ctx, ir_opt_info.opt_ir_file)
runfiles = ir_conv_runfiles.merge_all([opt_ir_runfiles, verilog_runfiles])
return [ir_conv_info, ir_opt_info, codegen_info, default_info(files=depset(direct=ir_conv_built_files + opt_ir_built_files + verilog_built_files, transitive=_get_transitive_built_files_for_xls_cc_ir(ctx)), runfiles=runfiles)]
_cc_verilog_attrs = dicts.add(_xls_cc_ir_attrs, xls_ir_opt_ir_attrs, xls_ir_verilog_attrs, CONFIG['xls_outs_attrs'], xls_toolchain_attr)
xls_cc_verilog = rule(doc='A build rule that generates a Verilog file from a C/C++ source file.\n\nExamples:\n\n1) A simple example. Assume target \'a_block_pb\' is defined.\n\n```\n xls_cc_verilog(\n name = "a_verilog",\n src = "a.cc",\n block = ":a_block_pb",\n codegen_args = {\n "generator": "combinational",\n "module_name": "A",\n "top": "A_proc",\n },\n )\n```\n ', implementation=_xls_cc_verilog_impl, attrs=_cc_verilog_attrs)
def xls_cc_verilog_macro(name, src, block, verilog_file, src_deps=[], xlscc_args={}, opt_ir_args={}, codegen_args={}, enable_generated_file=True, enable_presubmit_generated_file=False, **kwargs):
"""A macro that instantiates a build rule generating a Verilog file from a C/C++ source file.
The macro instantiates a build rule that generates an Verilog file from
a DSLX source file. The build rule executes the core functionality of
following macros:
1. xls_cc_ir (converts a C/C++ file to an IR),
1. xls_ir_opt_ir (optimizes the IR), and,
1. xls_ir_verilog (generated a Verilog file).
Examples:
1) A simple example. Assume target 'a_block_pb' is defined.
```
xls_cc_verilog(
name = "a_verilog",
src = "a.cc",
block = ":a_block_pb",
codegen_args = {
"generator": "combinational",
"module_name": "A",
"top": "A_proc",
},
)
```
Args:
name: The name of the rule.
src: The C/C++ source file containing the top level block. A single source
file must be provided. The file must have a '.cc' extension.
block: Protobuf describing top-level block interface. A single source file
single source file must be provided. The file must have a '.protobin'
or a '.binarypb' extension.
verilog_file: The filename of Verilog file generated. The filename must
have a '.v' extension.
src_deps: Additional source files for the rule. The file must have a
'.cc', '.h' or '.inc' extension.
xlscc_args: Arguments of the XLSCC conversion tool.
opt_ir_args: Arguments of the IR optimizer tool. For details on the
arguments, refer to the opt_main application at
//xls/tools/opt_main.cc. Note: the 'top'
argument is not assigned using this attribute.
codegen_args: Arguments of the codegen tool. For details on the arguments,
refer to the codegen_main application at
//xls/tools/codegen_main.cc.
enable_generated_file: See 'enable_generated_file' from
'enable_generated_file_wrapper' function.
enable_presubmit_generated_file: See 'enable_presubmit_generated_file'
from 'enable_generated_file_wrapper' function.
**kwargs: Keyword arguments. Named arguments.
"""
if type(name) != type(''):
fail("Argument 'name' must be of string type.")
if type(src) != type(''):
fail("Argument 'src' must be of string type.")
if type(block) != type(''):
fail("Argument 'block' must be of string type.")
if type(verilog_file) != type(''):
fail("Argument 'verilog_file' must be of string type.")
if type(src_deps) != type([]):
fail("Argument 'src_deps' must be of list type.")
if type(xlscc_args) != type({}):
fail("Argument 'xlscc_args' must be of dictionary type.")
if type(opt_ir_args) != type({}):
fail("Argument 'opt_ir_args' must be of dictionary type.")
if type(codegen_args) != type({}):
fail("Argument 'codegen_args' must be of dictionary type.")
if type(enable_generated_file) != type(True):
fail("Argument 'enable_generated_file' must be of boolean type.")
if type(enable_presubmit_generated_file) != type(True):
fail("Argument 'enable_presubmit_generated_file' must be " + 'of boolean type.')
kwargs = _append_xls_cc_ir_generated_files(kwargs, name)
kwargs = append_xls_ir_opt_ir_generated_files(kwargs, name)
kwargs = append_xls_ir_verilog_generated_files(kwargs, name, codegen_args)
xls_cc_verilog(name=name, src=src, block=block, verilog_file=verilog_file, src_deps=src_deps, xlscc_args=xlscc_args, opt_ir_args=opt_ir_args, codegen_args=codegen_args, outs=_get_xls_cc_ir_generated_files(kwargs) + get_xls_ir_opt_ir_generated_files(kwargs) + get_xls_ir_verilog_generated_files(kwargs, codegen_args) + [verilog_file], **kwargs)
enable_generated_file_wrapper(wrapped_target=name, enable_generated_file=enable_generated_file, enable_presubmit_generated_file=enable_presubmit_generated_file, **kwargs)
|
class InvalidBitstringError(BaseException):
pass
class InvalidQuantumKeyError(BaseException):
pass
|
class Invalidbitstringerror(BaseException):
pass
class Invalidquantumkeyerror(BaseException):
pass
|
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
ans = []
nums.sort()
for i in range(0, len(nums)-2):
if nums[i] > 0:
break
if i > 0 and nums[i-1] == nums[i]:
continue
left, right = i+1, len(nums)-1
while right > left:
s = nums[left] + nums[right] + nums[i]
if s == 0:
ans.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while right > left and nums[left] == nums[left-1]:
left += 1
while right > left and nums[right] == nums[right+1]:
right -= 1
elif s < 0:
left += 1
else:
right -= 1
return ans
|
class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
ans = []
nums.sort()
for i in range(0, len(nums) - 2):
if nums[i] > 0:
break
if i > 0 and nums[i - 1] == nums[i]:
continue
(left, right) = (i + 1, len(nums) - 1)
while right > left:
s = nums[left] + nums[right] + nums[i]
if s == 0:
ans.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while right > left and nums[left] == nums[left - 1]:
left += 1
while right > left and nums[right] == nums[right + 1]:
right -= 1
elif s < 0:
left += 1
else:
right -= 1
return ans
|
def sum_all(ls):
sum = 0
if(len(ls) != 2):
print("Invalid input")
else:
ls.sort()
start = ls[0]
end = ls[1]
if(start == end):
sum = 2 * start
else:
for i in range(start, end+1):
sum += i
return sum
|
def sum_all(ls):
sum = 0
if len(ls) != 2:
print('Invalid input')
else:
ls.sort()
start = ls[0]
end = ls[1]
if start == end:
sum = 2 * start
else:
for i in range(start, end + 1):
sum += i
return sum
|
# Primitive reimplementation of the buildflag_header scripts used in the gn build
def _buildflag_header_impl(ctx):
content = "// Generated by build/buildflag_header.bzl\n"
content += '// From "' + ctx.attr.name + '"\n'
content += "\n#ifndef %s_h\n" % ctx.attr.name
content += "#define %s_h\n\n" % ctx.attr.name
content += '#include "build/buildflag.h"\n\n'
for key in ctx.attr.flags:
content += "#define BUILDFLAG_INTERNAL_%s() (%s)\n" % (key, ctx.attr.flags[key])
content += "\n#endif // %s_h\n" % ctx.attr.name
ctx.actions.write(output = ctx.outputs.header, content = content)
buildflag_header = rule(
implementation = _buildflag_header_impl,
attrs = {
"flags": attr.string_dict(mandatory = True),
"header": attr.string(mandatory = True),
"header_dir": attr.string(),
},
outputs = {"header": "%{header_dir}%{header}"},
output_to_genfiles = True,
)
|
def _buildflag_header_impl(ctx):
content = '// Generated by build/buildflag_header.bzl\n'
content += '// From "' + ctx.attr.name + '"\n'
content += '\n#ifndef %s_h\n' % ctx.attr.name
content += '#define %s_h\n\n' % ctx.attr.name
content += '#include "build/buildflag.h"\n\n'
for key in ctx.attr.flags:
content += '#define BUILDFLAG_INTERNAL_%s() (%s)\n' % (key, ctx.attr.flags[key])
content += '\n#endif // %s_h\n' % ctx.attr.name
ctx.actions.write(output=ctx.outputs.header, content=content)
buildflag_header = rule(implementation=_buildflag_header_impl, attrs={'flags': attr.string_dict(mandatory=True), 'header': attr.string(mandatory=True), 'header_dir': attr.string()}, outputs={'header': '%{header_dir}%{header}'}, output_to_genfiles=True)
|
# Space: O(n)
# Time: O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root):
if (root is None) or (root.left is None and root.right is None): return root
def inorder_traversal(root):
if root is None: return []
res = []
left = inorder_traversal(root.left)
res.append(root.val)
right = inorder_traversal(root.right)
return left + res + right
def update_BST(adict, root):
queue = [root]
while queue:
cur = queue.pop(0)
# print(cur.val)
cur.val = adict[cur.val]
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return root
inorder_traversal_res = inorder_traversal(root)
cache = {}
for i in range(len(inorder_traversal_res)):
cache[inorder_traversal_res[i]] = sum(inorder_traversal_res[i:])
return update_BST(cache, root)
|
class Solution:
def convert_bst(self, root):
if root is None or (root.left is None and root.right is None):
return root
def inorder_traversal(root):
if root is None:
return []
res = []
left = inorder_traversal(root.left)
res.append(root.val)
right = inorder_traversal(root.right)
return left + res + right
def update_bst(adict, root):
queue = [root]
while queue:
cur = queue.pop(0)
cur.val = adict[cur.val]
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return root
inorder_traversal_res = inorder_traversal(root)
cache = {}
for i in range(len(inorder_traversal_res)):
cache[inorder_traversal_res[i]] = sum(inorder_traversal_res[i:])
return update_bst(cache, root)
|
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULTIPLY NOT NULL NUMBER OR PLACEHOLDER PLUS RBRACE RBRACKET RETURN RPAREN SEMICOLON STRING WHILEstatement_list : statement statement_list\n | emptyempty :statement : IMPORT STRING SEMICOLONstatement : assignment SEMICOLONstatement : conditionalstatement : expr SEMICOLONstatement : macro_defstatement : macro_callassignment : l_value EQUAL r_valuestatement : looploop : WHILE LPAREN expr RPAREN LBRACE statement_list RBRACEstatement : fun_deffun_def : FUN ID LPAREN id_list RPAREN LBRACE statement_list RBRACEstatement : RETURN expr SEMICOLONid_list : IDid_list : ID COMMA id_listid_list : emptyconditional : IF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif conditional_elseconditional_elif : ELIF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elifconditional_elif : emptyconditional_else : ELSE LBRACE statement_list RBRACEconditional_else : emptyr_value : exprl_value : IDl_value : ID fieldsl_value : PLACEHOLDERl_value : PLACEHOLDER fieldsfields : LBRACKET expr RBRACKETfields : LBRACKET expr RBRACKET fieldsexpr : alg_opexpr : STRINGexpr : NUMBERexpr : BOOLexpr : NULLexpr : func_callexpr : IDexpr : LPAREN expr RPARENexpr : anonymous_fun func_call : ID LPAREN arg_list RPARENarg_list : emptyarg_list : exprarg_list : expr COMMA arg_listalg_op : expr PLUS expr\n | expr MINUS expr\n | expr MULTIPLY expr\n | expr DIVIDE exprexpr : LBRACKET arg_list RBRACKETexpr : LBRACE record_list RBRACEexpr : LPAREN statement_list RPARENrecord_list : ID COLON exprrecord_list : ID COLON expr COMMA record_listrecord_list : emptyexpr : expr LBRACKET expr RBRACKETexpr : comp_opexpr : PLACEHOLDERcomp_op : expr EQUAL EQUAL exprcomp_op : expr BANG EQUAL exprcomp_op : expr GT exprcomp_op : expr GT EQUAL exprcomp_op : expr LT exprcomp_op : expr LT EQUAL exprexpr : log_oplog_op : expr AND exprlog_op : expr OR exprlog_op : NOT exprmacro_def : MAC macro_def_arg_list LBRACE statement_list RBRACEmacro_def_arg_list : ATOM macro_def_arg_list_recmacro_def_arg_list_rec : PLACEHOLDER macro_def_arg_list_recmacro_def_arg_list_rec : ATOM macro_def_arg_list_recmacro_def_arg_list_rec : emptymacro_call : ATOM macro_arg_list SEMICOLONmacro_arg_list : ATOM macro_arg_listmacro_arg_list : expr macro_arg_listmacro_arg_list : emptyanonymous_fun : LPAREN id_list RPAREN LBRACE statement_list RBRACE'
_lr_action_items = {'IMPORT':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[4,4,-6,-8,-9,-11,-13,4,-5,-7,-4,-15,4,-72,4,4,-67,4,4,-3,-12,-3,-21,-14,-19,-23,4,-22,4,-3,-20,]),'RETURN':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[13,13,-6,-8,-9,-11,-13,13,-5,-7,-4,-15,13,-72,13,13,-67,13,13,-3,-12,-3,-21,-14,-19,-23,13,-22,13,-3,-20,]),'$end':([0,1,2,3,7,9,10,11,12,34,36,37,78,92,112,141,149,150,152,154,155,156,158,164,167,168,],[-3,0,-3,-2,-6,-8,-9,-11,-13,-1,-5,-7,-4,-15,-72,-67,-3,-12,-3,-21,-14,-19,-23,-22,-3,-20,]),'IF':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[15,15,-6,-8,-9,-11,-13,15,-5,-7,-4,-15,15,-72,15,15,-67,15,15,-3,-12,-3,-21,-14,-19,-23,15,-22,15,-3,-20,]),'STRING':([0,2,4,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[5,5,35,-32,-6,-8,-9,-11,-13,5,5,-31,-33,-34,-35,-36,-39,5,-55,-63,5,5,-5,-7,5,5,5,5,5,5,5,5,5,-37,-56,5,5,5,5,5,5,5,-66,-4,-44,-45,-46,-47,5,5,-59,5,-61,5,-64,-65,-15,-38,-50,-49,5,-48,5,5,-72,5,-54,-57,-58,-60,-62,5,-40,5,-67,5,-76,5,-3,-12,-3,-21,-14,-19,-23,5,5,-22,5,-3,-20,]),'NUMBER':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[19,19,-32,-6,-8,-9,-11,-13,19,19,-31,-33,-34,-35,-36,-39,19,-55,-63,19,19,-5,-7,19,19,19,19,19,19,19,19,19,-37,-56,19,19,19,19,19,19,19,-66,-4,-44,-45,-46,-47,19,19,-59,19,-61,19,-64,-65,-15,-38,-50,-49,19,-48,19,19,-72,19,-54,-57,-58,-60,-62,19,-40,19,-67,19,-76,19,-3,-12,-3,-21,-14,-19,-23,19,19,-22,19,-3,-20,]),'BOOL':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[20,20,-32,-6,-8,-9,-11,-13,20,20,-31,-33,-34,-35,-36,-39,20,-55,-63,20,20,-5,-7,20,20,20,20,20,20,20,20,20,-37,-56,20,20,20,20,20,20,20,-66,-4,-44,-45,-46,-47,20,20,-59,20,-61,20,-64,-65,-15,-38,-50,-49,20,-48,20,20,-72,20,-54,-57,-58,-60,-62,20,-40,20,-67,20,-76,20,-3,-12,-3,-21,-14,-19,-23,20,20,-22,20,-3,-20,]),'NULL':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[21,21,-32,-6,-8,-9,-11,-13,21,21,-31,-33,-34,-35,-36,-39,21,-55,-63,21,21,-5,-7,21,21,21,21,21,21,21,21,21,-37,-56,21,21,21,21,21,21,21,-66,-4,-44,-45,-46,-47,21,21,-59,21,-61,21,-64,-65,-15,-38,-50,-49,21,-48,21,21,-72,21,-54,-57,-58,-60,-62,21,-40,21,-67,21,-76,21,-3,-12,-3,-21,-14,-19,-23,21,21,-22,21,-3,-20,]),'ID':([0,2,5,7,9,10,11,12,13,16,17,18,19,20,21,22,24,25,26,28,30,32,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,99,100,101,104,105,106,112,114,116,117,118,119,120,121,123,128,137,139,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[23,23,-32,-6,-8,-9,-11,-13,50,57,60,-31,-33,-34,-35,-36,-39,50,-55,-63,50,76,50,-5,-7,50,50,50,50,50,50,50,50,50,-37,-56,50,50,50,50,50,50,50,-66,-4,-44,-45,-46,-47,50,50,-59,50,-61,50,-64,-65,-15,-38,-50,124,-49,50,-48,50,23,-72,50,124,-54,-57,-58,-60,-62,23,-40,23,60,-67,23,-76,23,-3,-12,-3,-21,-14,-19,-23,50,23,-22,23,-3,-20,]),'LPAREN':([0,2,5,7,9,10,11,12,13,15,16,18,19,20,21,22,23,24,25,26,28,30,31,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,57,63,64,71,73,75,76,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,153,154,155,156,158,159,160,164,165,167,168,],[16,16,-32,-6,-8,-9,-11,-13,16,53,16,-31,-33,-34,-35,-36,63,-39,16,-55,-63,16,75,16,-5,-7,16,16,16,16,16,16,16,16,16,63,-56,16,16,63,16,16,16,16,16,116,-66,-4,-44,-45,-46,-47,16,16,-59,16,-61,16,-64,-65,-15,-38,-50,-49,16,-48,16,16,-72,16,-54,-57,-58,-60,-62,16,-40,16,-67,16,-76,16,-3,-12,-3,159,-21,-14,-19,-23,16,16,-22,16,-3,-20,]),'LBRACKET':([0,2,5,7,8,9,10,11,12,13,16,18,19,20,21,22,23,24,25,26,27,28,30,33,36,37,38,39,40,41,42,45,46,47,48,49,50,51,52,53,54,57,63,64,67,71,73,75,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,94,95,96,97,100,101,103,104,105,106,112,114,115,117,118,119,120,121,123,127,128,129,134,137,141,142,145,148,149,150,152,154,155,156,158,159,160,161,164,165,167,168,],[25,25,-32,-6,38,-8,-9,-11,-13,25,25,-31,-33,-34,-35,-36,64,-39,25,-55,64,-63,25,25,-5,-7,25,25,25,25,25,25,25,25,25,38,-37,-56,25,25,38,64,25,25,38,25,114,25,38,-4,38,-44,-45,-46,-47,25,25,38,25,38,25,38,38,-15,38,38,-38,-50,-49,25,38,-48,25,25,-72,25,38,-54,38,38,38,38,25,38,-40,64,38,25,-67,25,-76,25,-3,-12,-3,-21,-14,-19,-23,25,25,38,-22,25,-3,-20,]),'LBRACE':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,69,70,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,98,100,101,104,105,106,107,108,109,110,112,114,117,118,119,120,121,122,123,128,132,133,135,137,141,142,143,145,148,149,150,152,154,155,156,157,158,159,160,163,164,165,167,168,],[17,17,-32,-6,-8,-9,-11,-13,17,17,-31,-33,-34,-35,-36,-39,17,-55,-63,17,17,-5,-7,17,17,17,17,17,17,17,17,17,-37,-56,17,17,17,17,106,-3,17,17,17,-66,-4,-44,-45,-46,-47,17,17,-59,17,-61,17,-64,-65,-15,-38,-50,123,-49,17,-48,17,17,-3,-68,-3,-71,-72,17,-54,-57,-58,-60,-62,137,17,-40,-70,-69,142,17,-67,17,148,-76,17,-3,-12,-3,-21,-14,-19,160,-23,17,17,165,-22,17,-3,-20,]),'PLACEHOLDER':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,70,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,107,109,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[27,27,-32,-6,-8,-9,-11,-13,51,27,-31,-33,-34,-35,-36,-39,51,-55,-63,51,51,-5,-7,51,51,51,51,51,51,51,51,51,-37,-56,51,51,51,51,109,51,51,51,-66,-4,-44,-45,-46,-47,51,51,-59,51,-61,51,-64,-65,-15,-38,-50,-49,51,-48,51,27,109,109,-72,51,-54,-57,-58,-60,-62,27,-40,27,-67,27,-76,27,-3,-12,-3,-21,-14,-19,-23,51,27,-22,27,-3,-20,]),'MAC':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[29,29,-6,-8,-9,-11,-13,29,-5,-7,-4,-15,29,-72,29,29,-67,29,29,-3,-12,-3,-21,-14,-19,-23,29,-22,29,-3,-20,]),'ATOM':([0,2,5,7,9,10,11,12,16,18,19,20,21,22,24,26,28,29,30,36,37,50,51,70,71,73,77,78,80,81,82,83,86,88,90,91,92,96,97,100,104,106,107,109,112,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,160,164,165,167,168,],[30,30,-32,-6,-8,-9,-11,-13,30,-31,-33,-34,-35,-36,-39,-55,-63,70,71,-5,-7,-37,-56,107,71,71,-66,-4,-44,-45,-46,-47,-59,-61,-64,-65,-15,-38,-50,-49,-48,30,107,107,-72,-54,-57,-58,-60,-62,30,-40,30,-67,30,-76,30,-3,-12,-3,-21,-14,-19,-23,30,-22,30,-3,-20,]),'WHILE':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[31,31,-6,-8,-9,-11,-13,31,-5,-7,-4,-15,31,-72,31,31,-67,31,31,-3,-12,-3,-21,-14,-19,-23,31,-22,31,-3,-20,]),'FUN':([0,2,7,9,10,11,12,16,36,37,78,92,106,112,123,137,141,142,148,149,150,152,154,155,156,158,160,164,165,167,168,],[32,32,-6,-8,-9,-11,-13,32,-5,-7,-4,-15,32,-72,32,32,-67,32,32,-3,-12,-3,-21,-14,-19,-23,32,-22,32,-3,-20,]),'NOT':([0,2,5,7,9,10,11,12,13,16,18,19,20,21,22,24,25,26,28,30,33,36,37,38,39,40,41,42,45,46,47,48,50,51,52,53,63,64,71,73,75,77,78,80,81,82,83,84,85,86,87,88,89,90,91,92,96,97,100,101,104,105,106,112,114,117,118,119,120,121,123,128,137,141,142,145,148,149,150,152,154,155,156,158,159,160,164,165,167,168,],[33,33,-32,-6,-8,-9,-11,-13,33,33,-31,-33,-34,-35,-36,-39,33,-55,-63,33,33,-5,-7,33,33,33,33,33,33,33,33,33,-37,-56,33,33,33,33,33,33,33,-66,-4,-44,-45,-46,-47,33,33,-59,33,-61,33,-64,-65,-15,-38,-50,-49,33,-48,33,33,-72,33,-54,-57,-58,-60,-62,33,-40,33,-67,33,-76,33,-3,-12,-3,-21,-14,-19,-23,33,33,-22,33,-3,-20,]),'RPAREN':([2,3,5,7,9,10,11,12,16,18,19,20,21,22,24,26,27,28,34,36,37,50,51,54,55,56,57,58,63,66,67,77,78,80,81,82,83,86,88,90,91,92,95,96,97,99,100,102,104,105,112,115,116,117,118,119,120,121,124,125,126,128,130,136,141,145,149,150,152,154,155,156,158,161,164,167,168,],[-3,-2,-32,-6,-8,-9,-11,-13,-3,-31,-33,-34,-35,-36,-39,-55,-56,-63,-1,-5,-7,-37,-56,96,97,98,-16,-2,-3,-41,-42,-66,-4,-44,-45,-46,-47,-59,-61,-64,-65,-15,122,-38,-50,-3,-49,128,-48,-3,-72,135,-3,-54,-57,-58,-60,-62,-16,-17,-18,-40,-43,143,-67,-76,-3,-12,-3,-21,-14,-19,-23,163,-22,-3,-20,]),'RBRACE':([2,3,5,7,9,10,11,12,17,18,19,20,21,22,24,26,28,34,36,37,50,51,59,61,77,78,80,81,82,83,86,88,90,91,92,96,97,100,104,106,112,117,118,119,120,121,123,127,128,131,137,138,139,141,142,144,145,146,147,148,149,150,151,152,154,155,156,158,160,162,164,165,166,167,168,],[-3,-2,-32,-6,-8,-9,-11,-13,-3,-31,-33,-34,-35,-36,-39,-55,-63,-1,-5,-7,-37,-56,100,-53,-66,-4,-44,-45,-46,-47,-59,-61,-64,-65,-15,-38,-50,-49,-48,-3,-72,-54,-57,-58,-60,-62,-3,-51,-40,141,-3,145,-3,-67,-3,149,-76,-52,150,-3,-3,-12,155,-3,-21,-14,-19,-23,-3,164,-22,-3,167,-3,-20,]),'SEMICOLON':([5,6,8,18,19,20,21,22,23,24,26,27,28,30,35,49,50,51,54,57,71,72,73,74,77,80,81,82,83,86,88,90,91,93,94,96,97,100,104,111,113,117,118,119,120,121,128,145,],[-32,36,37,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,-3,78,92,-37,-56,37,-37,-3,112,-3,-75,-66,-44,-45,-46,-47,-59,-61,-64,-65,-10,-24,-38,-50,-49,-48,-73,-74,-54,-57,-58,-60,-62,-40,-76,]),'PLUS':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,39,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,39,-37,-56,39,-37,39,39,39,39,-44,-45,-46,-47,39,39,39,39,39,39,-38,-50,-49,39,-48,39,-54,39,39,39,39,39,-40,39,-76,39,]),'MINUS':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,40,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,40,-37,-56,40,-37,40,40,40,40,-44,-45,-46,-47,40,40,40,40,40,40,-38,-50,-49,40,-48,40,-54,40,40,40,40,40,-40,40,-76,40,]),'MULTIPLY':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,41,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,41,-37,-56,41,-37,41,41,41,41,41,41,-46,-47,41,41,41,41,41,41,-38,-50,-49,41,-48,41,-54,41,41,41,41,41,-40,41,-76,41,]),'DIVIDE':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,42,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,42,-37,-56,42,-37,42,42,42,42,42,42,-46,-47,42,42,42,42,42,42,-38,-50,-49,42,-48,42,-54,42,42,42,42,42,-40,42,-76,42,]),'EQUAL':([5,8,14,18,19,20,21,22,23,24,26,27,28,43,44,45,46,49,50,51,54,57,62,67,68,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,129,134,140,145,161,],[-32,43,52,-31,-33,-34,-35,-36,-25,-39,-55,-27,-63,84,85,87,89,43,-37,-56,43,-25,-26,43,-28,43,43,43,-44,-45,-46,-47,43,43,43,43,43,43,-38,-50,-49,43,-48,43,-54,43,43,43,43,43,-40,-29,43,-30,-76,43,]),'BANG':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,44,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,44,-37,-56,44,-37,44,44,44,44,-44,-45,-46,-47,44,44,44,44,44,44,-38,-50,-49,44,-48,44,-54,44,44,44,44,44,-40,44,-76,44,]),'GT':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,45,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,45,-37,-56,45,-37,45,45,45,45,-44,-45,-46,-47,45,45,45,45,45,45,-38,-50,-49,45,-48,45,-54,45,45,45,45,45,-40,45,-76,45,]),'LT':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,46,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,46,-37,-56,46,-37,46,46,46,46,-44,-45,-46,-47,46,46,46,46,46,46,-38,-50,-49,46,-48,46,-54,46,46,46,46,46,-40,46,-76,46,]),'AND':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,47,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,47,-37,-56,47,-37,47,47,47,47,-44,-45,-46,-47,47,47,47,47,47,47,-38,-50,-49,47,-48,47,-54,47,47,47,47,47,-40,47,-76,47,]),'OR':([5,8,18,19,20,21,22,23,24,26,27,28,49,50,51,54,57,67,73,77,79,80,81,82,83,86,88,90,91,94,95,96,97,100,103,104,115,117,118,119,120,121,127,128,134,145,161,],[-32,48,-31,-33,-34,-35,-36,-37,-39,-55,-56,-63,48,-37,-56,48,-37,48,48,48,48,-44,-45,-46,-47,48,48,48,48,48,48,-38,-50,-49,48,-48,48,-54,48,48,48,48,48,-40,48,-76,48,]),'COMMA':([5,18,19,20,21,22,24,26,28,50,51,57,67,77,80,81,82,83,86,88,90,91,96,97,100,104,117,118,119,120,121,124,127,128,134,145,],[-32,-31,-33,-34,-35,-36,-39,-55,-63,-37,-56,99,105,-66,-44,-45,-46,-47,-59,-61,-64,-65,-38,-50,-49,-48,-54,-57,-58,-60,-62,99,139,-40,105,-76,]),'RBRACKET':([5,18,19,20,21,22,24,25,26,28,50,51,65,66,67,77,79,80,81,82,83,86,88,90,91,96,97,100,103,104,105,114,117,118,119,120,121,128,130,134,145,],[-32,-31,-33,-34,-35,-36,-39,-3,-55,-63,-37,-56,104,-41,-42,-66,117,-44,-45,-46,-47,-59,-61,-64,-65,-38,-50,-49,129,-48,-3,-3,-54,-57,-58,-60,-62,-40,-43,117,-76,]),'COLON':([60,],[101,]),'ELIF':([149,167,],[153,153,]),'ELSE':([149,152,154,167,168,],[-3,157,-21,-3,-20,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement_list':([0,2,16,106,123,137,142,148,160,165,],[1,34,55,131,138,144,147,151,162,166,]),'statement':([0,2,16,106,123,137,142,148,160,165,],[2,2,2,2,2,2,2,2,2,2,]),'empty':([0,2,16,17,25,30,63,70,71,73,99,105,106,107,109,114,116,123,137,139,142,148,149,152,160,165,167,],[3,3,58,61,66,74,66,110,74,74,126,66,3,110,110,66,126,3,3,61,3,3,154,158,3,3,154,]),'assignment':([0,2,16,106,123,137,142,148,160,165,],[6,6,6,6,6,6,6,6,6,6,]),'conditional':([0,2,16,106,123,137,142,148,160,165,],[7,7,7,7,7,7,7,7,7,7,]),'expr':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[8,8,49,54,67,73,77,79,80,81,82,83,86,88,90,91,94,95,67,103,73,73,115,118,119,120,121,127,67,8,134,8,8,8,8,161,8,8,]),'macro_def':([0,2,16,106,123,137,142,148,160,165,],[9,9,9,9,9,9,9,9,9,9,]),'macro_call':([0,2,16,106,123,137,142,148,160,165,],[10,10,10,10,10,10,10,10,10,10,]),'loop':([0,2,16,106,123,137,142,148,160,165,],[11,11,11,11,11,11,11,11,11,11,]),'fun_def':([0,2,16,106,123,137,142,148,160,165,],[12,12,12,12,12,12,12,12,12,12,]),'l_value':([0,2,16,106,123,137,142,148,160,165,],[14,14,14,14,14,14,14,14,14,14,]),'alg_op':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,]),'func_call':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,]),'anonymous_fun':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,]),'comp_op':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,]),'log_op':([0,2,13,16,25,30,33,38,39,40,41,42,45,46,47,48,52,53,63,64,71,73,75,84,85,87,89,101,105,106,114,123,137,142,148,159,160,165,],[28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,]),'id_list':([16,99,116,],[56,125,136,]),'record_list':([17,139,],[59,146,]),'fields':([23,27,57,129,],[62,68,62,140,]),'arg_list':([25,63,105,114,],[65,102,130,65,]),'macro_def_arg_list':([29,],[69,]),'macro_arg_list':([30,71,73,],[72,111,113,]),'r_value':([52,],[93,]),'macro_def_arg_list_rec':([70,107,109,],[108,132,133,]),'conditional_elif':([149,167,],[152,168,]),'conditional_else':([152,],[156,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> statement_list","S'",1,None,None,None),
('statement_list -> statement statement_list','statement_list',2,'p_statement_list','parse.py',20),
('statement_list -> empty','statement_list',1,'p_statement_list','parse.py',21),
('empty -> <empty>','empty',0,'p_empty','parse.py',30),
('statement -> IMPORT STRING SEMICOLON','statement',3,'p_statement_import','parse.py',34),
('statement -> assignment SEMICOLON','statement',2,'p_statement_assignment','parse.py',38),
('statement -> conditional','statement',1,'p_statement_conditional','parse.py',42),
('statement -> expr SEMICOLON','statement',2,'p_statement_expr','parse.py',46),
('statement -> macro_def','statement',1,'p_statement_macro_def','parse.py',50),
('statement -> macro_call','statement',1,'p_statement_macro_call','parse.py',54),
('assignment -> l_value EQUAL r_value','assignment',3,'p_assignment','parse.py',58),
('statement -> loop','statement',1,'p_statement_loop','parse.py',62),
('loop -> WHILE LPAREN expr RPAREN LBRACE statement_list RBRACE','loop',7,'p_loop','parse.py',66),
('statement -> fun_def','statement',1,'p_statement_fun_def','parse.py',70),
('fun_def -> FUN ID LPAREN id_list RPAREN LBRACE statement_list RBRACE','fun_def',8,'p_fun_def','parse.py',74),
('statement -> RETURN expr SEMICOLON','statement',3,'p_statement_return','parse.py',78),
('id_list -> ID','id_list',1,'p_id_list_single','parse.py',82),
('id_list -> ID COMMA id_list','id_list',3,'p_id_list_multi','parse.py',86),
('id_list -> empty','id_list',1,'p_id_list_empty','parse.py',90),
('conditional -> IF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif conditional_else','conditional',9,'p_conditional_full','parse.py',94),
('conditional_elif -> ELIF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif','conditional_elif',8,'p_conditional_elif','parse.py',99),
('conditional_elif -> empty','conditional_elif',1,'p_conditional_elif_empty','parse.py',103),
('conditional_else -> ELSE LBRACE statement_list RBRACE','conditional_else',4,'p_conditional_else','parse.py',107),
('conditional_else -> empty','conditional_else',1,'p_conditional_else_empty','parse.py',111),
('r_value -> expr','r_value',1,'p_r_value','parse.py',115),
('l_value -> ID','l_value',1,'p_l_value_id','parse.py',119),
('l_value -> ID fields','l_value',2,'p_l_value_record','parse.py',123),
('l_value -> PLACEHOLDER','l_value',1,'p_l_value_placeholder','parse.py',127),
('l_value -> PLACEHOLDER fields','l_value',2,'p_l_value_placeholder_record','parse.py',131),
('fields -> LBRACKET expr RBRACKET','fields',3,'p_fields_single','parse.py',134),
('fields -> LBRACKET expr RBRACKET fields','fields',4,'p_fields_multi','parse.py',138),
('expr -> alg_op','expr',1,'p_expr','parse.py',142),
('expr -> STRING','expr',1,'p_expr_string','parse.py',146),
('expr -> NUMBER','expr',1,'p_expr_number','parse.py',150),
('expr -> BOOL','expr',1,'p_expr_bool','parse.py',154),
('expr -> NULL','expr',1,'p_expr_null','parse.py',158),
('expr -> func_call','expr',1,'p_expr_func_call','parse.py',162),
('expr -> ID','expr',1,'p_expr_id','parse.py',166),
('expr -> LPAREN expr RPAREN','expr',3,'p_expr_parens','parse.py',170),
('expr -> anonymous_fun','expr',1,'p_expr_anonymous_fun','parse.py',174),
('func_call -> ID LPAREN arg_list RPAREN','func_call',4,'p_func_call','parse.py',178),
('arg_list -> empty','arg_list',1,'p_arg_list_empty','parse.py',182),
('arg_list -> expr','arg_list',1,'p_arg_list_single','parse.py',186),
('arg_list -> expr COMMA arg_list','arg_list',3,'p_arg_list_multi','parse.py',190),
('alg_op -> expr PLUS expr','alg_op',3,'p_alg_op','parse.py',197),
('alg_op -> expr MINUS expr','alg_op',3,'p_alg_op','parse.py',198),
('alg_op -> expr MULTIPLY expr','alg_op',3,'p_alg_op','parse.py',199),
('alg_op -> expr DIVIDE expr','alg_op',3,'p_alg_op','parse.py',200),
('expr -> LBRACKET arg_list RBRACKET','expr',3,'p_expr_list','parse.py',211),
('expr -> LBRACE record_list RBRACE','expr',3,'p_expr_object','parse.py',215),
('expr -> LPAREN statement_list RPAREN','expr',3,'p_expr_sequence','parse.py',219),
('record_list -> ID COLON expr','record_list',3,'p_record_list_single','parse.py',223),
('record_list -> ID COLON expr COMMA record_list','record_list',5,'p_record_list_multi','parse.py',227),
('record_list -> empty','record_list',1,'p_record_list_empty','parse.py',231),
('expr -> expr LBRACKET expr RBRACKET','expr',4,'p_expr_access','parse.py',235),
('expr -> comp_op','expr',1,'p_expr_comp_op','parse.py',239),
('expr -> PLACEHOLDER','expr',1,'p_expr_placeholder','parse.py',243),
('comp_op -> expr EQUAL EQUAL expr','comp_op',4,'p_comp_op_eq','parse.py',247),
('comp_op -> expr BANG EQUAL expr','comp_op',4,'p_comp_op_neq','parse.py',251),
('comp_op -> expr GT expr','comp_op',3,'p_comp_op_gt','parse.py',255),
('comp_op -> expr GT EQUAL expr','comp_op',4,'p_comp_op_gte','parse.py',259),
('comp_op -> expr LT expr','comp_op',3,'p_comp_op_lt','parse.py',263),
('comp_op -> expr LT EQUAL expr','comp_op',4,'p_comp_op_lte','parse.py',267),
('expr -> log_op','expr',1,'p_expr_log_op','parse.py',271),
('log_op -> expr AND expr','log_op',3,'p_log_op_and','parse.py',275),
('log_op -> expr OR expr','log_op',3,'p_log_op_or','parse.py',279),
('log_op -> NOT expr','log_op',2,'p_log_op_not','parse.py',283),
('macro_def -> MAC macro_def_arg_list LBRACE statement_list RBRACE','macro_def',5,'p_macro_def','parse.py',287),
('macro_def_arg_list -> ATOM macro_def_arg_list_rec','macro_def_arg_list',2,'p_macro_def_arg_list_start_atom','parse.py',291),
('macro_def_arg_list_rec -> PLACEHOLDER macro_def_arg_list_rec','macro_def_arg_list_rec',2,'p_macro_def_arg_list_rec_placeholder','parse.py',295),
('macro_def_arg_list_rec -> ATOM macro_def_arg_list_rec','macro_def_arg_list_rec',2,'p_macro_def_arg_list_rec_atom','parse.py',299),
('macro_def_arg_list_rec -> empty','macro_def_arg_list_rec',1,'p_macro_def_arg_list_rec_empty','parse.py',303),
('macro_call -> ATOM macro_arg_list SEMICOLON','macro_call',3,'p_macro_call_atom_start','parse.py',307),
('macro_arg_list -> ATOM macro_arg_list','macro_arg_list',2,'p_macro_call_arg_list_atom','parse.py',311),
('macro_arg_list -> expr macro_arg_list','macro_arg_list',2,'p_macro_call_arg_list_expr','parse.py',315),
('macro_arg_list -> empty','macro_arg_list',1,'p_macro_call_arg_list_empty','parse.py',319),
('anonymous_fun -> LPAREN id_list RPAREN LBRACE statement_list RBRACE','anonymous_fun',6,'p_anonymous_fun','parse.py',323),
]
|
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULTIPLY NOT NULL NUMBER OR PLACEHOLDER PLUS RBRACE RBRACKET RETURN RPAREN SEMICOLON STRING WHILEstatement_list : statement statement_list\n | emptyempty :statement : IMPORT STRING SEMICOLONstatement : assignment SEMICOLONstatement : conditionalstatement : expr SEMICOLONstatement : macro_defstatement : macro_callassignment : l_value EQUAL r_valuestatement : looploop : WHILE LPAREN expr RPAREN LBRACE statement_list RBRACEstatement : fun_deffun_def : FUN ID LPAREN id_list RPAREN LBRACE statement_list RBRACEstatement : RETURN expr SEMICOLONid_list : IDid_list : ID COMMA id_listid_list : emptyconditional : IF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif conditional_elseconditional_elif : ELIF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elifconditional_elif : emptyconditional_else : ELSE LBRACE statement_list RBRACEconditional_else : emptyr_value : exprl_value : IDl_value : ID fieldsl_value : PLACEHOLDERl_value : PLACEHOLDER fieldsfields : LBRACKET expr RBRACKETfields : LBRACKET expr RBRACKET fieldsexpr : alg_opexpr : STRINGexpr : NUMBERexpr : BOOLexpr : NULLexpr : func_callexpr : IDexpr : LPAREN expr RPARENexpr : anonymous_fun func_call : ID LPAREN arg_list RPARENarg_list : emptyarg_list : exprarg_list : expr COMMA arg_listalg_op : expr PLUS expr\n | expr MINUS expr\n | expr MULTIPLY expr\n | expr DIVIDE exprexpr : LBRACKET arg_list RBRACKETexpr : LBRACE record_list RBRACEexpr : LPAREN statement_list RPARENrecord_list : ID COLON exprrecord_list : ID COLON expr COMMA record_listrecord_list : emptyexpr : expr LBRACKET expr RBRACKETexpr : comp_opexpr : PLACEHOLDERcomp_op : expr EQUAL EQUAL exprcomp_op : expr BANG EQUAL exprcomp_op : expr GT exprcomp_op : expr GT EQUAL exprcomp_op : expr LT exprcomp_op : expr LT EQUAL exprexpr : log_oplog_op : expr AND exprlog_op : expr OR exprlog_op : NOT exprmacro_def : MAC macro_def_arg_list LBRACE statement_list RBRACEmacro_def_arg_list : ATOM macro_def_arg_list_recmacro_def_arg_list_rec : PLACEHOLDER macro_def_arg_list_recmacro_def_arg_list_rec : ATOM macro_def_arg_list_recmacro_def_arg_list_rec : emptymacro_call : ATOM macro_arg_list SEMICOLONmacro_arg_list : ATOM macro_arg_listmacro_arg_list : expr macro_arg_listmacro_arg_list : emptyanonymous_fun : LPAREN id_list RPAREN LBRACE statement_list RBRACE'
_lr_action_items = {'IMPORT': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [4, 4, -6, -8, -9, -11, -13, 4, -5, -7, -4, -15, 4, -72, 4, 4, -67, 4, 4, -3, -12, -3, -21, -14, -19, -23, 4, -22, 4, -3, -20]), 'RETURN': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [13, 13, -6, -8, -9, -11, -13, 13, -5, -7, -4, -15, 13, -72, 13, 13, -67, 13, 13, -3, -12, -3, -21, -14, -19, -23, 13, -22, 13, -3, -20]), '$end': ([0, 1, 2, 3, 7, 9, 10, 11, 12, 34, 36, 37, 78, 92, 112, 141, 149, 150, 152, 154, 155, 156, 158, 164, 167, 168], [-3, 0, -3, -2, -6, -8, -9, -11, -13, -1, -5, -7, -4, -15, -72, -67, -3, -12, -3, -21, -14, -19, -23, -22, -3, -20]), 'IF': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [15, 15, -6, -8, -9, -11, -13, 15, -5, -7, -4, -15, 15, -72, 15, 15, -67, 15, 15, -3, -12, -3, -21, -14, -19, -23, 15, -22, 15, -3, -20]), 'STRING': ([0, 2, 4, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [5, 5, 35, -32, -6, -8, -9, -11, -13, 5, 5, -31, -33, -34, -35, -36, -39, 5, -55, -63, 5, 5, -5, -7, 5, 5, 5, 5, 5, 5, 5, 5, 5, -37, -56, 5, 5, 5, 5, 5, 5, 5, -66, -4, -44, -45, -46, -47, 5, 5, -59, 5, -61, 5, -64, -65, -15, -38, -50, -49, 5, -48, 5, 5, -72, 5, -54, -57, -58, -60, -62, 5, -40, 5, -67, 5, -76, 5, -3, -12, -3, -21, -14, -19, -23, 5, 5, -22, 5, -3, -20]), 'NUMBER': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [19, 19, -32, -6, -8, -9, -11, -13, 19, 19, -31, -33, -34, -35, -36, -39, 19, -55, -63, 19, 19, -5, -7, 19, 19, 19, 19, 19, 19, 19, 19, 19, -37, -56, 19, 19, 19, 19, 19, 19, 19, -66, -4, -44, -45, -46, -47, 19, 19, -59, 19, -61, 19, -64, -65, -15, -38, -50, -49, 19, -48, 19, 19, -72, 19, -54, -57, -58, -60, -62, 19, -40, 19, -67, 19, -76, 19, -3, -12, -3, -21, -14, -19, -23, 19, 19, -22, 19, -3, -20]), 'BOOL': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [20, 20, -32, -6, -8, -9, -11, -13, 20, 20, -31, -33, -34, -35, -36, -39, 20, -55, -63, 20, 20, -5, -7, 20, 20, 20, 20, 20, 20, 20, 20, 20, -37, -56, 20, 20, 20, 20, 20, 20, 20, -66, -4, -44, -45, -46, -47, 20, 20, -59, 20, -61, 20, -64, -65, -15, -38, -50, -49, 20, -48, 20, 20, -72, 20, -54, -57, -58, -60, -62, 20, -40, 20, -67, 20, -76, 20, -3, -12, -3, -21, -14, -19, -23, 20, 20, -22, 20, -3, -20]), 'NULL': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [21, 21, -32, -6, -8, -9, -11, -13, 21, 21, -31, -33, -34, -35, -36, -39, 21, -55, -63, 21, 21, -5, -7, 21, 21, 21, 21, 21, 21, 21, 21, 21, -37, -56, 21, 21, 21, 21, 21, 21, 21, -66, -4, -44, -45, -46, -47, 21, 21, -59, 21, -61, 21, -64, -65, -15, -38, -50, -49, 21, -48, 21, 21, -72, 21, -54, -57, -58, -60, -62, 21, -40, 21, -67, 21, -76, 21, -3, -12, -3, -21, -14, -19, -23, 21, 21, -22, 21, -3, -20]), 'ID': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 32, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 99, 100, 101, 104, 105, 106, 112, 114, 116, 117, 118, 119, 120, 121, 123, 128, 137, 139, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [23, 23, -32, -6, -8, -9, -11, -13, 50, 57, 60, -31, -33, -34, -35, -36, -39, 50, -55, -63, 50, 76, 50, -5, -7, 50, 50, 50, 50, 50, 50, 50, 50, 50, -37, -56, 50, 50, 50, 50, 50, 50, 50, -66, -4, -44, -45, -46, -47, 50, 50, -59, 50, -61, 50, -64, -65, -15, -38, -50, 124, -49, 50, -48, 50, 23, -72, 50, 124, -54, -57, -58, -60, -62, 23, -40, 23, 60, -67, 23, -76, 23, -3, -12, -3, -21, -14, -19, -23, 50, 23, -22, 23, -3, -20]), 'LPAREN': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 30, 31, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 57, 63, 64, 71, 73, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 153, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [16, 16, -32, -6, -8, -9, -11, -13, 16, 53, 16, -31, -33, -34, -35, -36, 63, -39, 16, -55, -63, 16, 75, 16, -5, -7, 16, 16, 16, 16, 16, 16, 16, 16, 16, 63, -56, 16, 16, 63, 16, 16, 16, 16, 16, 116, -66, -4, -44, -45, -46, -47, 16, 16, -59, 16, -61, 16, -64, -65, -15, -38, -50, -49, 16, -48, 16, 16, -72, 16, -54, -57, -58, -60, -62, 16, -40, 16, -67, 16, -76, 16, -3, -12, -3, 159, -21, -14, -19, -23, 16, 16, -22, 16, -3, -20]), 'LBRACKET': ([0, 2, 5, 7, 8, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 57, 63, 64, 67, 71, 73, 75, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 100, 101, 103, 104, 105, 106, 112, 114, 115, 117, 118, 119, 120, 121, 123, 127, 128, 129, 134, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 161, 164, 165, 167, 168], [25, 25, -32, -6, 38, -8, -9, -11, -13, 25, 25, -31, -33, -34, -35, -36, 64, -39, 25, -55, 64, -63, 25, 25, -5, -7, 25, 25, 25, 25, 25, 25, 25, 25, 25, 38, -37, -56, 25, 25, 38, 64, 25, 25, 38, 25, 114, 25, 38, -4, 38, -44, -45, -46, -47, 25, 25, 38, 25, 38, 25, 38, 38, -15, 38, 38, -38, -50, -49, 25, 38, -48, 25, 25, -72, 25, 38, -54, 38, 38, 38, 38, 25, 38, -40, 64, 38, 25, -67, 25, -76, 25, -3, -12, -3, -21, -14, -19, -23, 25, 25, 38, -22, 25, -3, -20]), 'LBRACE': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 69, 70, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 98, 100, 101, 104, 105, 106, 107, 108, 109, 110, 112, 114, 117, 118, 119, 120, 121, 122, 123, 128, 132, 133, 135, 137, 141, 142, 143, 145, 148, 149, 150, 152, 154, 155, 156, 157, 158, 159, 160, 163, 164, 165, 167, 168], [17, 17, -32, -6, -8, -9, -11, -13, 17, 17, -31, -33, -34, -35, -36, -39, 17, -55, -63, 17, 17, -5, -7, 17, 17, 17, 17, 17, 17, 17, 17, 17, -37, -56, 17, 17, 17, 17, 106, -3, 17, 17, 17, -66, -4, -44, -45, -46, -47, 17, 17, -59, 17, -61, 17, -64, -65, -15, -38, -50, 123, -49, 17, -48, 17, 17, -3, -68, -3, -71, -72, 17, -54, -57, -58, -60, -62, 137, 17, -40, -70, -69, 142, 17, -67, 17, 148, -76, 17, -3, -12, -3, -21, -14, -19, 160, -23, 17, 17, 165, -22, 17, -3, -20]), 'PLACEHOLDER': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 70, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 107, 109, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [27, 27, -32, -6, -8, -9, -11, -13, 51, 27, -31, -33, -34, -35, -36, -39, 51, -55, -63, 51, 51, -5, -7, 51, 51, 51, 51, 51, 51, 51, 51, 51, -37, -56, 51, 51, 51, 51, 109, 51, 51, 51, -66, -4, -44, -45, -46, -47, 51, 51, -59, 51, -61, 51, -64, -65, -15, -38, -50, -49, 51, -48, 51, 27, 109, 109, -72, 51, -54, -57, -58, -60, -62, 27, -40, 27, -67, 27, -76, 27, -3, -12, -3, -21, -14, -19, -23, 51, 27, -22, 27, -3, -20]), 'MAC': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [29, 29, -6, -8, -9, -11, -13, 29, -5, -7, -4, -15, 29, -72, 29, 29, -67, 29, 29, -3, -12, -3, -21, -14, -19, -23, 29, -22, 29, -3, -20]), 'ATOM': ([0, 2, 5, 7, 9, 10, 11, 12, 16, 18, 19, 20, 21, 22, 24, 26, 28, 29, 30, 36, 37, 50, 51, 70, 71, 73, 77, 78, 80, 81, 82, 83, 86, 88, 90, 91, 92, 96, 97, 100, 104, 106, 107, 109, 112, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [30, 30, -32, -6, -8, -9, -11, -13, 30, -31, -33, -34, -35, -36, -39, -55, -63, 70, 71, -5, -7, -37, -56, 107, 71, 71, -66, -4, -44, -45, -46, -47, -59, -61, -64, -65, -15, -38, -50, -49, -48, 30, 107, 107, -72, -54, -57, -58, -60, -62, 30, -40, 30, -67, 30, -76, 30, -3, -12, -3, -21, -14, -19, -23, 30, -22, 30, -3, -20]), 'WHILE': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [31, 31, -6, -8, -9, -11, -13, 31, -5, -7, -4, -15, 31, -72, 31, 31, -67, 31, 31, -3, -12, -3, -21, -14, -19, -23, 31, -22, 31, -3, -20]), 'FUN': ([0, 2, 7, 9, 10, 11, 12, 16, 36, 37, 78, 92, 106, 112, 123, 137, 141, 142, 148, 149, 150, 152, 154, 155, 156, 158, 160, 164, 165, 167, 168], [32, 32, -6, -8, -9, -11, -13, 32, -5, -7, -4, -15, 32, -72, 32, 32, -67, 32, 32, -3, -12, -3, -21, -14, -19, -23, 32, -22, 32, -3, -20]), 'NOT': ([0, 2, 5, 7, 9, 10, 11, 12, 13, 16, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 33, 36, 37, 38, 39, 40, 41, 42, 45, 46, 47, 48, 50, 51, 52, 53, 63, 64, 71, 73, 75, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 96, 97, 100, 101, 104, 105, 106, 112, 114, 117, 118, 119, 120, 121, 123, 128, 137, 141, 142, 145, 148, 149, 150, 152, 154, 155, 156, 158, 159, 160, 164, 165, 167, 168], [33, 33, -32, -6, -8, -9, -11, -13, 33, 33, -31, -33, -34, -35, -36, -39, 33, -55, -63, 33, 33, -5, -7, 33, 33, 33, 33, 33, 33, 33, 33, 33, -37, -56, 33, 33, 33, 33, 33, 33, 33, -66, -4, -44, -45, -46, -47, 33, 33, -59, 33, -61, 33, -64, -65, -15, -38, -50, -49, 33, -48, 33, 33, -72, 33, -54, -57, -58, -60, -62, 33, -40, 33, -67, 33, -76, 33, -3, -12, -3, -21, -14, -19, -23, 33, 33, -22, 33, -3, -20]), 'RPAREN': ([2, 3, 5, 7, 9, 10, 11, 12, 16, 18, 19, 20, 21, 22, 24, 26, 27, 28, 34, 36, 37, 50, 51, 54, 55, 56, 57, 58, 63, 66, 67, 77, 78, 80, 81, 82, 83, 86, 88, 90, 91, 92, 95, 96, 97, 99, 100, 102, 104, 105, 112, 115, 116, 117, 118, 119, 120, 121, 124, 125, 126, 128, 130, 136, 141, 145, 149, 150, 152, 154, 155, 156, 158, 161, 164, 167, 168], [-3, -2, -32, -6, -8, -9, -11, -13, -3, -31, -33, -34, -35, -36, -39, -55, -56, -63, -1, -5, -7, -37, -56, 96, 97, 98, -16, -2, -3, -41, -42, -66, -4, -44, -45, -46, -47, -59, -61, -64, -65, -15, 122, -38, -50, -3, -49, 128, -48, -3, -72, 135, -3, -54, -57, -58, -60, -62, -16, -17, -18, -40, -43, 143, -67, -76, -3, -12, -3, -21, -14, -19, -23, 163, -22, -3, -20]), 'RBRACE': ([2, 3, 5, 7, 9, 10, 11, 12, 17, 18, 19, 20, 21, 22, 24, 26, 28, 34, 36, 37, 50, 51, 59, 61, 77, 78, 80, 81, 82, 83, 86, 88, 90, 91, 92, 96, 97, 100, 104, 106, 112, 117, 118, 119, 120, 121, 123, 127, 128, 131, 137, 138, 139, 141, 142, 144, 145, 146, 147, 148, 149, 150, 151, 152, 154, 155, 156, 158, 160, 162, 164, 165, 166, 167, 168], [-3, -2, -32, -6, -8, -9, -11, -13, -3, -31, -33, -34, -35, -36, -39, -55, -63, -1, -5, -7, -37, -56, 100, -53, -66, -4, -44, -45, -46, -47, -59, -61, -64, -65, -15, -38, -50, -49, -48, -3, -72, -54, -57, -58, -60, -62, -3, -51, -40, 141, -3, 145, -3, -67, -3, 149, -76, -52, 150, -3, -3, -12, 155, -3, -21, -14, -19, -23, -3, 164, -22, -3, 167, -3, -20]), 'SEMICOLON': ([5, 6, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 30, 35, 49, 50, 51, 54, 57, 71, 72, 73, 74, 77, 80, 81, 82, 83, 86, 88, 90, 91, 93, 94, 96, 97, 100, 104, 111, 113, 117, 118, 119, 120, 121, 128, 145], [-32, 36, 37, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, -3, 78, 92, -37, -56, 37, -37, -3, 112, -3, -75, -66, -44, -45, -46, -47, -59, -61, -64, -65, -10, -24, -38, -50, -49, -48, -73, -74, -54, -57, -58, -60, -62, -40, -76]), 'PLUS': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 39, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 39, -37, -56, 39, -37, 39, 39, 39, 39, -44, -45, -46, -47, 39, 39, 39, 39, 39, 39, -38, -50, -49, 39, -48, 39, -54, 39, 39, 39, 39, 39, -40, 39, -76, 39]), 'MINUS': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 40, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 40, -37, -56, 40, -37, 40, 40, 40, 40, -44, -45, -46, -47, 40, 40, 40, 40, 40, 40, -38, -50, -49, 40, -48, 40, -54, 40, 40, 40, 40, 40, -40, 40, -76, 40]), 'MULTIPLY': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 41, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 41, -37, -56, 41, -37, 41, 41, 41, 41, 41, 41, -46, -47, 41, 41, 41, 41, 41, 41, -38, -50, -49, 41, -48, 41, -54, 41, 41, 41, 41, 41, -40, 41, -76, 41]), 'DIVIDE': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 42, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 42, -37, -56, 42, -37, 42, 42, 42, 42, 42, 42, -46, -47, 42, 42, 42, 42, 42, 42, -38, -50, -49, 42, -48, 42, -54, 42, 42, 42, 42, 42, -40, 42, -76, 42]), 'EQUAL': ([5, 8, 14, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 43, 44, 45, 46, 49, 50, 51, 54, 57, 62, 67, 68, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 129, 134, 140, 145, 161], [-32, 43, 52, -31, -33, -34, -35, -36, -25, -39, -55, -27, -63, 84, 85, 87, 89, 43, -37, -56, 43, -25, -26, 43, -28, 43, 43, 43, -44, -45, -46, -47, 43, 43, 43, 43, 43, 43, -38, -50, -49, 43, -48, 43, -54, 43, 43, 43, 43, 43, -40, -29, 43, -30, -76, 43]), 'BANG': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 44, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 44, -37, -56, 44, -37, 44, 44, 44, 44, -44, -45, -46, -47, 44, 44, 44, 44, 44, 44, -38, -50, -49, 44, -48, 44, -54, 44, 44, 44, 44, 44, -40, 44, -76, 44]), 'GT': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 45, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 45, -37, -56, 45, -37, 45, 45, 45, 45, -44, -45, -46, -47, 45, 45, 45, 45, 45, 45, -38, -50, -49, 45, -48, 45, -54, 45, 45, 45, 45, 45, -40, 45, -76, 45]), 'LT': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 46, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 46, -37, -56, 46, -37, 46, 46, 46, 46, -44, -45, -46, -47, 46, 46, 46, 46, 46, 46, -38, -50, -49, 46, -48, 46, -54, 46, 46, 46, 46, 46, -40, 46, -76, 46]), 'AND': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 47, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 47, -37, -56, 47, -37, 47, 47, 47, 47, -44, -45, -46, -47, 47, 47, 47, 47, 47, 47, -38, -50, -49, 47, -48, 47, -54, 47, 47, 47, 47, 47, -40, 47, -76, 47]), 'OR': ([5, 8, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 49, 50, 51, 54, 57, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 96, 97, 100, 103, 104, 115, 117, 118, 119, 120, 121, 127, 128, 134, 145, 161], [-32, 48, -31, -33, -34, -35, -36, -37, -39, -55, -56, -63, 48, -37, -56, 48, -37, 48, 48, 48, 48, -44, -45, -46, -47, 48, 48, 48, 48, 48, 48, -38, -50, -49, 48, -48, 48, -54, 48, 48, 48, 48, 48, -40, 48, -76, 48]), 'COMMA': ([5, 18, 19, 20, 21, 22, 24, 26, 28, 50, 51, 57, 67, 77, 80, 81, 82, 83, 86, 88, 90, 91, 96, 97, 100, 104, 117, 118, 119, 120, 121, 124, 127, 128, 134, 145], [-32, -31, -33, -34, -35, -36, -39, -55, -63, -37, -56, 99, 105, -66, -44, -45, -46, -47, -59, -61, -64, -65, -38, -50, -49, -48, -54, -57, -58, -60, -62, 99, 139, -40, 105, -76]), 'RBRACKET': ([5, 18, 19, 20, 21, 22, 24, 25, 26, 28, 50, 51, 65, 66, 67, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 96, 97, 100, 103, 104, 105, 114, 117, 118, 119, 120, 121, 128, 130, 134, 145], [-32, -31, -33, -34, -35, -36, -39, -3, -55, -63, -37, -56, 104, -41, -42, -66, 117, -44, -45, -46, -47, -59, -61, -64, -65, -38, -50, -49, 129, -48, -3, -3, -54, -57, -58, -60, -62, -40, -43, 117, -76]), 'COLON': ([60], [101]), 'ELIF': ([149, 167], [153, 153]), 'ELSE': ([149, 152, 154, 167, 168], [-3, 157, -21, -3, -20])}
_lr_action = {}
for (_k, _v) in _lr_action_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement_list': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [1, 34, 55, 131, 138, 144, 147, 151, 162, 166]), 'statement': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), 'empty': ([0, 2, 16, 17, 25, 30, 63, 70, 71, 73, 99, 105, 106, 107, 109, 114, 116, 123, 137, 139, 142, 148, 149, 152, 160, 165, 167], [3, 3, 58, 61, 66, 74, 66, 110, 74, 74, 126, 66, 3, 110, 110, 66, 126, 3, 3, 61, 3, 3, 154, 158, 3, 3, 154]), 'assignment': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]), 'conditional': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [7, 7, 7, 7, 7, 7, 7, 7, 7, 7]), 'expr': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [8, 8, 49, 54, 67, 73, 77, 79, 80, 81, 82, 83, 86, 88, 90, 91, 94, 95, 67, 103, 73, 73, 115, 118, 119, 120, 121, 127, 67, 8, 134, 8, 8, 8, 8, 161, 8, 8]), 'macro_def': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]), 'macro_call': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]), 'loop': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [11, 11, 11, 11, 11, 11, 11, 11, 11, 11]), 'fun_def': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [12, 12, 12, 12, 12, 12, 12, 12, 12, 12]), 'l_value': ([0, 2, 16, 106, 123, 137, 142, 148, 160, 165], [14, 14, 14, 14, 14, 14, 14, 14, 14, 14]), 'alg_op': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18]), 'func_call': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22]), 'anonymous_fun': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24]), 'comp_op': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26]), 'log_op': ([0, 2, 13, 16, 25, 30, 33, 38, 39, 40, 41, 42, 45, 46, 47, 48, 52, 53, 63, 64, 71, 73, 75, 84, 85, 87, 89, 101, 105, 106, 114, 123, 137, 142, 148, 159, 160, 165], [28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28]), 'id_list': ([16, 99, 116], [56, 125, 136]), 'record_list': ([17, 139], [59, 146]), 'fields': ([23, 27, 57, 129], [62, 68, 62, 140]), 'arg_list': ([25, 63, 105, 114], [65, 102, 130, 65]), 'macro_def_arg_list': ([29], [69]), 'macro_arg_list': ([30, 71, 73], [72, 111, 113]), 'r_value': ([52], [93]), 'macro_def_arg_list_rec': ([70, 107, 109], [108, 132, 133]), 'conditional_elif': ([149, 167], [152, 168]), 'conditional_else': ([152], [156])}
_lr_goto = {}
for (_k, _v) in _lr_goto_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> statement_list", "S'", 1, None, None, None), ('statement_list -> statement statement_list', 'statement_list', 2, 'p_statement_list', 'parse.py', 20), ('statement_list -> empty', 'statement_list', 1, 'p_statement_list', 'parse.py', 21), ('empty -> <empty>', 'empty', 0, 'p_empty', 'parse.py', 30), ('statement -> IMPORT STRING SEMICOLON', 'statement', 3, 'p_statement_import', 'parse.py', 34), ('statement -> assignment SEMICOLON', 'statement', 2, 'p_statement_assignment', 'parse.py', 38), ('statement -> conditional', 'statement', 1, 'p_statement_conditional', 'parse.py', 42), ('statement -> expr SEMICOLON', 'statement', 2, 'p_statement_expr', 'parse.py', 46), ('statement -> macro_def', 'statement', 1, 'p_statement_macro_def', 'parse.py', 50), ('statement -> macro_call', 'statement', 1, 'p_statement_macro_call', 'parse.py', 54), ('assignment -> l_value EQUAL r_value', 'assignment', 3, 'p_assignment', 'parse.py', 58), ('statement -> loop', 'statement', 1, 'p_statement_loop', 'parse.py', 62), ('loop -> WHILE LPAREN expr RPAREN LBRACE statement_list RBRACE', 'loop', 7, 'p_loop', 'parse.py', 66), ('statement -> fun_def', 'statement', 1, 'p_statement_fun_def', 'parse.py', 70), ('fun_def -> FUN ID LPAREN id_list RPAREN LBRACE statement_list RBRACE', 'fun_def', 8, 'p_fun_def', 'parse.py', 74), ('statement -> RETURN expr SEMICOLON', 'statement', 3, 'p_statement_return', 'parse.py', 78), ('id_list -> ID', 'id_list', 1, 'p_id_list_single', 'parse.py', 82), ('id_list -> ID COMMA id_list', 'id_list', 3, 'p_id_list_multi', 'parse.py', 86), ('id_list -> empty', 'id_list', 1, 'p_id_list_empty', 'parse.py', 90), ('conditional -> IF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif conditional_else', 'conditional', 9, 'p_conditional_full', 'parse.py', 94), ('conditional_elif -> ELIF LPAREN expr RPAREN LBRACE statement_list RBRACE conditional_elif', 'conditional_elif', 8, 'p_conditional_elif', 'parse.py', 99), ('conditional_elif -> empty', 'conditional_elif', 1, 'p_conditional_elif_empty', 'parse.py', 103), ('conditional_else -> ELSE LBRACE statement_list RBRACE', 'conditional_else', 4, 'p_conditional_else', 'parse.py', 107), ('conditional_else -> empty', 'conditional_else', 1, 'p_conditional_else_empty', 'parse.py', 111), ('r_value -> expr', 'r_value', 1, 'p_r_value', 'parse.py', 115), ('l_value -> ID', 'l_value', 1, 'p_l_value_id', 'parse.py', 119), ('l_value -> ID fields', 'l_value', 2, 'p_l_value_record', 'parse.py', 123), ('l_value -> PLACEHOLDER', 'l_value', 1, 'p_l_value_placeholder', 'parse.py', 127), ('l_value -> PLACEHOLDER fields', 'l_value', 2, 'p_l_value_placeholder_record', 'parse.py', 131), ('fields -> LBRACKET expr RBRACKET', 'fields', 3, 'p_fields_single', 'parse.py', 134), ('fields -> LBRACKET expr RBRACKET fields', 'fields', 4, 'p_fields_multi', 'parse.py', 138), ('expr -> alg_op', 'expr', 1, 'p_expr', 'parse.py', 142), ('expr -> STRING', 'expr', 1, 'p_expr_string', 'parse.py', 146), ('expr -> NUMBER', 'expr', 1, 'p_expr_number', 'parse.py', 150), ('expr -> BOOL', 'expr', 1, 'p_expr_bool', 'parse.py', 154), ('expr -> NULL', 'expr', 1, 'p_expr_null', 'parse.py', 158), ('expr -> func_call', 'expr', 1, 'p_expr_func_call', 'parse.py', 162), ('expr -> ID', 'expr', 1, 'p_expr_id', 'parse.py', 166), ('expr -> LPAREN expr RPAREN', 'expr', 3, 'p_expr_parens', 'parse.py', 170), ('expr -> anonymous_fun', 'expr', 1, 'p_expr_anonymous_fun', 'parse.py', 174), ('func_call -> ID LPAREN arg_list RPAREN', 'func_call', 4, 'p_func_call', 'parse.py', 178), ('arg_list -> empty', 'arg_list', 1, 'p_arg_list_empty', 'parse.py', 182), ('arg_list -> expr', 'arg_list', 1, 'p_arg_list_single', 'parse.py', 186), ('arg_list -> expr COMMA arg_list', 'arg_list', 3, 'p_arg_list_multi', 'parse.py', 190), ('alg_op -> expr PLUS expr', 'alg_op', 3, 'p_alg_op', 'parse.py', 197), ('alg_op -> expr MINUS expr', 'alg_op', 3, 'p_alg_op', 'parse.py', 198), ('alg_op -> expr MULTIPLY expr', 'alg_op', 3, 'p_alg_op', 'parse.py', 199), ('alg_op -> expr DIVIDE expr', 'alg_op', 3, 'p_alg_op', 'parse.py', 200), ('expr -> LBRACKET arg_list RBRACKET', 'expr', 3, 'p_expr_list', 'parse.py', 211), ('expr -> LBRACE record_list RBRACE', 'expr', 3, 'p_expr_object', 'parse.py', 215), ('expr -> LPAREN statement_list RPAREN', 'expr', 3, 'p_expr_sequence', 'parse.py', 219), ('record_list -> ID COLON expr', 'record_list', 3, 'p_record_list_single', 'parse.py', 223), ('record_list -> ID COLON expr COMMA record_list', 'record_list', 5, 'p_record_list_multi', 'parse.py', 227), ('record_list -> empty', 'record_list', 1, 'p_record_list_empty', 'parse.py', 231), ('expr -> expr LBRACKET expr RBRACKET', 'expr', 4, 'p_expr_access', 'parse.py', 235), ('expr -> comp_op', 'expr', 1, 'p_expr_comp_op', 'parse.py', 239), ('expr -> PLACEHOLDER', 'expr', 1, 'p_expr_placeholder', 'parse.py', 243), ('comp_op -> expr EQUAL EQUAL expr', 'comp_op', 4, 'p_comp_op_eq', 'parse.py', 247), ('comp_op -> expr BANG EQUAL expr', 'comp_op', 4, 'p_comp_op_neq', 'parse.py', 251), ('comp_op -> expr GT expr', 'comp_op', 3, 'p_comp_op_gt', 'parse.py', 255), ('comp_op -> expr GT EQUAL expr', 'comp_op', 4, 'p_comp_op_gte', 'parse.py', 259), ('comp_op -> expr LT expr', 'comp_op', 3, 'p_comp_op_lt', 'parse.py', 263), ('comp_op -> expr LT EQUAL expr', 'comp_op', 4, 'p_comp_op_lte', 'parse.py', 267), ('expr -> log_op', 'expr', 1, 'p_expr_log_op', 'parse.py', 271), ('log_op -> expr AND expr', 'log_op', 3, 'p_log_op_and', 'parse.py', 275), ('log_op -> expr OR expr', 'log_op', 3, 'p_log_op_or', 'parse.py', 279), ('log_op -> NOT expr', 'log_op', 2, 'p_log_op_not', 'parse.py', 283), ('macro_def -> MAC macro_def_arg_list LBRACE statement_list RBRACE', 'macro_def', 5, 'p_macro_def', 'parse.py', 287), ('macro_def_arg_list -> ATOM macro_def_arg_list_rec', 'macro_def_arg_list', 2, 'p_macro_def_arg_list_start_atom', 'parse.py', 291), ('macro_def_arg_list_rec -> PLACEHOLDER macro_def_arg_list_rec', 'macro_def_arg_list_rec', 2, 'p_macro_def_arg_list_rec_placeholder', 'parse.py', 295), ('macro_def_arg_list_rec -> ATOM macro_def_arg_list_rec', 'macro_def_arg_list_rec', 2, 'p_macro_def_arg_list_rec_atom', 'parse.py', 299), ('macro_def_arg_list_rec -> empty', 'macro_def_arg_list_rec', 1, 'p_macro_def_arg_list_rec_empty', 'parse.py', 303), ('macro_call -> ATOM macro_arg_list SEMICOLON', 'macro_call', 3, 'p_macro_call_atom_start', 'parse.py', 307), ('macro_arg_list -> ATOM macro_arg_list', 'macro_arg_list', 2, 'p_macro_call_arg_list_atom', 'parse.py', 311), ('macro_arg_list -> expr macro_arg_list', 'macro_arg_list', 2, 'p_macro_call_arg_list_expr', 'parse.py', 315), ('macro_arg_list -> empty', 'macro_arg_list', 1, 'p_macro_call_arg_list_empty', 'parse.py', 319), ('anonymous_fun -> LPAREN id_list RPAREN LBRACE statement_list RBRACE', 'anonymous_fun', 6, 'p_anonymous_fun', 'parse.py', 323)]
|
#!/usr/bin/env python3
NUMBER_OF_MARKS = 5
def avg(numbers):
return sum(numbers) / len(numbers)
def valid_mark(mark):
return 0 <= mark <= 100
def read_marks(number_of_marks):
marks_read = []
for count in range(number_of_marks):
while True:
mark = int(input(f'Enter mark #{count + 1}: '))
if valid_mark(mark):
break
else:
print('Mark out of range. Try again.')
marks_read.append(mark)
return marks_read
def letter_grade(mark):
if mark > 70:
return 'A'
elif mark > 60:
return 'B'
elif mark > 50:
return 'C'
elif mark > 40:
return 'D'
else:
return 'F'
def print_results(marks):
print()
print(f'Maximum Mark: {max(marks)}')
print(f'Minimum Mark: {min(marks)}')
print(f'Average Mark: {avg(marks):.2f}')
print()
print(f'Grade: {letter_grade(avg(marks))}')
if __name__ == '__main__':
mark_list = read_marks(NUMBER_OF_MARKS)
print_results(mark_list)
|
number_of_marks = 5
def avg(numbers):
return sum(numbers) / len(numbers)
def valid_mark(mark):
return 0 <= mark <= 100
def read_marks(number_of_marks):
marks_read = []
for count in range(number_of_marks):
while True:
mark = int(input(f'Enter mark #{count + 1}: '))
if valid_mark(mark):
break
else:
print('Mark out of range. Try again.')
marks_read.append(mark)
return marks_read
def letter_grade(mark):
if mark > 70:
return 'A'
elif mark > 60:
return 'B'
elif mark > 50:
return 'C'
elif mark > 40:
return 'D'
else:
return 'F'
def print_results(marks):
print()
print(f'Maximum Mark: {max(marks)}')
print(f'Minimum Mark: {min(marks)}')
print(f'Average Mark: {avg(marks):.2f}')
print()
print(f'Grade: {letter_grade(avg(marks))}')
if __name__ == '__main__':
mark_list = read_marks(NUMBER_OF_MARKS)
print_results(mark_list)
|
class Vertex:
'''This class will create Vertex of Graph, include methods
add neighbours(v) and rem_neighbor(v)'''
def __init__(self, n): # To initiate instance Graph Vertex
self.name = n
self.neighbors = list()
self.color = 'black'
def add_neighbor(self, v): # To add neighbour in graph
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
def rem_neighbor(self, v): # To remove neighbor in graph
if v in self.neighbors:
self.neighbors.remove(v)
class Graph:
'''This Graph Class will implement Graph using adjacency list include
methods add vertex, add edge and dfs triversal that print Vertax label using
adjacency list '''
vertices = {} # create directory
def add_vertex(self, vertex): # To add vertex
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False
def add_edge(self, src, dst): # To add Edges
if src in self.vertices and dst in self.vertices:
for key, value in self.vertices.items():
if key == src:
value.add_neighbor(dst)
if key == dst:
value.add_neighbor(src)
return True
else:
return False
def rem_edge(self, src, dst): # To remove Edges
if src in self.vertices and dst in self.vertices:
self.vertices[src].rem_neighbor(dst)
self.vertices[dst].rem_neighbor(src)
print("Edges removed from {} to {}".format(src, dst))
return True
else:
return False
def dfs(self, vertex): # dfs Triversal
vertex.color = 'blue'
for v in vertex.neighbors:
if self.vertices[v].color == 'black':
self.dfs(self.vertices[v])
vertex.color = 'blue'
if vertex.color == 'blue':
for key in sorted(list(self.vertices.keys())):
print(key + str(self.vertices[key].neighbors))
|
class Vertex:
"""This class will create Vertex of Graph, include methods
add neighbours(v) and rem_neighbor(v)"""
def __init__(self, n):
self.name = n
self.neighbors = list()
self.color = 'black'
def add_neighbor(self, v):
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
def rem_neighbor(self, v):
if v in self.neighbors:
self.neighbors.remove(v)
class Graph:
"""This Graph Class will implement Graph using adjacency list include
methods add vertex, add edge and dfs triversal that print Vertax label using
adjacency list """
vertices = {}
def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False
def add_edge(self, src, dst):
if src in self.vertices and dst in self.vertices:
for (key, value) in self.vertices.items():
if key == src:
value.add_neighbor(dst)
if key == dst:
value.add_neighbor(src)
return True
else:
return False
def rem_edge(self, src, dst):
if src in self.vertices and dst in self.vertices:
self.vertices[src].rem_neighbor(dst)
self.vertices[dst].rem_neighbor(src)
print('Edges removed from {} to {}'.format(src, dst))
return True
else:
return False
def dfs(self, vertex):
vertex.color = 'blue'
for v in vertex.neighbors:
if self.vertices[v].color == 'black':
self.dfs(self.vertices[v])
vertex.color = 'blue'
if vertex.color == 'blue':
for key in sorted(list(self.vertices.keys())):
print(key + str(self.vertices[key].neighbors))
|
"""
https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/
Tags: Weekly-Contest_281; Brute-Force; Easy
"""
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for i in range(1, num + 1):
s = str(i)
# Digit Sum
sm = sum(map(int, s))
if sm % 2 == 0:
ans += 1
return ans
|
"""
https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/
Tags: Weekly-Contest_281; Brute-Force; Easy
"""
class Solution:
def count_even(self, num: int) -> int:
ans = 0
for i in range(1, num + 1):
s = str(i)
sm = sum(map(int, s))
if sm % 2 == 0:
ans += 1
return ans
|
"""191. Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/
"""
class Solution:
def hammingWeight(self, n: int) -> int:
def low_bit(x: int) -> int:
return x & -x
ans = 0
while n != 0:
n -= low_bit(n)
ans += 1
return ans
|
"""191. Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/
"""
class Solution:
def hamming_weight(self, n: int) -> int:
def low_bit(x: int) -> int:
return x & -x
ans = 0
while n != 0:
n -= low_bit(n)
ans += 1
return ans
|
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4, 1, 1, 1, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 5, 1, 1, 1, 4, 1, 1, 5, 1, 1, 5, 3, 3, 5, 3, 1, 1,
1, 4, 1, 1, 1, 1, 1, 1, 5, 3, 1, 2, 1, 1, 1, 4, 1, 3, 1, 5, 1, 1, 2, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 4, 3, 2, 1, 2, 4, 1, 3, 1, 5, 1, 2, 1, 4, 1, 1, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1, 3, 1, 3, 3, 1, 4, 3, 4, 1, 1, 1, 1, 5, 1, 3, 3, 2, 5, 3, 1, 1, 3, 1, 3, 1, 1, 1, 1, 4, 1, 1, 1, 1, 3, 1, 5, 1, 1, 1, 4, 4, 1, 1, 5, 5, 2, 4, 5, 1, 1, 1, 1, 5, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1]
new_num = 8
reset_num = 6
def getFishCounts(input):
fishes = [0] * (new_num + 1)
for i in input:
fishes[i] += 1
return fishes
def simDay(fishes):
newFishes = [0] * (new_num + 1)
# Move counters down
for i in range(0, new_num):
newFishes[i] = fishes[i + 1]
# Move the zeros back to 7
newFishes[reset_num] += fishes[0]
# Create new fishes
newFishes[8] = fishes[0]
return newFishes
def runSim(input, days):
fishes = getFishCounts(input)
for d in range(days):
fishes = simDay(fishes)
# print(f'Day: {d}: ', fishes)
return sum(fishes)
if __name__ == '__main__':
# test = runSim([3, 4, 3, 1, 2], 80)
# print(test)
isPart1 = False
if isPart1:
total = runSim(input, 80)
print('The answer is:', total)
else:
total = runSim(input, 256)
print('The answer is:', total)
# else:
# total = findWorstVents(filename, False)
# print('The answer is:', total)
|
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4, 1, 1, 1, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 5, 1, 1, 1, 4, 1, 1, 5, 1, 1, 5, 3, 3, 5, 3, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 5, 3, 1, 2, 1, 1, 1, 4, 1, 3, 1, 5, 1, 1, 2, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 4, 3, 2, 1, 2, 4, 1, 3, 1, 5, 1, 2, 1, 4, 1, 1, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1, 3, 1, 3, 3, 1, 4, 3, 4, 1, 1, 1, 1, 5, 1, 3, 3, 2, 5, 3, 1, 1, 3, 1, 3, 1, 1, 1, 1, 4, 1, 1, 1, 1, 3, 1, 5, 1, 1, 1, 4, 4, 1, 1, 5, 5, 2, 4, 5, 1, 1, 1, 1, 5, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1]
new_num = 8
reset_num = 6
def get_fish_counts(input):
fishes = [0] * (new_num + 1)
for i in input:
fishes[i] += 1
return fishes
def sim_day(fishes):
new_fishes = [0] * (new_num + 1)
for i in range(0, new_num):
newFishes[i] = fishes[i + 1]
newFishes[reset_num] += fishes[0]
newFishes[8] = fishes[0]
return newFishes
def run_sim(input, days):
fishes = get_fish_counts(input)
for d in range(days):
fishes = sim_day(fishes)
return sum(fishes)
if __name__ == '__main__':
is_part1 = False
if isPart1:
total = run_sim(input, 80)
print('The answer is:', total)
else:
total = run_sim(input, 256)
print('The answer is:', total)
|
def none_check(value):
if value is None:
return False
else:
return True
def is_empty(any_type_value):
if any_type_value:
return False
else:
return True
|
def none_check(value):
if value is None:
return False
else:
return True
def is_empty(any_type_value):
if any_type_value:
return False
else:
return True
|
"""
Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# Class to represent a graph
# This class must have the following interface:
# Constructor creates an empty graph, no parameters.
# addVertex(value) adds vertex to the graph
# addEdge(v1, v2, weight) adds edge from v1 to v2 with a certain weight
# getWeight(v1, v2) returns weight of an edge between v1 and v2, if the edge does not exist returns -1
# Dijkstra algorithm will be added in future
|
"""
Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
|
"""lesson6/solution_simple_functions.py
Contains solutions for simple functions.
"""
# Exercise 1: Write a function that prints your name and try calling it.
# Work in this file and not in the Python shell. Defining functions in
# a Python shell is difficult. Remember to name your function something
# that indicates its purpose.
def print_my_name():
print("Vinay Mayar")
print_my_name()
# Exercise 2: Write a function that uses your function from Exercise 1
# to print your name 10 times.
def print_my_name_ten_times():
for ctr in range(10):
print_my_name()
print_my_name_ten_times()
|
"""lesson6/solution_simple_functions.py
Contains solutions for simple functions.
"""
def print_my_name():
print('Vinay Mayar')
print_my_name()
def print_my_name_ten_times():
for ctr in range(10):
print_my_name()
print_my_name_ten_times()
|
# Link class
class Link:
## Constructor ##
def __init__(self, text = "None", url = "None", status_code = 000): # Not the keyword 'None' so it will still print something
# Dictionary of URL-related content
self.text = text
self.url = url
self.status_code = status_code
# Trims the inside of a string (removing extra whitespace between words)
def trim_inner(self, text):
return " ".join( [string.strip() for string in text.split()] ) # Separate the indiv. words and trim them individually
## OVERLOADS ##
# String representation of the 'Link' class
def __str__(self):
# Format: status code, hyperlinked text, then url (CSV)
text = self.trim_inner(self.text) # Trim internal whitespace;
if not text: # If the string is blank,
text = "N/A" # Give it some text
return f"{self.status_code}, {text}, {self.url}"
# Relational Operators, compared by status code for sorting
# > (less than)
def __lt__(self, other):
return self.status_code < other.status_code
# >= (less than or equal to)
def __le__(self, other):
return self.status_code <= other.status_code
# == (is equal to)
def __eq__(self, other):
return self.staus_code == other.status_code
# != (is not equal to)
def __ne__(self, other):
return self.status_code != other.status_code
# < (greater than)
def __gt__(self, other):
return self.status_code > other.status_code
# <= (greater than or equal to)
def __ge__(self, other):
return self.status_code >= other.status_code
# End of Link class
|
class Link:
def __init__(self, text='None', url='None', status_code=0):
self.text = text
self.url = url
self.status_code = status_code
def trim_inner(self, text):
return ' '.join([string.strip() for string in text.split()])
def __str__(self):
text = self.trim_inner(self.text)
if not text:
text = 'N/A'
return f'{self.status_code}, {text}, {self.url}'
def __lt__(self, other):
return self.status_code < other.status_code
def __le__(self, other):
return self.status_code <= other.status_code
def __eq__(self, other):
return self.staus_code == other.status_code
def __ne__(self, other):
return self.status_code != other.status_code
def __gt__(self, other):
return self.status_code > other.status_code
def __ge__(self, other):
return self.status_code >= other.status_code
|
# -*- coding: utf-8 -*-
"""Manages custom event formatter helpers."""
class FormattersManager(object):
"""Custom event formatter helpers manager."""
_custom_formatter_helpers = {}
@classmethod
def GetEventFormatterHelper(cls, identifier):
"""Retrieves a custom event formatter helper.
Args:
identifier (str): identifier.
Returns:
CustomEventFormatterHelper: custom event formatter or None if not
available.
"""
identifier = identifier.lower()
return cls._custom_formatter_helpers.get(identifier)
@classmethod
def RegisterEventFormatterHelper(cls, formatter_helper_class):
"""Registers a custom event formatter helper.
The custom event formatter helpers are identified based on their lower
case identifier.
Args:
formatter_helper_class (type): class of the custom event formatter helper.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding identifier.
"""
identifier = formatter_helper_class.IDENTIFIER.lower()
if identifier in cls._custom_formatter_helpers:
raise KeyError((
'Custom event formatter helper already set for identifier: '
'{0:s}.').format(formatter_helper_class.IDENTIFIER))
cls._custom_formatter_helpers[identifier] = formatter_helper_class()
@classmethod
def RegisterEventFormatterHelpers(cls, formatter_helper_classes):
"""Registers custom event formatter helpers.
The formatter classes are identified based on their lower case data type.
Args:
formatter_helper_classes (list[type]): classes of the custom event
formatter helpers.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding data type.
"""
for formatter_helper_class in formatter_helper_classes:
cls.RegisterEventFormatterHelper(formatter_helper_class)
|
"""Manages custom event formatter helpers."""
class Formattersmanager(object):
"""Custom event formatter helpers manager."""
_custom_formatter_helpers = {}
@classmethod
def get_event_formatter_helper(cls, identifier):
"""Retrieves a custom event formatter helper.
Args:
identifier (str): identifier.
Returns:
CustomEventFormatterHelper: custom event formatter or None if not
available.
"""
identifier = identifier.lower()
return cls._custom_formatter_helpers.get(identifier)
@classmethod
def register_event_formatter_helper(cls, formatter_helper_class):
"""Registers a custom event formatter helper.
The custom event formatter helpers are identified based on their lower
case identifier.
Args:
formatter_helper_class (type): class of the custom event formatter helper.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding identifier.
"""
identifier = formatter_helper_class.IDENTIFIER.lower()
if identifier in cls._custom_formatter_helpers:
raise key_error('Custom event formatter helper already set for identifier: {0:s}.'.format(formatter_helper_class.IDENTIFIER))
cls._custom_formatter_helpers[identifier] = formatter_helper_class()
@classmethod
def register_event_formatter_helpers(cls, formatter_helper_classes):
"""Registers custom event formatter helpers.
The formatter classes are identified based on their lower case data type.
Args:
formatter_helper_classes (list[type]): classes of the custom event
formatter helpers.
Raises:
KeyError: if a custom formatter helper is already set for the
corresponding data type.
"""
for formatter_helper_class in formatter_helper_classes:
cls.RegisterEventFormatterHelper(formatter_helper_class)
|
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}'
template_close = template_open.replace('{{#','{{/')
kibana_url = (
"{{ctx.metadata.kibana_url}}/app/kibana#/discover?"
"_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,"
"index:'metricbeat-*',key:query,negate:!f,type:custom,value:''),"
"query:(bool:(must:!((regexp:(kubernetes.pod.name:'{{ctx.metadata.regex}}')),"
"(match:(metricset.name:'state_pod')),"
"(match:(kubernetes.namespace:{{ctx.metadata.namespace}}))))))),"
"index:'metricbeat-*',"
"interval:auto,query:(language:lucene,query:''),"
"regexp:(language:lucene,query:'kubernetes.pod.name:test-nginx-%5B%5E-%5D%20-%5B%5E-%5D%20'),"
"sort:!('@timestamp',desc),time:(from:now%2FM,mode:quick,to:now%2FM))"
"&_g=(refreshInterval:(display:Off,pause:!f,value:0),"
"time:(from:now-15m,mode:quick,to:now))"
)
watch_url = "{{ctx.metadata.kibana_url}}/app/management/insightsAndAlerting/watcher/watches/watch/{{ctx.metadata.name}}/status"
slack_alert_template = "{template_open}*<{kibana_url}|{{{{ctx.metadata.name}}}}>* has `{{{{ctx.payload.aggregations.pods.value}}}}` not ready pod(s) <{watch_url}|[ack]>{{{{#ctx.metadata.docs}}}} <{{{{.}}}}|[docs]>{{{{/ctx.metadata.docs}}}}{template_close}".format(**locals())
email_alert_template = "{template_open}<a href=\"{kibana_url}\">{{{{ctx.metadata.name}}}}</a> has {{{{ctx.payload.aggregations.pods.value}}}} not ready pod(s) <a href=\"{watch_url}\">[ack]</a>{{{{#ctx.metadata.docs}}}} <a href=\"{{{{.}}}}\">[docs]</a>{{{{/ctx.metadata.docs}}}}{template_close}".format(**locals())
k8s_template = {
"metadata": {
"name": "",
"namespace": "",
"regex": "",
"kibana_url": "",
"kibana_dashboard": "",
"docs": "",
"xpack" : {
"type" : "json"
},
},
"trigger": {
"schedule": {
"interval": ""
}
},
"input": {
"search": {
"request": {
"search_type": "query_then_fetch",
"indices": [
"metricbeat-*"
],
"rest_total_hits_as_int": True,
"body": {
"aggs": {
"result": {
"top_hits": {
"size": 1
}
},
"pods": {
"cardinality": {
"field": "kubernetes.pod.name"
}
},
"not_ready": {
"terms": {
"field": "kubernetes.pod.name",
"min_doc_count": 12,
"size": 100
}
}
},
"query": {
"bool": {
"must_not": [],
"must": [],
"filter": [
{
"range": {
"@timestamp": {
"gte": "now-{{ctx.metadata.window}}"
}
}
}
]
}
}
}
}
}
},
"condition": {},
"actions": {
"email_admin": {
"throttle_period_in_millis": 300000,
"email": {
"profile": "standard",
"subject": "{{#ctx.payload.aggregations.result.hits.hits.0._source}}{{ctx.metadata.name}} has {{ctx.payload.aggregations.pods.value}} not ready pod(s){{/ctx.payload.aggregations.result.hits.hits.0._source}}",
"body": {
"html": email_alert_template
}
}
},
"notify-slack": {
"throttle_period_in_millis": 300000,
"slack": {
"message": {
"text": slack_alert_template
}
}
}
}
}
metricbeat_template = {
"metadata": {
"window": "300s",
"subject": "No metricbeat data has been recieved in the last 5 minutes!"
},
"trigger": {
"schedule": {
"interval": "60s"
}
},
"input": {
"search": {
"request": {
"search_type": "query_then_fetch",
"indices": [
"metricbeat-*"
],
"rest_total_hits_as_int": True,
"body": {
"query": {
"bool": {
"must": [
{
"match": {
"metricset.name": "state_pod"
}
}
],
"filter": [
{
"range": {
"@timestamp": {
"gte": "now-{{ctx.metadata.window}}"
}
}
}
]
}
}
}
}
}
},
"condition": {
"compare": {
"ctx.payload.hits.total": {
"eq": 0
}
}
},
"actions": {
"email_admin": {
"throttle_period_in_millis": 300000,
"email": {
"profile": "standard",
"subject": "{{ctx.metadata.subject}}",
"body": {
"text": "{{ctx.metadata.message}}"
}
}
},
"notify-slack": {
"throttle_period_in_millis": 300000,
"slack": {
"message": {
"text": "{{ctx.metadata.message}}"
}
}
}
}
}
|
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}'
template_close = template_open.replace('{{#', '{{/')
kibana_url = "{{ctx.metadata.kibana_url}}/app/kibana#/discover?_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'metricbeat-*',key:query,negate:!f,type:custom,value:''),query:(bool:(must:!((regexp:(kubernetes.pod.name:'{{ctx.metadata.regex}}')),(match:(metricset.name:'state_pod')),(match:(kubernetes.namespace:{{ctx.metadata.namespace}}))))))),index:'metricbeat-*',interval:auto,query:(language:lucene,query:''),regexp:(language:lucene,query:'kubernetes.pod.name:test-nginx-%5B%5E-%5D%20-%5B%5E-%5D%20'),sort:!('@timestamp',desc),time:(from:now%2FM,mode:quick,to:now%2FM))&_g=(refreshInterval:(display:Off,pause:!f,value:0),time:(from:now-15m,mode:quick,to:now))"
watch_url = '{{ctx.metadata.kibana_url}}/app/management/insightsAndAlerting/watcher/watches/watch/{{ctx.metadata.name}}/status'
slack_alert_template = '{template_open}*<{kibana_url}|{{{{ctx.metadata.name}}}}>* has `{{{{ctx.payload.aggregations.pods.value}}}}` not ready pod(s) <{watch_url}|[ack]>{{{{#ctx.metadata.docs}}}} <{{{{.}}}}|[docs]>{{{{/ctx.metadata.docs}}}}{template_close}'.format(**locals())
email_alert_template = '{template_open}<a href="{kibana_url}">{{{{ctx.metadata.name}}}}</a> has {{{{ctx.payload.aggregations.pods.value}}}} not ready pod(s) <a href="{watch_url}">[ack]</a>{{{{#ctx.metadata.docs}}}} <a href="{{{{.}}}}">[docs]</a>{{{{/ctx.metadata.docs}}}}{template_close}'.format(**locals())
k8s_template = {'metadata': {'name': '', 'namespace': '', 'regex': '', 'kibana_url': '', 'kibana_dashboard': '', 'docs': '', 'xpack': {'type': 'json'}}, 'trigger': {'schedule': {'interval': ''}}, 'input': {'search': {'request': {'search_type': 'query_then_fetch', 'indices': ['metricbeat-*'], 'rest_total_hits_as_int': True, 'body': {'aggs': {'result': {'top_hits': {'size': 1}}, 'pods': {'cardinality': {'field': 'kubernetes.pod.name'}}, 'not_ready': {'terms': {'field': 'kubernetes.pod.name', 'min_doc_count': 12, 'size': 100}}}, 'query': {'bool': {'must_not': [], 'must': [], 'filter': [{'range': {'@timestamp': {'gte': 'now-{{ctx.metadata.window}}'}}}]}}}}}}, 'condition': {}, 'actions': {'email_admin': {'throttle_period_in_millis': 300000, 'email': {'profile': 'standard', 'subject': '{{#ctx.payload.aggregations.result.hits.hits.0._source}}{{ctx.metadata.name}} has {{ctx.payload.aggregations.pods.value}} not ready pod(s){{/ctx.payload.aggregations.result.hits.hits.0._source}}', 'body': {'html': email_alert_template}}}, 'notify-slack': {'throttle_period_in_millis': 300000, 'slack': {'message': {'text': slack_alert_template}}}}}
metricbeat_template = {'metadata': {'window': '300s', 'subject': 'No metricbeat data has been recieved in the last 5 minutes!'}, 'trigger': {'schedule': {'interval': '60s'}}, 'input': {'search': {'request': {'search_type': 'query_then_fetch', 'indices': ['metricbeat-*'], 'rest_total_hits_as_int': True, 'body': {'query': {'bool': {'must': [{'match': {'metricset.name': 'state_pod'}}], 'filter': [{'range': {'@timestamp': {'gte': 'now-{{ctx.metadata.window}}'}}}]}}}}}}, 'condition': {'compare': {'ctx.payload.hits.total': {'eq': 0}}}, 'actions': {'email_admin': {'throttle_period_in_millis': 300000, 'email': {'profile': 'standard', 'subject': '{{ctx.metadata.subject}}', 'body': {'text': '{{ctx.metadata.message}}'}}}, 'notify-slack': {'throttle_period_in_millis': 300000, 'slack': {'message': {'text': '{{ctx.metadata.message}}'}}}}}
|
c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
|
c = get_config()
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
|
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
complement = {}
out = []
for i,n in enumerate(nums):
complement[target-n] = i
for i,n in enumerate(nums):
idx = complement.get(n, None)
if idx != None and idx != i:
out.append([nums[idx], nums[i]])
return out
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
nums.sort()
out = []
if set(nums) == {0}:
return [[0,0,0]]
i = 0
while len(nums) >= 3:
l_twosum = self.twoSum(nums[1:], -nums[0])
if l_twosum != None:
for l in l_twosum:
l.append(nums[0])
out.append(l)
nums.pop(0)
for i,l in enumerate(out):
out[i] = sorted(l)
out = list(map(list, set(map(tuple, out))))
return out
|
class Solution:
def two_sum(self, nums: List[int], target: int) -> List[List[int]]:
complement = {}
out = []
for (i, n) in enumerate(nums):
complement[target - n] = i
for (i, n) in enumerate(nums):
idx = complement.get(n, None)
if idx != None and idx != i:
out.append([nums[idx], nums[i]])
return out
def three_sum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
nums.sort()
out = []
if set(nums) == {0}:
return [[0, 0, 0]]
i = 0
while len(nums) >= 3:
l_twosum = self.twoSum(nums[1:], -nums[0])
if l_twosum != None:
for l in l_twosum:
l.append(nums[0])
out.append(l)
nums.pop(0)
for (i, l) in enumerate(out):
out[i] = sorted(l)
out = list(map(list, set(map(tuple, out))))
return out
|
#To solve Rat in a maze problem using backtracking
#initializing the size of the maze and soution matrix
N = 4
solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ]
def is_safe(maze, x, y ):
'''A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
'''
if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
return True
return False
def check_if_solution_exists(maze):
if solve_maze(maze) == False:
print("Solution doesn't exist");
return False
# recursive function to solve rat in a maze problem
def solve_maze(maze, x=0,y=0):
'''
This function will make several recursive calls
until we reach to some finding, if we reach to destination
following asafe path, then it prints the solution and return true,
will return false otherwise.
'''
# if (x, y is goal) return True
if x == N - 1 and y == N - 1:
solution_maze[x][y] = 1
print("solution:", solution_maze)
return True
# check if the move is valid
if is_safe(maze, x, y) == True:
# mark x, y as part of solution path
# for(0,0) it sets up 1 in solution maze
solution_maze[x][y] = 1
# Move forward in x direction (recursive call)
if solve_maze(maze, x + 1, y) == True:
return True
# Move down in y direction if moving in x direction is not fruitful
#(recursive call)
if solve_maze(maze, x, y + 1) == True:
return True
#no option for rat to move, backtrack
solution_maze[x][y] = 0
return False
# Driver program to test above function
if __name__ == "__main__":
maze = [ [1, 0, 0, 0],
[1, 1, 0, 1],
[1, 0, 0, 0],
[1, 1, 1, 1] ]
check_if_solution_exists(maze)
|
n = 4
solution_maze = [[0 for j in range(N)] for i in range(N)]
def is_safe(maze, x, y):
"""A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
"""
if x >= 0 and x < N and (y >= 0) and (y < N) and (maze[x][y] == 1):
return True
return False
def check_if_solution_exists(maze):
if solve_maze(maze) == False:
print("Solution doesn't exist")
return False
def solve_maze(maze, x=0, y=0):
"""
This function will make several recursive calls
until we reach to some finding, if we reach to destination
following asafe path, then it prints the solution and return true,
will return false otherwise.
"""
if x == N - 1 and y == N - 1:
solution_maze[x][y] = 1
print('solution:', solution_maze)
return True
if is_safe(maze, x, y) == True:
solution_maze[x][y] = 1
if solve_maze(maze, x + 1, y) == True:
return True
if solve_maze(maze, x, y + 1) == True:
return True
solution_maze[x][y] = 0
return False
if __name__ == '__main__':
maze = [[1, 0, 0, 0], [1, 1, 0, 1], [1, 0, 0, 0], [1, 1, 1, 1]]
check_if_solution_exists(maze)
|
for i in range(2):
print(i) # print 0 then 1
for i in range(4,6):
print (i) # print 4 then 5
"""
Explanation:
If only single argument is passed to the range method,
Python considers this argument as the end of the range and the default start value of range is 0.
So, it will print all the numbers starting from 0 and before the supplied argument.
For the second for loop the starting value is explicitly supplied as 4 and ending is 5.
"""
|
for i in range(2):
print(i)
for i in range(4, 6):
print(i)
'\nExplanation:\nIf only single argument is passed to the range method, \nPython considers this argument as the end of the range and the default start value of range is 0. \nSo, it will print all the numbers starting from 0 and before the supplied argument.\nFor the second for loop the starting value is explicitly supplied as 4 and ending is 5.\n'
|
# called concatenation sometimes..
str1 = 'abra, '
str2 = 'cadabra. '
str3 = 'i wanna reach out and grab ya.'
combo = str1 + str1 + str2 + str3
# you probably don't remember the song.
print(combo)
# you can also do it this way
print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round and round')
# notice the change in single and double quotes. hopefully the change makes sense.
print('not sure why the space for lines 2,3,4 above.', '\n', "i guess there's more to learn... :)")
|
str1 = 'abra, '
str2 = 'cadabra. '
str3 = 'i wanna reach out and grab ya.'
combo = str1 + str1 + str2 + str3
print(combo)
print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round and round')
print('not sure why the space for lines 2,3,4 above.', '\n', "i guess there's more to learn... :)")
|
#!/usr/bin/env python3
"""Initialize.
Turn full names into initials.
Source:
https://edabit.com/challenge/ANsubgd5zPGxov3u8
"""
def __initialize(name: str, period: bool=False) -> str:
"""Turn full name string into a initials string.
Private function used by initialize.
Arguments:
name {[str]} -- Full name to be initialized.
Keyword Arguments:
period {bool} -- Include periods in initials (default: {False})
Returns:
[str] -- Initials string.
"""
if period:
return f"{'.'.join([n[0] for n in name.split(' ')])}."
return ''.join([n[0] for n in name.split(' ')])
def initialize(names: list, **kwargs) ->list:
"""Turn a list of full names into a list of initials.
Arguments:
names {list} -- List of full names, with a space between each name.
Raises:
TypeError -- Check for names is a list.
Returns:
list -- All names initialized.
"""
if isinstance(names, list):
return [__initialize(name.strip(), **kwargs) for name in names if len(name) > 2 and ' ' in name]
else:
raise TypeError('Parameter \'names\' is not a list.')
def main():
"""Run sample initialize function."""
print(initialize(['Peter Parker', 'Steve Rogers', 'Tony Stark']))
print(initialize(
['Bruce Wayne', 'Clark Kent', 'Diana Prince'], period=True))
if __name__ == "__main__":
main()
|
"""Initialize.
Turn full names into initials.
Source:
https://edabit.com/challenge/ANsubgd5zPGxov3u8
"""
def __initialize(name: str, period: bool=False) -> str:
"""Turn full name string into a initials string.
Private function used by initialize.
Arguments:
name {[str]} -- Full name to be initialized.
Keyword Arguments:
period {bool} -- Include periods in initials (default: {False})
Returns:
[str] -- Initials string.
"""
if period:
return f"{'.'.join([n[0] for n in name.split(' ')])}."
return ''.join([n[0] for n in name.split(' ')])
def initialize(names: list, **kwargs) -> list:
"""Turn a list of full names into a list of initials.
Arguments:
names {list} -- List of full names, with a space between each name.
Raises:
TypeError -- Check for names is a list.
Returns:
list -- All names initialized.
"""
if isinstance(names, list):
return [__initialize(name.strip(), **kwargs) for name in names if len(name) > 2 and ' ' in name]
else:
raise type_error("Parameter 'names' is not a list.")
def main():
"""Run sample initialize function."""
print(initialize(['Peter Parker', 'Steve Rogers', 'Tony Stark']))
print(initialize(['Bruce Wayne', 'Clark Kent', 'Diana Prince'], period=True))
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.